Stateful Components & Actions
A stateful Component (Totoglu\Htmx\Component) encapsulates its public state, server actions, authorization, and HTML template in a single PHP class served through endpointUrl (/hx/req).
Component Lifecycle
Section titled “Component Lifecycle”- Initial Page Render (
$htmx->renderComponent('charter-inquiry', $props)):fill($props)populates public typed properties.mount()runs once on initial render for setup (loading defaults, initial page context).authorize()verifies the current user may view the component.render()outputs HTML containing$this->renderStatePayload()and$this->requestUrl('actionName').
- Subsequent HTMX Request (
POST /hx/reqorGET /hx/req):Htmx::handleEndpoint()resolves the registered component class viaresolveRegisteredComponentClass().SignedStateCodecverifies the HKDF-SHA256hx__statesignature and context claims (__uid,__sid,__ep,__pid,__adm).hydrate()restores public properties from the verified state.authorize()andauthorizeAction($action)verify permissions.- For mutating verbs (
POST,PUT,PATCH,DELETE),$session->CSRF->validate()is enforced automatically. ForGET/QUERY, onlyquery*methods are permitted. executeAction()invokes the target method, thenrender()returns the updated HTML fragment.
Mutating Actions & Validation Errors
Section titled “Mutating Actions & Validation Errors”<?php declare(strict_types=1);
namespace ProcessWire;
use Totoglu\Htmx\Component;
final class CharterQuoteComponent extends Component{ public int $yachtId = 0; public int $guests = 6; public bool $submitted = false;
protected function authorizeAction(string $action): bool { return $action === 'submitInquiry' || $action === 'queryEstimate'; }
public function submitInquiry(): void { $email = $this->wire()->sanitizer->email((string) $this->wire()->input->post('email')); if ($email === '') { $this->validationError('email', 'Please enter a valid contact email.'); return; }
$this->submitted = true; $this->wire()->htmx->response->trigger('charter:inquiry-sent', ['yachtId' => $this->yachtId]); }
public function render(): string { $actionUrl = $this->requestUrl('submitInquiry'); $state = $this->renderStatePayload(); $csrf = $this->wire()->session->CSRF->renderInput();
// Render form with $actionUrl, $state, $csrf, and any validation errors return "<form hx-post=\"{$actionUrl}\" hx-swap=\"outerHTML\">{$csrf}{$state}...</form>"; }}Custom Views, Endpoints & Render Caching
Section titled “Custom Views, Endpoints & Render Caching”setView(string $viewPath): Delegates HTML rendering to a PHP view file insidecomponentsPath, executed safely byConfinedViewRenderer.setEndpointUrl(string $url)/setStateKey(string $key): Overrides the component’s target endpoint URL orhx__statefield key when nesting multiple components on one page.enableRenderCache(int $ttlSeconds): EnablesHtmxCachefragment caching for expensive read-heavy components.