diff --git a/README.md b/README.md index d43929e..516fa40 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ CakePHP integration for [htmx](https://htmx.org/). -Supported CakePHP Versions >= 4.x.x. 5.x support will be added later. +Supported CakePHP Versions >= [4.x](https://github.com/zunnu/cake-htmx/tree/4.x) and 5.x. ## Installing Using [Composer][composer] @@ -113,6 +113,123 @@ document.body.addEventListener('htmx:configRequest', (event) => { }) ``` +## Examples + +### Users index search functionality + +In this example, we will implement a search functionality for the users' index using Htmx to filter results dynamically. We will wrap our table body inside a [viewBlock](https://book.cakephp.org/5/en/views.html#using-view-blocks) called `usersTable`. When the page loads, we will render the `usersTable` [viewBlock](https://book.cakephp.org/5/en/views.html#using-view-blocks). + +```php +// Template/Users/index.php + +Form->control('search', [ + 'label' => false, + 'placeholder' => __('Search'), + 'type' => 'text', + 'required' => false, + 'class' => 'form-control input-text search', + 'value' => !empty($search) ? $search : '', + 'hx-get' => $this->Url->build(['controller' => 'Users', 'action' => 'index']), + 'hx-trigger' => "keyup changed delay:200ms", + 'hx-target' => "#search-results", + 'templates' => [ + 'inputContainer' => '
{{content}}
' + ] +]); ?> + + + + + + + + + + + + + + + start('usersTable'); ?> + + + + + + + + + + + end(); ?> + + fetch('usersTable'); ?> + +
id ?>name) ?>email) ?>modified ?>created ?> + Html->link('Edit', + [ + 'action' => 'edit', + $user->id + ], + [ + 'escape' => false + ] + ); ?> + Form->postLink('Delete', + [ + 'action' => 'delete', + $user->id + ], + [ + 'confirm' => __('Are you sure you want to delete user {0}?', $user->email), + 'escape' => false + ] + ); ?> +
+``` +In out controller we will check if the request is Htmx and if so then we will only render the `usersTable` [viewBlock](https://book.cakephp.org/5/en/views.html#using-view-blocks). + +```php +// src/Controller/UsersController.php + +public function index() +{ + $search = null; + $query = $this->Users->find('all'); + + if ($this->request->is('get')) { + if(!empty($this->request->getQueryParams())) { + $data = $this->request->getQueryParams(); + + if(isset($data['search'])) { + $data = $data['search']; + $conditions = [ + 'OR' => [ + 'Users.id' => (int)$data, + 'Users.name LIKE' => '%' . $data . '%', + 'Users.email LIKE' => '%' . $data . '%', + ], + ]; + $query = $query->where([$conditions]); + $search = $data; + } + } + } + + $users = $query->toArray(); + $this->set(compact('users', 'search')); + + if($this->getRequest()->is('htmx')) { + $this->viewBuilder()->disableAutoLayout(); + + // we will only render the usersTable viewblock + $this->Htmx->setBlock('usersTable'); + } +} +``` + + + ## License Licensed under [The MIT License][mit].