Documentation

On this page

Download full book (text)

# **Chapter 18: AutoGate — A Full CRUD App With Almost No Gate Code** > **Prerequisites:** Chapters 7, 13, 15, 17 (Pagination, AJAX, Page helpers, Components) > **Try it:** Tested code from gate `ex18auto` > (`apps/examples/Ex18auto.gate.php` + `apps/examples/fronts/ex18auto_*.front`). > Reuses the `ex17_doc` table — install via > `http://localhost/SartajPhpDoc/ex17comps-install.html` first, then open > `http://localhost/SartajPhpDoc/ex18auto.html`. --- ## **18.1 What AutoGate Gives You For Free** Chapters 15-17 built CRUD by hand: `page_submit` → insert/update, `rowclick` → AJAX editor, `showall_show` → AJAX pagination, delete. `AutoGate` (`vendor/.../res/Slib/apps/helper/AutoGate.php`) is that exact flow already written — a `BasicGate` subclass whose handlers assume the standard conventions (list Front with `showall` Pagination, edit Front with `form2`, table with `id`). The entire tested demo Gate: ```php <?php // apps/examples/Ex18auto.gate.php — the WHOLE gate (tested) include_once(SphpBase::sphpSettings()->slibPath . '/apps/helper/AutoGate.php'); use Sphp\Tools\FrontFile; class Ex18auto extends AutoGate { public function onstart() { global $masterf; $this->getAuthenticate('GUEST,MEMBER,ADMIN'); $this->setTableName('ex17_doc'); // reuse Ex17 table $this->heading = 'Ex18 AutoGate'; $this->formid = 'form2'; // Required by AutoGate: list Front (Pagination id=showall) // + edit Front (form id=form2, btnDel) $this->showallFront = new FrontFile('list'); $this->genFormFront = new FrontFile('edit'); $this->setMasterFile($masterf); parent::onstart(); } } ``` Five meaningful lines: table, form id, two FrontFiles, `parent::onstart()`. ## **18.2 The Contract Between Gate and Fronts** AutoGate's handlers reach into your Fronts by **id**, so the Fronts must use the expected ids: | Id | Where | AutoGate uses it for | |----|-------|----------------------| | `showall` | list Front (`Pagination`) | list rows, AJAX paging, refresh after save | | `form2` | edit Front (`HTMLForm`) | `$this->formid` — insert/update branch | | `btnDel` | edit Front | delete button (hidden on add, shown on edit) | | `showall_editor` | list Front holder div | `addJsonFront` target for the edit form | | `showall_dlg` | list Front dialog div | jQuery UI dialog around the editor | | `listFormHolder` | list Front wrapper | AJAX list reload target (`loadform`) | The tested list Front (`ex18auto_list.front`): ```html <div id="listFormHolder"> <table class="table table-sm"> <thead><tr><th>ID</th><th>Title</th><th>Category</th></tr></thead> <tbody id="showall" runat="server" path="uikit/data/Pagination.php" fun-setFieldNames="id,txttitle,sltcategory" dtable="ex17_doc" fun-setPerPageRows="10"> <tr style="cursor:pointer" onclick="sendAjax('##{getEventUrl('rowclick', $showall->getRow('id'))}#');"> <td runas="holder" sphp-comp="showall" dfield="id"></td> <td runas="holder" sphp-comp="showall" dfield="txttitle"></td> <td runas="holder" sphp-comp="showall" dfield="sltcategory"></td> </tr> </tbody> </table> <div id="pagebar">##{$showall->getPageBar()}#</div> </div> <!-- AutoGate rowclick injects edit Front here --> <div id="showall_dlg" title="Edit"> <div id="showall_editor"></div> </div> <script runas="jsfunctioncode" function="ready"> if (window.jQuery && jQuery.fn.dialog) { jQuery("#showall_dlg").dialog({ autoOpen: false, width: 520, modal: true }); } </script> ``` ## **18.3 Handlers You No Longer Write** From the AutoGate source (all inherited by `Ex18auto`): | Event | What the parent does | |-------|----------------------| | `page_new` | render list Front | | `page_event_rowclick` | `viewData(form2)` → show `btnDel` → open dialog → `addJsonFront(genFormFront,'showall_editor')` | | `page_event_addform` / `showall_newa` | inject empty form (session `formType=Add`) | | `page_submit` | `isUpdateRequest()` → `update()` else `insert()` | | `insert()` / `update()` | `insertData`/`updateData` with `$this->extra` → refresh `showall` → close dialog → `sendSuccess` | | `page_event_delete` | `deleteRec()` → refresh list → close dialog | | `page_event_showall_show` | AJAX page change (`addJsonComp` + pagebar) | | `page_event_loadform` | AJAX list reload into `listFormHolder` | Notice `insert()` merges `$this->extra` automatically — so the Gate adds convention columns **without touching page_submit**: ```php <?php // inside your onstart, before parent::onstart(): global $cmpId; $this->extra[]['spcmpId'] = $cmpId; $this->extra[]['userid'] = 0; $this->extra[]['parentid'] = 0; $this->extra[]['submit_timestamp'] = time(); $this->extra[]['update_timestamp'] = time(); ``` Override any single handler when your app deviates — e.g. log to `data_log` (Chapter 16) by overriding `update()`, calling `parent::update()` after your snapshot. ## **18.4 Feedback Blocks: sendSuccess / sendError** AutoGate answers AJAX with a small UI protocol — message banners plus a JS animation hook your master can implement: ```php <?php public function sendSuccess($msg) { $this->jsServer->addJsonBlock('html', 'sphpsuccessmsg', $msg); $this->jsServer->addJsonJsBlock('runanierr("success");'); } public function sendError($errorInner = "") { // traces setMsg/setErr/setErrInner into sphpinfomsg / sphperrormsg blocks } ``` So soft errors you set in overrides (`setErr('app1', ...)`) surface in the dialog automatically — `sendError()` reads `traceError(true)` for you. ## **18.5 AutoGatePermis — Same Handlers + Permissions** `AutoGatePermis` (same folder) layers Chapter 14's `hasPermission()` checks on insert/update/delete. Register the gate with a permlist and the stock handlers guard themselves: ```php <?php // reg.php registerGate("mydocs", __DIR__ . "/apps/MyDocs.gate.php", "", "My Docs", array(["add","Add"],["delete","Delete"])); ``` ```php <?php class MyDocs extends AutoGatePermis { /* same 5-line onstart */ } ``` Use AutoGate for internal/GUEST demos, AutoGatePermis for anything with real users. ## **18.5a PermisGate — The Older Permission-CRUD Parent (`apps/permis/`)** `PermisGate` (`vendor/.../res/Slib/apps/permis/PermisGate.php`) predates AutoGate and solves the same problem with a slightly different contract. This project's real member area uses it — `apps/permis/MebProfile.gate.php`, `MebProfilePermission.gate.php`, and `MebHome.gate.php` all extend it. Know it so you can read (and extend) the shipped permission app: | | AutoGate | PermisGate | |---|----------|------------| | Permission checks | `AutoGatePermis` variant | built into stock `insert/update/delete/view/addnew` | | Edit entry event | `rowclick` (dialog) | `page_event_view` (full page) + `page_event_addnew` | | Update path | `page_event_rowclick` submit | `page_event_up` → forwards to `page_submit` | | Extra columns | `$this->extra` | `$this->extra` (auto-adds `userid`, `parentid`, `spcmpId`, timestamps) | | List refresh | dialog AJAX | `page_event_showall_show` + delete AJAX (`addJsonComp` + pagebar) | The stock handlers (from the vendor source) show the permission discipline to copy into hand-written Gates: ```php <?php // PermisGate (vendor) — every mutation checks its permission first public function page_event_view($evtp) { if ($this->page->hasPermission("view") && $this->page->getEventParameter() != "") { $form2 = $this->genFormFront->getComponent($this->formid); $this->page->viewData($form2); $this->setFrontFile($this->genFormFront); } else { $this->page_new(); // no permission → back to list, no error page } } ``` `insert()` fills `$this->extra` from the **session** — `userid` = `session('sid')`, `parentid` = `session('parentid')`, plus `$cmpId` and timestamps — which is exactly the ownership convention from Chapter 12 (`id`, `userid`, `parentid`, `spcmpId`, `submit_timestamp`, `update_timestamp`). Tables you want PermisGate to manage must carry those columns. A real subclass overrides one method and delegates the rest (tested in this project's member area): ```php <?php // apps/permis/MebProfile.gate.php (excerpt) include_once(SphpBase::sphpSettings()->slibPath . "/apps/permis/PermisGate.php"); class MebProfile extends PermisGate { public function onstart() { global $mebmasterf; $this->getAuthenticate("ADMIN,MEMBER"); $this->page->getAuthenticatePerm("view"); // require mebProfile-view $this->setTableName("member"); $this->genFormFront = new FrontFile("edit"); $this->showallFront = new FrontFile("list"); // scope the list to this user's sub-tree (Chapter 15's fu_setWhere) $this->defWhere = " WHERE member.parentid = '" . $this->client->session('parentid') . "' AND usertype = 'MEMBER' AND member.id != '" . $this->client->session('sid') . "'"; $this->showallFront->getComponent('showall')->fu_setWhere($this->defWhere); $this->setMasterFile($mebmasterf); } public function insert() { // add domain checks, then reuse the parent if ($this->checkUserEmail($this->client->request('email'))) { setErr('App', 'This Email already exist!!'); $this->setFrontFile($this->genFormFront); } else { $this->extra[]['usertype'] = 'MEMBER'; parent::insert(); } } } ``` Note the pattern: **override → validate → `parent::insert()`**. The parent also ships `checkUserName()` / `checkUserEmail()` helpers built on `$this->dbEngine->isRecordExist()` (Chapter 15). Which parent to pick: **AutoGate** for new CRUD screens (dialog UX, cleaner contract), **PermisGate** when extending the shipped `apps/permis/` member area. Both teach the same lesson — a parent Gate encodes conventions, a subclass overrides only what differs. ## **18.6 When NOT to Use AutoGate** 1. **Non-standard flows** — multi-step wizards, approval chains: write the Gate by hand (Chapters 15-17) 2. **Different ids** — if `showall`/`form2` clash with existing markup, the parent's `getComponent('showall')` calls fail; renaming means overriding most handlers anyway 3. **Heavy custom validation between steps** — you'd override `insert()` and `update()` entirely, at which point the hand-written Gate is clearer 4. **Full form generation from DB schema** is a separate helper tool (AiInfo/GenAppFromDb) — AutoGate only automates the *handlers* Rule of thumb: **AutoGate for stock admin CRUD screens, hand-written Gates for product flows.** ## **18.7 Verify It Yourself** Against `http://localhost/SartajPhpDoc/`: 1. `ex17comps-install.html` (creates `ex17_doc`) 2. `ex18auto.html` → list of `ex17_doc` rows with pagebar 3. Click a row → modal dialog with filled edit form → Update → dialog closes, list refreshes via AJAX 4. Change page via pagebar → rows swap without reload (`showall_show`) 5. Delete inside the dialog → row disappears from list --- **Previous:** [Chapter 17 — Built-in Form and Data Components](chapter17.md) · **Next:** [Chapter 19 — Debugging and Error Tracing](chapter19.md)