PHPackages                             zunnu/cake-htmx - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. zunnu/cake-htmx

ActiveCakephp-plugin[Utility &amp; Helpers](/categories/utility)

zunnu/cake-htmx
===============

Htmx plugin for CakePHP

1.0.4(5mo ago)187.1k↓26%51MITPHPPHP &gt;=8.1CI passing

Since Jan 30Pushed 5mo ago4 watchersCompare

[ Source](https://github.com/zunnu/cake-htmx)[ Packagist](https://packagist.org/packages/zunnu/cake-htmx)[ RSS](/packages/zunnu-cake-htmx/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (6)Versions (13)Used By (1)

cake-htmx
=========

[](#cake-htmx)

CakePHP integration for [htmx](https://htmx.org/).

Supported CakePHP Versions &gt;= [4.x](https://github.com/zunnu/cake-htmx/tree/4.x) and 5.x.

Installing Using [Composer](http://getcomposer.org)
---------------------------------------------------

[](#installing-using-composer)

`cd` to the root of your app folder (where the `composer.json` file is) and run the following command:

```
composer require zunnu/cake-htmx

```

Then load the plugin by using CakePHP's console:

```
./bin/cake plugin load CakeHtmx

```

To install htmx please browse [their documentation](https://htmx.org/docs/#installing)

Usage
-----

[](#usage)

Main functionality is currently wrapped inside Htmx component. To load the component you will need to modify your `src/Controller/AppController.php` and load the Htmx component in the `initialize()` function

```
$this->loadComponent('CakeHtmx.Htmx');
```

### Request

[](#request)

You can use detector to check if the request is Htmx.

```
$this->getRequest()->is('htmx')  // Always true if the request is performed by Htmx
$this->getRequest()->is('boosted') // Indicates that the request is via an element using hx-boost
$this->getRequest()->is('htmx-noboost') // Convenience check that returns true if the request is htmx but not boosted.
$this->getRequest()->is('historyRestoreRequest') // True if the request is for history restoration after a miss in the local history cache
```

Using the component you can check more specific details about the request.

```
$this->Htmx->getCurrentUrl();  // The current URL of the browser
$this->Htmx->getPromptResponse(); // The user response to an hx-prompt
$this->Htmx->getTarget(); // The id of the target element if it exists
$this->Htmx->getTriggerName(); // The name of the triggered element if it exists
$this->Htmx->getTriggerId(); // The id of the triggered element if it exists
```

### Response

[](#response)

- `redirect`

Htmx can trigger a client side redirect when it receives a response with the `HX-Redirect` [header](https://htmx.org/reference/#response_headers).

```
$this->Htmx->redirect('/somewhere-else');
```

- `clientRefresh`

Htmx will trigger a page reload when it receives a response with the `HX-Refresh` [header](https://htmx.org/reference/#response_headers). `clientRefresh` is a custom response that allows you to send such a response. It takes no arguments, since Htmx ignores any content.

```
$this->Htmx->clientRefresh();
```

- `stopPolling`

When using a [polling trigger](https://htmx.org/docs/#polling), Htmx will stop polling when it encounters a response with the special HTTP status code 286. `stopPolling` is a custom response with that status code.

```
$this->Htmx->stopPolling();
```

See the documentation for all the remaining [available headers](https://htmx.org/reference/#response_headers).

```
$this->Htmx->location($location) // Allows you to do a client-side redirect that does not do a full page reload
$this->Htmx->pushUrl($url) // pushes a new url into the history stack
$this->Htmx->replaceUrl($url) // replaces the current URL in the location bar
$this->Htmx->reswap($option) // Allows you to specify how the response will be swapped
$this->Htmx->retarget($selector); // A CSS selector that updates the target of the content update to a different element on the page
```

Additionally, you can trigger [client-side events](https://htmx.org/headers/hx-trigger/) using the `addTrigger` methods.

```
$this->Htmx
    ->addTrigger('myEvent')
    ->addTriggerAfterSettle('myEventAfterSettle')
    ->addTriggerAfterSwap('myEventAfterSwap');
```

If you want to pass details along with the event you can use the second argument to send a body. It supports strings or arrays.

```
$this->Htmx->addTrigger('myEvent', 'Hello from myEvent')
->addTriggerAfterSettle('showMessage', [
    'level' => 'info',
    'message' => 'Here is a Message'
]);
```

You can call those methods multiple times if you want to trigger multiple events.

```
$this->Htmx
    ->addTrigger('trigger1', 'A Message')
    ->addTrigger('trigger2', 'Another Message')
```

CSRF token
----------

[](#csrf-token)

To add CSRF token to all your request add below code to your layout.

```
document.body.addEventListener('htmx:configRequest', (event) => {
    event.detail.headers['X-CSRF-Token'] = "";
})
```

Rendering blocks and OOB Swap
-----------------------------

[](#rendering-blocks-and-oob-swap)

The `setBlock()` function allows you to render a specific block while removing other blocks that might be rendered. This is particularly useful when you need to update only a portion of your view.

Calling `setBlock(null)` clears any selection.

```
$this->Htmx->setBlock('userTable');
```

The `addBlock()` function allows you to add a specific block to the list of blocks that should be rendered.

```
$this->Htmx->addBlock('userTable');
```

The `addBlocks()` function allows you to add multiple blocks to the list of blocks that should be rendered

```
$this->Htmx->addBlocks(['userTable', 'pagination']);
$this->Htmx->addBlocks(['userTable', 'pagination'], true); // Appends the blocks to the existing array.
```

> **Note:** `addBlocks()` appends by default. Pass `false` as the second argument to replace:
>
> ```
> $this->Htmx->addBlocks(['usersTable', 'pagination']);           // append (default)
> $this->Htmx->addBlocks(['onlyThis'], false);                    // replace
> ```

### OOB Swap

[](#oob-swap)

Htmx supports updating multiple targets by returning multiple partial responses with [`hx-swap-oob`](https://htmx.org/docs/#oob_swaps). See the example `Users index search functionality with pagination update`Note if you are working with tables like in the example. You might need to add

```

    htmx.config.useTemplateFragments = true;

```

In your template or layout.

### Clearing Blocks

[](#clearing-blocks)

You can clear the current block selection in two equivalent ways:

```
// Explicitly clear any selection
$this->Htmx->clearBlocks();

// Or, using setBlock(null)
$this->Htmx->setBlock(null);
```

Examples
--------

[](#examples)

### Users index search functionality

[](#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).

```
// Template/Users/index.php
