# **Chapter 4: Page Events - Handling Browser Requests**
> **File Extension Reference:**
> - Gate Files: `*.gate.php` (e.g., `Blog.gate.php`)
> - Front Files: `*.front` (e.g., `blog_list.front`)
> - Master Files: `*.mast.php` (e.g., `default/master.mast.php`)
> - Front Places: `*.place.front` or `*.place.php`
> **Try it:** All code in this chapter is tested code from the runnable example
> gate `blog` (`apps/examples/Blog.gate.php`). The project runs under the Apache
> webroot as subfolder `SartajPhpDoc`. Open
> `http://localhost/SartajPhpDoc/blog-install.html` once to create the
> `book2_post` table, then `http://localhost/SartajPhpDoc/blog.html`.
---
## **4.1 Understanding Page Events**
Page Events are the methods in your Gate class that handle actual browser requests. Unlike lifecycle events which fire automatically, Page Events are triggered by URLs.
The URL pattern is:
```
gate-event-parameter.html
```
Examples (all live in the `blog` example):
- `blog.html` → Gate: blog, Event: new → `page_new()`
- `blog.html` (POST) → Gate: blog, Event: submit → `page_submit()`
- `blog-view-5.html` → Gate: blog, Event: view, Parameter: 5 → `page_event_view($evtp)`
- `blog-search-php.html` → Gate: blog, Event: search, Parameter: php → `page_event_search($evtp)`
## **4.2 Built-in Page Events**
SartajPhp provides two built-in Page Events: `page_new()` for the landing URL (GET) and `page_submit()` for POST to the landing URL.
### **page_new() - Default Page Load**
Triggered when browser simply loads the Gate landing URL (GET request).
```php
// apps/examples/Blog.gate.php
// URL: blog.html
public function page_new()
{
$this->pageName = 'Blog';
if ($this->client->isRequest('q')) {
$q = $this->client->request('q');
$this->statusMsg = 'Filtered by q=' . $q . ' (use blog-search-KEYWORD.html too)';
} else {
$this->statusMsg = '';
}
// The Pagination Component inside blog_list.front renders the posts
$this->setFrontFile($this->listFront);
}
```
### **page_submit() - Form Submission**
Triggered when a form POSTs to the landing URL. This is the single handler for both insert and update — the form itself knows which mode it is in.
```php
// apps/examples/Blog.gate.php
// URL: blog.html (POST) — one handler for insert AND update
public function page_submit()
{
$form2 = $this->editFront->getComponent('form2');
// HTMLForm::isUpdateRequest() = true when form carries a RecID (edit)
if ($form2->isUpdateRequest()) {
$this->doUpdate($form2);
} else {
$this->doInsert($form2);
}
}
```
`isUpdateRequest()` is true when the submitted form carries its hidden record token
(`form2re`). The framework renders that hidden field for you and encrypts it —
after `$this->page->viewData($form2, $evtp)` fills a record, the same POST is an update;
an empty form is an insert.
### **Insert New Record**
```php
// apps/examples/Blog.gate.php
private function doInsert($form2)
{
global $cmpId;
$extra = array();
$extra[]['userid'] = 0;
$extra[]['parentid'] = 0;
$extra[]['spcmpId'] = $cmpId;
$extra[]['submit_timestamp'] = time();
$extra[]['update_timestamp'] = time();
$id = $this->page->insertData($form2, $extra);
if (!getCheckErr() && $id) {
$this->statusMsg = 'Inserted id=' . $id;
$this->pageName = 'Blog';
$this->setFrontFile($this->listFront);
} else {
setErr('blog', 'Insert failed');
$this->setFrontFile($this->editFront);
}
}
```
`insertData()` collects every Component inside the form that has a `dfield` attribute,
builds the INSERT, executes it, and returns the new record ID. `$extra` adds columns
that have no Component (timestamps, company id). `getCheckErr()` reports validation
errors set by Components or by `setErr()`.
### **Update Existing Record**
```php
// apps/examples/Blog.gate.php
private function doUpdate($form2)
{
$extra = array();
$extra[]['update_timestamp'] = time();
$this->page->updateData($form2, $extra);
if (!getCheckErr()) {
$this->statusMsg = 'Updated id=' . $form2->getRecID();
$this->pageName = 'Blog';
$this->setFrontFile($this->listFront);
} else {
setErr('blog', 'Update failed');
$this->setFrontFile($this->editFront);
}
}
```
`updateData()` uses the form's record ID (`$form2->getRecID()`) as the WHERE key.
### **page_event_view($evtp) - Custom Event for View/Edit Single Record**
```php
// apps/examples/Blog.gate.php
// URL: blog-view-5.html
public function page_event_view($evtp)
{
if ($evtp === '' || $evtp === null) {
$this->page_new();
return;
}
$this->pageName = 'Edit Post';
$this->formButton = 'Update';
$form2 = $this->editFront->getComponent('form2');
// Fill dfield-bound children from table (rec id = event parameter)
$this->page->viewData($form2, $evtp);
$this->setFrontFile($this->editFront);
}
```
### **page_event_delete($evtp) - Custom Page Event for Delete Record**
```php
// apps/examples/Blog.gate.php
// URL: blog-delete-5.html
public function page_event_delete($evtp)
{
if ($evtp !== '' && $evtp !== null) {
// deleteRec() uses the table set by $this->setTableName() in onstart
$this->page->deleteRec($evtp);
$this->statusMsg = 'Deleted id=' . $evtp;
}
$this->pageName = 'Blog';
$this->setFrontFile($this->listFront);
}
```
The table for `viewData/insertData/updateData/deleteRec` is set once in `onstart()`:
```php
// apps/examples/Blog.gate.php
public function onstart()
{
global $masterf;
$this->getAuthenticate('GUEST,MEMBER,ADMIN');
// Default table for Page::insertData / updateData / viewData / deleteRec
$this->setTableName('book2_post');
$this->listFront = new FrontFile('list');
$this->editFront = new FrontFile('edit');
$this->setMasterFile($masterf);
}
```
## **4.3 Custom Page Events**
Create your own events using the `page_event_*` naming pattern. The part of the URL
after the event name arrives as `$evtp`.
### **Parameterized Custom Event (search)**
```php
// apps/examples/Blog.gate.php
// URL: blog-search-KEYWORD.html — $evtp carries the keyword
public function page_event_search($evtp)
{
$this->pageName = 'Search: ' . $evtp;
$this->statusMsg = 'Pagination WHERE set from event parameter';
// Restrict the Pagination component query for this request only
$showall = $this->listFront->getComponent('showall');
$kw = str_replace("'", "''", (string) $evtp);
$showall->fu_setWhere("WHERE txttitle LIKE '%$kw%' ORDER BY id DESC");
$this->setFrontFile($this->listFront);
}
```
Try it: `blog-search-Hello.html` shows only posts whose title contains `Hello`.
### **Multiple Parameter Custom Event**
`$evtp` contains everything after the event name, so encode multiple values yourself:
```php
// URL: shop-filter-electronics-100-500.html
public function page_event_filter($evtp)
{
// $evtp = "electronics-100-500"
$parts = explode('-', $evtp);
$category = $parts[0]; // "electronics"
$minPrice = $parts[1]; // "100"
$maxPrice = $parts[2]; // "500"
$showall = $this->listFront->getComponent('showall');
$showall->fu_setWhere(
"WHERE category='$category' AND price BETWEEN $minPrice AND $maxPrice"
);
$this->setFrontFile($this->listFront);
}
```
### **Empty-Parameter Custom Event (addnew)**
```php
// apps/examples/Blog.gate.php
// URL: blog-addnew.html — empty form (insert mode: form has no RecID)
public function page_event_addnew($evtp)
{
$this->pageName = 'New Post';
$this->formButton = 'Save';
$this->setFrontFile($this->editFront);
}
```
### **AJAX Custom Event**
```php
// Called via AJAX: getAjax('blog', 'checktitle', '5')
public function page_event_checktitle($evtp)
{
// $evtp = "5" - post ID
$stock = $this->page->viewData($this->editFront->getComponent('form2'), $evtp);
// JSON response block for the browser helper
$this->jsServer->addJsonReturnBlock([
"post_id" => $evtp,
"found" => ($stock !== false)
]);
}
```
## **4.4 Getting Request Data**
In your Page Events, access request data using `$this->client` (the Request object;
same as `SphpBase::sphpRequest()` outside a Gate).
### **GET Parameters**
```php
public function page_new()
{
// From URL: blog.html?q=php
if ($this->client->isRequest('q')) {
$q = $this->client->request('q'); // "php"
}
}
```
### **POST Parameters (Form Data)**
```php
public function page_submit()
{
$title = $this->client->post('txttitle'); // text field
$body = $this->client->post('txabody'); // textarea
}
```
### **All Request Types**
```php
public function page_new()
{
// Get any parameter (GET or POST)
$value = $this->client->request('param');
// Get Raw POST data without security filtering, same as $_POST["json1"]
$rawData = $this->client->post('json1', true);
// Check if parameter exists
if ($this->client->isRequest('search')) {
// do search
}
}
```
## **4.5 Sending Responses**
### **HTML Response (Most Common)**
```php
public function page_new()
{
// Set FrontFile to render (merged with Master File)
$this->setFrontFile($this->listFront);
}
```
### **JSON/AJAX Response**
```php
public function page_event_checkstock($evtp)
{
// Send JSON data
$this->jsServer->addJsonReturnBlock([
"success" => true,
"stock" => 50
]);
// Or update an HTML element by component id
$this->jsServer->addJsonHtmlBlock("divStatus", "In Stock!");
// Or execute JavaScript in the browser
$this->jsServer->addJsonJsBlock("$('#btnBuy').prop('disabled', false);");
}
```
### **Redirect Response**
```php
public function page_submit()
{
// After processing, redirect to another page
$this->page->forward(getGateUrl("blog"));
// Or redirect with event
$this->page->forward(getEventUrl("view", $newId));
}
```
## **4.6 Complete Example - Blog Application**
The complete tested Gate (list, install, addnew, view, search, submit, delete):
```php
<?php
// apps/examples/Blog.gate.php
use Sphp\Gates\BasicGate;
use Sphp\Tools\FrontFile;
class Blog extends BasicGate
{
/** @var FrontFile list page */
public $listFront = null;
/** @var FrontFile edit form */
public $editFront = null;
/** @var string heading shown by both fronts */
public $pageName = 'Blog';
/** @var string status line shown on list */
public $statusMsg = '';
/** @var string Save / Update button caption */
public $formButton = 'Save';
public function onstart()
{
global $masterf;
$this->getAuthenticate('GUEST,MEMBER,ADMIN');
$this->setTableName('book2_post');
$this->listFront = new FrontFile('list');
$this->editFront = new FrontFile('edit');
$this->setMasterFile($masterf);
}
public function page_new() { /* list — see 4.2 */ }
public function page_event_install($evtp)
{
$db = $this->dbEngine;
$db->connect();
include_once(SphpBase::sphpSettings()->getProjectPath() . '/db/db_book2.php');
$db->disconnect();
$this->statusMsg = 'Installed book2 tables (db/db_book2.php)';
$this->setFrontFile($this->listFront);
}
public function page_event_addnew($evtp) { /* empty form — see 4.3 */ }
public function page_event_view($evtp) { /* viewData — see 4.2 */ }
public function page_event_search($evtp) { /* fu_setWhere — see 4.3 */ }
public function page_submit() { /* isUpdateRequest — see 4.2 */ }
public function page_event_delete($evtp) { /* deleteRec — see 4.2 */ }
}
```
The list FrontFile (`apps/examples/fronts/blog_list.front`) uses the Pagination
Component so `page_new()` needs no query code at all:
```html
<!-- apps/examples/fronts/blog_list.front (excerpt) -->
<tbody id="showall" runat="server" path="uikit/data/Pagination.php"
fun-setFieldNames="id,txttitle,update_timestamp"
dtable="book2_post"
fun-setPerPageRows="10"
fun-setWhere=" ORDER BY id DESC ">
<tr>
<td runas="holder" sphp-comp="showall" dfield="id"></td>
<td runas="holder" sphp-comp="showall" dfield="txttitle"></td>
<td>##{date('Y-m-d H:i', intval($showall->getRow('update_timestamp')))}#</td>
<td>
<a href="##{getEventUrl('view', $showall->getRow('id'))}#">Edit</a>
|
<a href="##{getEventUrl('delete', $showall->getRow('id'))}#"
onclick="return confirm('Delete?');">Del</a>
</td>
</tr>
</tbody>
<div id="pagebar">##{$showall->getPageBar()}#</div>
```
## **4.7 URL Mapping Reference**
| URL | Gate | Event | Parameter | Page Event Called | Parameter Access |
|-----|------|-------|-----------|-------------------|------------------|
| `blog.html` | blog | new | - | `page_new()` | `$this->client->request('q')` for query string |
| `blog.html` (POST) | blog | submit | - | `page_submit()` → insert or update via `isUpdateRequest()` | form components / `$form2->getRecID()` |
| `blog-view-5.html` | blog | view | 5 | `page_event_view($evtp)` | `$evtp = "5"` (also `$this->page->evtp`) |
| `blog-search-php.html` | blog | search | php | `page_event_search($evtp)` | `$evtp = "php"` |
| `blog-addnew.html` | blog | addnew | - | `page_event_addnew($evtp)` | `$evtp = ""` |
| `blog-delete-5.html` | blog | delete | 5 | `page_event_delete($evtp)` | `$evtp = "5"` |
**Note:** Built-in events are `page_new` and `page_submit`. Custom events
(`page_event_*`) receive `$evtp` directly as a method parameter; it is also readable
as `$this->page->evtp`.
## **4.8 Chapter Summary**
1. **Page Events** handle browser requests mapped from URLs
2. **Built-in events**: `page_new()` (GET landing URL), `page_submit()` (POST landing URL)
3. **Insert vs update**: one `page_submit()` + `$form->isUpdateRequest()`; save with
`$this->page->insertData($form, $extra)` / `updateData($form, $extra)`
4. **Custom events**: `page_event_name($evtp)` — everything after the event name in the URL
5. **Get data**: `$this->client->request()`, `$this->client->post()`, `$this->client->isRequest()`
6. **Send responses**: `setFrontFile()`, `jsServer->addJson*Block()` for AJAX, `page->forward()` for redirect
## **4.9 What's Next?**
In the next chapter, you'll learn about FrontFile Events - how to interact with your templates from within your Gate class.
---
*Next: Chapter 5 - FrontFile Events: Interacting with Templates*