Documentation

On this page

Download full book (text)

# **Chapter 7: Two Front Files Pattern - Pagination and Edit Form** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Product.gate.php`) > - Front Files: `*.front` (e.g., `product_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 `product` (`apps/examples/Product.gate.php`). Open > `http://localhost/SartajPhpDoc/product-install.html` once, then > `http://localhost/SartajPhpDoc/product.html`. --- ## **7.1 The Two Front Files Pattern** A common pattern in SartajPhp is using **two Front Files** in one Gate: 1. **List Front File** - Displays data with Pagination Component 2. **Edit Front File** - Form for inserting/updating records This pattern provides: - Clean separation between viewing and editing - Reusable pagination for any table - Automatic database operations - Built-in form validation ## **7.2 When to Use This Pattern** Use when your application needs: - List view with pagination - Add new record functionality - Edit existing record functionality - Delete functionality ## **7.3 Step 1: Register the Gate** ```php <?php // reg.php registerGate("product", __DIR__ . "/apps/examples/Product.gate.php"); ``` ## **7.4 Step 2: Create the Gate Class** ```php <?php // apps/examples/Product.gate.php use Sphp\Gates\BasicGate; use Sphp\Tools\FrontFile; class Product extends BasicGate { /** @var FrontFile list with Pagination */ public $listFront = null; /** @var FrontFile add/edit form */ public $editFront = null; public $pageName = 'Products'; public $statusMsg = ''; public $formButton = 'Save'; public function onstart() { global $masterf; $this->getAuthenticate('GUEST,MEMBER,ADMIN'); $this->setTableName('book2_product'); $this->listFront = new FrontFile('list'); $this->editFront = new FrontFile('edit'); $this->setMasterFile($masterf); } // Page Events below } ``` ## **7.5 Step 3: Create List Front File with Pagination** Create `apps/examples/fronts/product_list.front`: ```html <!-- apps/examples/fronts/product_list.front --> <title id="title1" runat="server">Products — List</title> <h1>##{$parentGate->pageName}#</h1> <p class="text-muted small"> Table <code>book2_product</code> · Pagination + AJAX · Status: <code>##{$parentGate->statusMsg}#</code> </p> <p> <a class="btn btn-sm btn-primary" href="##{getEventUrl('install')}#">Install schema</a> <a class="btn btn-sm btn-success" href="##{getEventUrl('create')}#">Add Product</a> <a class="btn btn-sm btn-outline-secondary" href="##{getGateUrl('product')}#">Reload</a> </p> <p class="small text-danger">##{raw:traceError(true)}#</p> <table class="table table-striped table-sm"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th>Category</th> <th></th> </tr> </thead> <!-- fun-setAJAX = paging without full page reload --> <tbody id="showall" runat="server" path="uikit/data/Pagination.php" fun-setFieldNames="id,txtname,numprice,sltcategory" dtable="book2_product" fun-setPerPageRows="5" fun-setAJAX="" fun-setWhere=" ORDER BY id DESC "> <tr> <td runas="holder" sphp-comp="showall" dfield="id"></td> <td runas="holder" sphp-comp="showall" dfield="txtname"></td> <td>$##{$showall->getRow('numprice')}#</td> <td>##{$showall->getRow('sltcategory')}#</td> <td> <a href="##{getEventUrl('edit', $showall->getRow('id'))}#">Edit</a> | <a href="##{getEventUrl('delete', $showall->getRow('id'))}#" onclick="return confirm('Delete?');">Del</a> </td> </tr> </tbody> </table> <!-- Holder reads Component property page_links --> <div id="pagebar" runas="holder" sphp-comp="showall" sphp-comp-prop="page_links"></div> ``` ### **How the Pagination Component works** The `<tbody id="showall" runat="server" path="uikit/data/Pagination.php">` tag becomes a Pagination Component. Its inner markup is a **row template** — the framework repeats it once per database row: | Attribute / syntax | Purpose | |--------------------|---------| | `dtable` | Database table to page through | | `fun-setFieldNames` | Fields to SELECT (comma-separated) | | `fun-setPerPageRows` | Rows per page | | `fun-setWhere` | Extra ORDER BY / WHERE SQL | | `fun-setAJAX` | Page links update via AJAX (no reload) | | `runas="holder" sphp-comp="showall" dfield="id"` | Row cell filled with current row field | | `##{$showall->getRow('numprice')}#` | Expression reading current row field | | `sphp-comp-prop="page_links"` | Page-number links rendered by the Component | Two equivalent ways to print a row value inside the template: - Holder cell: `<td runas="holder" sphp-comp="showall" dfield="txtname"></td>` - Expression: `##{$showall->getRow('txtname')}#` ## **7.6 Step 4: Create Edit Front File with Form** Create `apps/examples/fronts/product_edit.front`: ```html <!-- apps/examples/fronts/product_edit.front --> <title id="title1" runat="server">Product — Form</title> <h1>##{$parentGate->pageName}#</h1> <p><a href="##{getGateUrl('product')}#">Back to list</a></p> <p class="small text-danger">##{raw:traceError(true)}#</p> <form id="form2" runat="server" method="post" action="##{getThisGateUrl()}#" class="mb-4"> <div class="mb-3"> <label class="form-label">Product Name *</label> <input id="txtname" runat="server" type="text" class="form-control" dfield="txtname" dtable="book2_product" fui-setForm="form2" fun-setRequired="" fun-setMsgName="Name" /> </div> <div class="mb-3"> <label class="form-label">Price *</label> <input id="numprice" runat="server" type="number" step="0.01" class="form-control" dfield="numprice" dtable="book2_product" fui-setForm="form2" fun-setRequired="" fun-setMsgName="Price" /> </div> <div class="mb-3"> <label class="form-label">Category</label> <select id="sltcategory" runat="server" class="form-select" dfield="sltcategory" dtable="book2_product" fui-setForm="form2" fun-setOptions="Electronics=Electronics,Clothing=Clothing,Books=Books,Home=Home"></select> </div> <div class="mb-3"> <label class="form-label">Description</label> <textarea id="txadescription" runat="server" class="form-control" rows="4" dfield="txadescription" dtable="book2_product" fui-setForm="form2"></textarea> </div> <button type="submit" class="btn btn-primary">##{$parentGate->formButton}#</button> <a href="##{getGateUrl('product')}#" class="btn btn-secondary">Cancel</a> </form> ``` ### **Key Form Component Attributes:** | Attribute | Purpose | |-----------|---------| | `dtable` | Database table to bind to | | `dfield` | Database field name | | `fui-setForm` | Bind to form for validation (init phase) | | `fun-setRequired` | Field is required (render phase) | | `fun-setMsgName` | Label used in validation error messages | | `fun-setOptions` | Dropdown options `value=Label,...` | The form posts to `##{getThisGateUrl()}#` — the Gate landing URL — so the POST lands in `page_submit()`. The framework adds a hidden record token automatically; you never render the record id yourself. ## **7.7 Step 5: Add Page Events to Handle Everything** ```php <?php // apps/examples/Product.gate.php — Page Events /** URL: product.html — list with pagination */ public function page_new() { $this->pageName = 'Products'; $this->setFrontFile($this->listFront); } /** URL: product-install.html — create table from db/db_book2.php */ 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); } /** URL: product-create.html — empty form for new record */ public function page_event_create($evtp) { $this->pageName = 'Add Product'; $this->formButton = 'Save'; $this->setFrontFile($this->editFront); } /** URL: product-edit-5.html — form populated with existing data */ public function page_event_edit($evtp) { if ($evtp === '' || $evtp === null) { $this->page_new(); return; } $this->pageName = 'Edit Product'; $this->formButton = 'Update'; $form2 = $this->editFront->getComponent('form2'); $this->page->viewData($form2, $evtp); $this->setFrontFile($this->editFront); } /** URL: product.html (POST) — insert or update */ public function page_submit() { $form2 = $this->editFront->getComponent('form2'); if ($form2->isUpdateRequest()) { $extra = array(); $extra[]['update_timestamp'] = time(); $this->page->updateData($form2, $extra); $ok = !getCheckErr(); $this->statusMsg = $ok ? 'Updated id=' . $form2->getRecID() : 'Update failed'; } else { 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); $ok = !getCheckErr() && $id; $this->statusMsg = $ok ? 'Inserted id=' . $id : 'Insert failed'; } if ($ok) { $this->pageName = 'Products'; $this->setFrontFile($this->listFront); } else { setErr('product', 'Save failed'); $this->setFrontFile($this->editFront); } } /** URL: product-delete-5.html */ public function page_event_delete($evtp) { if ($evtp !== '' && $evtp !== null) { $this->page->deleteRec($evtp); $this->statusMsg = 'Deleted id=' . $evtp; } $this->pageName = 'Products'; $this->setFrontFile($this->listFront); } ``` ## **7.8 URL Mapping Summary** | URL | Event | Action | |-----|-------|--------| | `product.html` | page_new | Show list with pagination | | `product.html` (POST) | page_submit | Save form (insert or update via `isUpdateRequest()`) | | `product-create.html` | page_event_create | Show empty form | | `product-edit-5.html` | page_event_edit | Show populated form | | `product-delete-5.html` | page_event_delete | Delete record | | `product-install.html` | page_event_install | Create table | ## **7.9 How Database Operations Work** ### **Automatic Insert** ```php // Collects form Components with dfield/dtable and inserts $this->page->insertData($form2, $extra); ``` This looks at Components in the form: - `txtname` with `dfield="txtname" dtable="book2_product"` - `numprice` with `dfield="numprice" dtable="book2_product"` - etc. And generates: `INSERT INTO book2_product (txtname, numprice, ...) VALUES (?, ?, ...)` plus the `$extra` columns, then returns the new record ID. ### **Automatic Update** ```php // Collects form Components and updates by the form's record ID $this->page->updateData($form2, $extra); ``` Generates: `UPDATE book2_product SET txtname=?, numprice=? WHERE id=?` ### **Loading Data for Edit** #### **Approach 1: Using $this->page->viewData() (Recommended)** ```php // Auto-populate form from record using database binding // Components need dfield and dtable attributes $this->page->viewData($form2, $recordId); ``` **How viewData works internally (Page::viewData):** ```php // viewData iterates over all form children components $compList = $form2->getAllChildren(); foreach ($compList as $compid => $comp) { // Only process components with dfield attribute and not marked blnDontFill if ($comp->dfield != '' && !$comp->blnDontFill) { // Get table from dtable attribute, else Page::$tblName // (the Gate's default table set via setTableName()) $table = ($comp->dtable != '') ? $comp->dtable : $this->tblName; // Page::$tblName // Build SELECT query, fetch data, set component value from database row } } ``` **Component flags for database binding:** - `dfield`: Database field name to bind with - `dtable`: Database table name (optional, uses `setTableName()` value by default) - `blnDontFill`: When set, component won't be filled from database #### **Approach 2: Manual fetch** ```php // Manual approach - fetch then set each component $this->dbEngine->connect(); $result = $this->dbEngine->executeQuery("SELECT * FROM book2_product WHERE id = $id"); $row = $this->dbEngine->rowFetchAssoc($result); $this->dbEngine->disconnect(); // Set each component manually $this->editFront->getComponent('txtname')->fi_setDefaultValue($row['txtname']); $this->editFront->getComponent('numprice')->fi_setDefaultValue($row['numprice']); ``` #### **FrontFile Component Database Binding** ```html <form id="form2" runat="server"> <!-- dfield = database field, dtable = database table --> <input id="txtname" runat="server" dfield="txtname" dtable="book2_product" /> <input id="numprice" runat="server" dfield="numprice" dtable="book2_product" type="number" /> <textarea id="txadescription" runat="server" dfield="txadescription" dtable="book2_product"></textarea> </form> ``` ### **Using Dynamic URLs** Always use `getThisGateUrl()`, `getEventUrl()`, `getGateUrl()` for dynamic URLs instead of hardcoded paths: In FrontFile: ```html <a href="##{getEventUrl('create')}#">Add New Product</a> <a href="##{getEventUrl('edit', $showall->getRow('id'))}#">Edit</a> ``` **Why use these helpers?** - Generates domain-binded absolute URLs (works under Apache subfolders like `/SartajPhpDoc/`) - Works even if you change the Gate registration name in `registerGate()` - Handles URL extensions dynamically ## **7.10 Complete File Structure** ``` SartajPhpDoc/ ├── reg.php │ ├── apps/ │ └── book2/ │ ├── Product.gate.php │ └── fronts/ │ ├── product_list.front # Pagination view │ └── product_edit.front # Add/Edit form │ ├── db/ │ └── db_book2.php # CREATE TABLE book2_product │ └── masters/ └── default/ ├── master.mast.php └── menu.place.php ``` ## **7.11 Chapter Summary** 1. **Two Front Files Pattern** - List for viewing, Form for editing 2. **Pagination Component** - `path="uikit/data/Pagination.php"` with `dtable`, `fun-setFieldNames`, `fun-setPerPageRows`, row cells via `sphp-comp` + `dfield` 3. **Form Components** - Use `dtable` and `dfield` for database binding 4. **Page Events**: - `page_new()` - Show list - `page_event_create()` - Empty form - `page_event_edit($evtp)` - Populated form via `viewData` - `page_submit()` - Save (insert/update via `isUpdateRequest()`) - `page_event_delete($evtp)` - Delete via `deleteRec` 5. **Database Operations** - `page->insertData()`, `page->updateData()`, `page->viewData()` ## **7.12 What's Next?** Next, learn about Master Files - how to create page layouts with headers, footers, and menus. --- *Next: Chapter 8 - Master Files: Creating Page Layouts*