Documentation

On this page

Download full book (text)

# **Chapter 5: FrontFile Events - Interacting with Templates** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Blog.gate.php`) > - Front Files: `*.front` (e.g., `blog_edit.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`). Open > `http://localhost/SartajPhpDoc/blog.html` (list) and `http://localhost/SartajPhpDoc/blog-addnew.html` > (form) — see Chapter 4 for setup. --- ## **5.1 What are FrontFile Events?** FrontFile Events allow your Gate class to interact with the FrontFile template. While Page Events handle browser requests, FrontFile Events handle template interactions. These events are called at specific times during FrontFile processing, allowing you to: - Attach metadata before/after Components are created - Modify Components before rendering - Handle Component-specific init events - Inject dynamic content ## **5.2 The FrontFile Event Methods** ### **onfrontinit($frontobj) - FrontFile Created** Called for **every FrontFile created in the Gate**. Use `addMetaData()` to attach values that FrontFile expressions can read as `##{$key}#`: ```php // apps/examples/Blog.gate.php public function onfrontinit($frontobj) { $frontobj->addMetaData('book2gate', 'blog'); } ``` In any FrontFile of this Gate: ```html <!-- blog_list.front --> <p class="small text-muted">onfrontinit metadata: <code>##{$book2gate}#</code></p> ``` Renders: `onfrontinit metadata: blog` **Important (tested):** `addMetaData('title', ...)` or `addMetaData('description', ...)` does NOT override the `<title runat="server">` component — the title Component drives `<title>`, the description meta tag, and og:title. Set the SEO title by filling the `<title>` component (or a Gate property inside it), and use `addMetaData` for custom keys you read in expressions. ### **onfrontprocess($frontobj) - FrontFile Processed** Called after the FrontFile has been parsed - all Components exist, all fusion attributes executed. Modify Components before rendering: ```php // apps/examples/Blog.gate.php public function onfrontprocess($frontobj) { $p = $frontobj->getComponentSafe('pAdminNote'); if ($p !== null && $this->page->getAuthenticateType() !== 'GUEST') { $p->setInnerHtml('Members/admins see this (onfrontprocess + setInnerHtml).'); } } ``` ```html <!-- blog_list.front — empty container, filled by Gate --> <div id="pAdminNote" runat="server" class="small text-info"></div> ``` `getComponentSafe()` returns `null` instead of throwing when the id is absent — useful when one Gate serves several FrontFiles. **Hide/show tip (tested):** `fu_unsetVisible()` turns the Component tag into a hidden input, but static text around it still prints. For clean show/hide, make the whole element a Component (`runat="server"`) with empty content and fill it from the Gate with `setInnerHtml()` only when it should appear. ## **5.3 Interacting with Components** ### **Getting Components** ```php // Get a specific component by ID $txtTitle = $this->editFront->getComponent('txttitle'); $showall = $this->listFront->getComponent('showall'); $p = $this->listFront->getComponentSafe('pAdminNote'); // null if missing ``` ### **Modifying Components** ```php public function page_event_view($evtp) { // Get component $txtTitle = $this->editFront->getComponent('txttitle'); // Set value (Render Phase) $txtTitle->fu_setValue('Hello Book2'); // Set default value (Parse Phase) $txtTitle->fi_setDefaultValue('Enter a title'); // Make read-only (TextField has fu_setReadOnly — note the capital O) $txtTitle->fu_setReadOnly(); // Hide / show (Render Phase) $txtTitle->fu_unsetVisible(); $txtTitle->fu_setVisible(); // Set inner HTML of a container Component $note = $this->listFront->getComponent('pAdminNote'); $note->setInnerHtml('<p>Dynamic content here</p>'); } ``` | Method | Phase | Purpose | |--------|-------|---------| | `fi_setDefaultValue($val)` | Parse (init) | Default value before form fill | | `fu_setValue($val)` | Render | Value at render time | | `setAttribute($name, $val)` | Any | Raw HTML attribute (readonly, data-*) | | `fu_setVisible()` / `fu_unsetVisible()` | Render | Show / hide the Component | | `setInnerHtml($html)` | Render | Replace inner content | | `getValue()` | Any | Read submitted/current value | ### **Working with Forms** For database operations with forms, use `$this->page` helper methods (see Section 5.8): ```php // apps/examples/Blog.gate.php public function page_submit() { $form2 = $this->editFront->getComponent('form2'); // Check if form is in insert or update mode if ($form2->isUpdateRequest()) { // Edit mode — record id = $form2->getRecID() $this->page->updateData($form2, array()); } else { // New record mode $insertedID = $this->page->insertData($form2, array()); } } // View record for editing public function page_event_view($evtp) { $form2 = $this->editFront->getComponent('form2'); $this->page->viewData($form2, $evtp); $this->setFrontFile($this->editFront); } // Delete record public function page_event_delete($evtp) { $this->page->deleteRec($evtp); } ``` ## **5.4 Component Events from FrontFile** You can also handle events that originate from Components in your FrontFile. ### **Component Event Naming** In your FrontFile, add hooks like `on-init="true"` or `on-startrender="true"`: ```html <input id="txttitle" runat="server" on-init="true"> ``` Then in your Gate, create a method named `comp_{ComponentId}_{event}`: ```php // apps/examples/Blog.gate.php // $arglst['obj'] = Component, $arglst['evt'] = 'on-init' public function comp_txttitle_on_init($arglst) { $comp = $arglst['obj']; $comp->setAttribute('data-book2-init', '1'); } ``` Verified: the rendered input carries `data-book2-init="1"`. ### **Handling Multiple Component Events** ```php // In FrontFile: // <input id="txtEmail" runat="server" on-init="true"> public function comp_txtEmail_on_init($arglst) { $component = $arglst['obj']; // Configure the component early (defaults, flags) $component->fi_setDefaultValue('you@example.com'); } ``` ## **5.5 Using Holder in FrontFile** The `runas="holder"` attribute creates placeholders for dynamic content. The fully tested forms (see Chapter 9 for the complete guide): ```html <!-- Bare holder — Gate must implement onholder($element) --> <div runas="holder"></div> <!-- Fill cell from Pagination Component row field --> <td runas="holder" sphp-comp="showall" dfield="txttitle"></td> <!-- Read a Component property --> <div runas="holder" sphp-comp="showall" sphp-comp-prop="page_links"></div> ``` ### **Setting Holder Content in Gate** ```php // apps/examples/Ex04front.gate.php — bare holder handler public function onholder($element) { // $element is the NodeTag with runas="holder" $element->setInnerHtml('filled by Gate onholder()'); } ``` **Pitfall (tested):** a bare `runas="holder"` without an `onholder()` method in the Gate throws `Call to undefined method ...::onholder()`. For Gate → FrontFile values, the simplest tested mechanism is a Gate property read through an expression — no holder needed: ```php // Gate public $statusMsg = 'Inserted id=3'; ``` ```html <!-- FrontFile --> <p>Status: <code>##{$parentGate->statusMsg}#</code></p> ``` ## **5.6 The onholder Event** `onholder($element)` is called for any holder tag that has no `sphp-comp` source. Branch on your own data attribute to serve several placeholders from one method: ```php // Gate public function onholder($element) { $type = $element->getAttribute('data-widget-type'); switch ($type) { case 'user-list': $element->setInnerHtml($this->getUserListHTML()); break; case 'product-grid': $element->setInnerHtml($this->getProductGridHTML()); break; } } ``` FrontFile: ```html <div runas="holder" data-widget-type="user-list"></div> <div runas="holder" data-widget-type="product-grid"></div> ``` ## **5.7 Complete Example - Blog Application** The tested Blog Gate combines everything in this chapter (full CRUD events in Chapter 4): ```php <?php // apps/examples/Blog.gate.php (FrontFile-event parts) use Sphp\Gates\BasicGate; use Sphp\Tools\FrontFile; class Blog extends BasicGate { public $listFront = null; public $editFront = null; public $pageName = 'Blog'; public $statusMsg = ''; public $formButton = 'Save'; public function onstart() { global $masterf; $this->getAuthenticate('GUEST,MEMBER,ADMIN'); // Default table for $this->page database methods $this->setTableName('book2_post'); $this->listFront = new FrontFile('list'); $this->editFront = new FrontFile('edit'); $this->setMasterFile($masterf); } /** Before parse: attach metadata readable as ##{$book2gate}# */ public function onfrontinit($frontobj) { $frontobj->addMetaData('book2gate', 'blog'); } /** After parse: components exist — fill admin note */ public function onfrontprocess($frontobj) { $p = $frontobj->getComponentSafe('pAdminNote'); if ($p !== null && $this->page->getAuthenticateType() !== 'GUEST') { $p->setInnerHtml('Members/admins see this (onfrontprocess + setInnerHtml).'); } } /** Component hook: on-init="true" on #txttitle */ public function comp_txttitle_on_init($arglst) { $arglst['obj']->setAttribute('data-book2-init', '1'); } /** Bare holder fallback (blog_list.front has no bare holder, edit front may add one) */ public function onholder($element) { $element->setInnerHtml('filled by Gate onholder()'); } // page_new / page_submit / page_event_* — see Chapter 4 } ``` ## **5.8 $this->page Helper Methods for Database Operations** SartajPhp provides helper methods through `$this->page` that reduce code when working with database operations. These methods work with Components that have database binding attributes (`dfield` and `dtable`). ### **Setting Table Name** Before using database methods, set the default table name in the Gate: ```php // apps/examples/Blog.gate.php public function onstart() { // ... $this->setTableName('book2_post'); } ``` ### **$this->page->viewData($form, $recID, $fldList, $where)** Fill form components with data from database: ```php public function page_event_view($evtp) { $form2 = $this->editFront->getComponent('form2'); // Fill form with record data ($evtp is the record ID) $this->page->viewData($form2, $evtp); // Or specify custom fields and where clause // $this->page->viewData($form2, '', "txttitle,txabody", "WHERE id=5"); $this->setFrontFile($this->editFront); } ``` ### **$this->page->insertData($form, $extra)** Insert form component values to database; returns the new record ID: ```php public function doInsert($form2) { global $cmpId; $extra = array(); $extra[]['submit_timestamp'] = time(); $extra[]['update_timestamp'] = time(); $extra[]['spcmpId'] = $cmpId; $insertedID = $this->page->insertData($form2, $extra); // check errors: if (!getCheckErr() && $insertedID) { ... } } ``` ### **$this->page->updateData($form, $extra, $recID, $where)** Update existing database record: ```php public function doUpdate($form2) { $extra = array(); $extra[]['update_timestamp'] = time(); // Record id taken from the form itself ($form2->getRecID()) $this->page->updateData($form2, $extra); // Or custom where clause // $this->page->updateData($form2, $extra, '', "WHERE txttitle='Hello Book2'"); } ``` ### **$this->page->deleteRec($recID)** Delete a database record: ```php public function page_event_delete($evtp) { // Delete using event parameter as record ID $this->page->deleteRec($evtp); // Or use the current event parameter implicitly // $this->page->deleteRec(); } ``` ### **Database Binding in FrontFile Components** For `$this->page` helper methods to work, Components need database binding attributes: ```html <!-- apps/examples/fronts/blog_edit.front --> <form id="form2" runat="server" method="post" action="##{getThisGateUrl()}#"> <input id="txttitle" runat="server" type="text" dfield="txttitle" dtable="book2_post" fui-setForm="form2" fun-setRequired="" fun-setMsgName="Title" /> <textarea id="txabody" runat="server" dfield="txabody" dtable="book2_post" fui-setForm="form2"></textarea> <button type="submit">Save</button> </form> ``` - `dfield`: Database table field name - `dtable`: Database table name (optional if `$this->setTableName()` was called) - `fui-setForm`: binds the Component to the form for validation ## **5.9 Chapter Summary** 1. **FrontFile Events** allow Gate-template interaction 2. **onfrontinit($frontobj)** - Called for every FrontFile; `addMetaData` keys read as `##{$key}#` 3. **onfrontprocess($frontobj)** - After parse; modify Components (`getComponentSafe`, `setInnerHtml`) 4. **Component Events** - `on-init="true"` + `comp_componentId_on_init($arglst)` with `$arglst['obj']` 5. **Holders** - `runas="holder"`: bare (needs Gate `onholder`), `sphp-comp` + `dfield`, `sphp-comp-prop` 6. **$this->page helper methods** - `viewData`, `insertData`, `updateData`, `deleteRec` with `dfield`/`dtable` binding and `setTableName()` ## **5.10 What's Next?** Now you understand how Gate interacts with FrontFile. Next, let's build actual webpages using Front Files and Master Files. --- *Next: Chapter 6 - Building Your First Webpage*