1. Go to this page and download the library: Download giantbits/yii2-htmx library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace app\components;
use giantbits\htmx\HtmxComponent;
class Counter extends HtmxComponent
{
public int $count = 0;
protected function actions(): array
{
return ['increment', 'decrement'];
}
protected function resolveState(): void
{
$this->count = Yii::$app->session->get('counter', 0);
}
public function actionIncrement(): void
{
$this->resolveState();
Yii::$app->session->set('counter', ++$this->count);
}
public function actionDecrement(): void
{
$this->resolveState();
Yii::$app->session->set('counter', --$this->count);
}
}
<?= \app\components\Counter::widget()
namespace app\components;
use giantbits\htmx\HtmxComponent;
class JobFilter extends HtmxComponent
{
public array $jobs = [];
public array $filters = [];
// Which actions can be called via HTMX
protected function actions(): array
{
return ['filter', 'reset'];
}
// Load state before every render
protected function resolveState(): void
{
$query = Job::find();
if (!empty($this->props['category'])) {
$query->andWhere(['category' => $this->props['category']]);
}
// Apply filters from POST data or session
$this->filters = Yii::$app->session->get('jobFilters', []);
foreach ($this->filters as $key => $value) {
$query->andWhere([$key => $value]);
}
$this->jobs = $query->all();
}
public function actionFilter(array $params = []): void
{
$filters = Yii::$app->request->post();
Yii::$app->session->set('jobFilters', $filters);
// Component auto re-renders after the action
}
public function actionReset(): void
{
Yii::$app->session->remove('jobFilters');
}
}
// Remove element from DOM (e.g., after deleting a record)
$this->actionSwap = 'delete';
// Emit event for other components to react
$this->emitEvent('listChanged');
// Client-side redirect after action
$this->redirect('/some/url');
// Push URL to browser history
$this->pushUrl('/jobs?page=2');
// Set custom response HTML instead of re-rendering the template
$this->actionHtml = '<p>Custom response</p>';
'params' => [
'htmx.version' => '2.0.4', // HTMX version to load from CDN
'htmx.local' => false, // true = load from local asset instead of CDN
],
components/
├── Counter.php
└── Counter.view.twig
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.