Live filters and forms without a reload
How a module updates part of a page without a reload: a filter on htmx, server actions through wire, CSRF for these requests and the rules for a module's client scripts.
By the end the module has a list with search and sorting that redraws as the visitor types, and a "Follow" button that runs an action on the server and replaces only itself. Both keep working without JavaScript: the form goes out as a normal request and the whole page comes back.
In both cases the server draws the HTML. For reads (filters, sorting, list pages) use htmx on top of an ordinary GET route. For an action that changes something, use wire: a server-side WireSurface with named actions.
Live filter on htmx
The controller is an ordinary GET route, and the filter has no separate address. Declaring routes is covered in Module routes, middleware and API.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Controllers;
use Flute\Core\Router\Annotations\Route;
use Flute\Core\Support\BaseController;
use Flute\Core\Support\FluteRequest;
use Flute\Modules\Example\Services\Leaderboard;
use Illuminate\View\View;
final class BoardController extends BaseController
{
public function __construct(
private readonly Leaderboard $leaderboard,
) {
}
#[Route(uri: '/example', methods: ['GET'], name: 'example.index')]
public function index(FluteRequest $request): View
{
$sorts = ['score' => __('example.board.by_score'), 'name' => __('example.board.by_name')];
$sort = (string) $request->input('sort', 'score');
$sort = array_key_exists($sort, $sorts) ? $sort : 'score';
$q = mb_substr(trim((string) $request->input('q', '')), 0, 32);
return view('example::index', [
'q' => $q,
'sort' => $sort,
'sorts' => $sorts,
'rows' => $this->leaderboard->search($q, $sort),
]);
}
}The form submits with GET, and the htmx attributes request the same address and replace only the block marked data-example-board. hx-push-url writes the filter into the address bar, so the link can be copied and the Back button works.
<section class="example-board" data-example-board>
<form class="example-board__bar" method="get" action="{{ route('example.index') }}"
hx-get="{{ route('example.index') }}"
hx-trigger="change, keyup changed delay:400ms from:find input[type=search]"
hx-target="[data-example-board]" hx-select="[data-example-board]" hx-swap="outerHTML"
hx-push-url="true" hx-disinherit="*">
<input type="search" name="q" value="{{ $q }}" maxlength="32" aria-label="{{ __('example.board.search') }}">
<x-fields.select name="sort" :value="$sort" :options="$sorts" aria-label="{{ __('example.board.sort') }}" />
<noscript><x-button type="tertiary" size="small" :submit="true">{{ __('example.board.apply') }}</x-button></noscript>
</form>
<ol class="example-board__list">
@foreach ($rows as $row)
<li>{{ $row['name'] }} · {{ $row['score'] }}</li>
@endforeach
</ol>
</section>The Clans module builds its ranking this way. An htmx request gets the page without the header and footer (request()->htmx()->omitsLayoutShell()), and hx-select cuts the block it needs out of it.
Action through wire
A surface is a class with an id(), an access check, a list of actions and the fragments it can redraw. The container builds it, so dependencies can come in through the constructor.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Wire;
use Flute\Admin\UI\Action\ActionDescriptor;
use Flute\Admin\UI\Action\ActionRegistry;
use Flute\Admin\UI\Action\ActionResult;
use Flute\Admin\UI\PageContext;
use Flute\Core\Wire\Contracts\WireSurface;
use Flute\Modules\Example\Services\Follows;
final class FollowSurface implements WireSurface
{
public const ID = 'example.follow';
public const FOLLOW = 'follow';
public function __construct(
private readonly Follows $follows,
) {
}
public function id(): string
{
return self::ID;
}
public function authorize(PageContext $context): bool
{
return user()->isLoggedIn();
}
public function actions(PageContext $context): ActionRegistry
{
return ( new ActionRegistry() )->register(ActionDescriptor::make(self::FOLLOW)->handler($this->toggle(...)));
}
public function renderFragment(string $fragmentId, PageContext $context): ?string
{
return null;
}
private function toggle(PageContext $context): ActionResult
{
$user = user()->getCurrentUser();
$server = (int) $context->input('server');
if ($user === null || $server <= 0) {
return ActionResult::make()->toast((string) __('example.follow.failed'), 'error');
}
$following = $this->follows->toggle($user, $server);
return ActionResult::make()
->replace(
'[data-example-follow="' . $server . '"]',
view('example::partials.follow', ['server' => $server, 'following' => $following])->render(),
)
->toast((string) __($following ? 'example.follow.on' : 'example.follow.off'));
}
}The button is a plain POST form to /wire. With JavaScript the core client flute-ui.js intercepts it and sends the request itself. Without it the browser submits the form and comes back to the page with a notice.
<div data-example-follow="{{ $server }}">
<form method="post" novalidate yoyo:ignore
action="{{ url(route('wire.action')) }}?_surface=example.follow&_action=follow"
data-wire-surface="example.follow" data-wire-action="follow">
<input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
<input type="hidden" name="server" value="{{ $server }}">
<x-button type="{{ $following ? 'tertiary' : 'secondary' }}" size="small" :submit="true" aria-pressed="{{ $following ? 'true' : 'false' }}">
{{ __($following ? 'example.follow.following' : 'example.follow.follow') }}
</x-button>
</form>
</div>Register the surface by class name in the provider's boot(). The object is built only when a request names this id:
use Flute\Core\Wire\WireRegistry;
use Flute\Modules\Example\Wire\FollowSurface;
$container->get(WireRegistry::class)->lazy(FollowSurface::ID, FollowSurface::class);The Wipes module's wipe subscriptions and the Clans module's clan actions work this way.
How it works
POST /wire?_surface=<id>&_action=<name> goes through the web group (CSRF and rate limiting) and the ban check. The core looks the surface up in WireRegistry, calls authorize(), then the action from actions(). Permissions for a single action are checked by ActionDescriptor::authorize('example.manage'). An action name missing from the list or an unknown surface gives 404 "Unknown error!", and a denied check gives 403 "Permission denied".
The handler returns an ActionResult. The response comes back as 200, and the operations travel in the HX-Trigger header as flute:* events that flute-ui.js carries out. A form sent without scripts gets a 303 back to the previous page or to redirect(), and toasts and field errors turn into flash messages.
GET /wire?_surface=<id>&_fragment=<id> returns the HTML from renderFragment(), and null gives 404. The response carries an ETag, so a poll with no changes gets a 304. The element that reload('list') redraws is marked with data-wire-fragment="list" and data-wire-surface="example.follow".
In worker mode WireRegistry::lazy() builds the surface again for each request, so its properties may hold things that belong to the current visitor.
CSRF
POST, PUT, PATCH and DELETE routes of a module get the csrf check on their own. A form needs the hidden _csrf_token field, and an htmx request sends the X-CSRF-Token header: the standard layout sets it on <body> through hx-headers, and flute-ui.js adds it to requests to /wire.
When the token has expired, an async request gets a 403 with an empty body, a fresh token in the X-CSRF-Token header and the notice "Your token has expired. Refresh the page". A request from another site is refused even with a valid token.
Reference
ActionResult | What the client does |
|---|---|
toast(string $message, string $type = 'success') | a notice, success, error, warning or info |
reload(string $componentId, array $params = []) | fetches the fragment again through GET /wire |
replace(string $selector, string $html, bool $morph = false) | replaces the element, with $morph it keeps unchanged nodes |
validationErrors(array $errors) | errors under the fields [data-field-error="<field>"], the result counts as failed |
event(string $name, array $payload = []) | an event on document.body |
openSurface(string $id, array $payload = []), closeSurface(string $id) | opens or closes a dialog |
redirect(string $url), location(string $url) | a full navigation, or an htmx navigation with a working Back button |
| Markup attribute | What it does |
|---|---|
data-wire-surface, data-wire-action | on a form or button: where to send it |
data-wire-confirm="text" | asks for confirmation before sending |
data-wire-param-<name>="value" | adds a field to the request |
data-wire-prompt="question" | on a button: asks for a string and sends it as the code field |
data-wire-fragment="<id>" | the area that reload() redraws |
<body> loads the htmx extensions head-support, loading-states, morph and response-targets, and htmx is version 2.0.10. Navigation links go through hx-boost into #main, and a route with the htmx middleware answers 404 to an ordinary request. In a controller request()->htmx() answers isHtmxRequest(), isBoosted(), getTarget(), getTriggerName() and getCurrentUrl().
Client scripts
Sites run on hosting without Node, so a script is served exactly as written. It is a classic script with no import, export or type="module", no TypeScript, no build step and no npm packages. The first line is // @ts-check, and every parameter and return value has JSDoc. Globals and libraries loaded with a tag are described in a .d.ts next to the module's scripts; don't declare again what the core's types/flute-globals.d.ts already declares.
{
"extends": "../../../tsconfig.strict.json",
"include": ["../../../types/flute-globals.d.ts", "Resources/assets/js/*.js", "Resources/assets/js/*.d.ts"]
}npx -y -p typescript@7.0.2 tsc -p app/Modules/Example/tsconfig.jsonA template loads the script with @at('Modules/Example/Resources/assets/js/example.js'), and the core adds defer and nonce to it. An inline <script> needs @nonce. onclick= handlers and hx-on are forbidden: the theme template check rejects them, and with "Block scripts the site did not issue" turned on in AdminSettingsSecurity the browser won't run them. A file longer than 500 lines is split into parts of about 400 lines, loaded together in one @bundle([...], 'js') list.
Insert text through textContent. In the admin, HTML from the server or a user goes through window.DOMPurify.sanitize(). The public site has no client-side sanitizer, so the server draws fragments there. A script that fetches JSON and builds the DOM by hand repeats the server markup and drifts away from the theme; htmx and wire exist for this.
Common mistakes
| Message or symptom | Cause |
|---|---|
Action "follow" handler must return an ActionResult. | the handler returned null or a string. Return ActionResult::make() even when there is nothing to do |
404 "Unknown error!" on /wire | the surface is not registered, or _surface or _action has a typo |
A lazy wire surface does not answer to the id it was registered under. in the log | the class's id() differs from the first argument of lazy() |
| the filter replaced the block with nothing | hx-select found no element in the response: the selector must exist both in the page and in its response |
| the action ran on someone else's record | the id from input() comes from the client. Check on the server that the record belongs to user()->getCurrentUser() |
The old FluteComponent components (Contracts\FluteComponentInterface) are built on Yoyo, and new code doesn't use them. Surfaces\SurfaceRegistry has nothing to do with interactivity: it holds rows and tabs in the player card and profile, listed in Extension points.