Skip to content

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).

  1. 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').
  2. Subsequent HTMX Request (POST /hx/req or GET /hx/req):
    • Htmx::handleEndpoint() resolves the registered component class via resolveRegisteredComponentClass().
    • SignedStateCodec verifies the HKDF-SHA256 hx__state signature and context claims (__uid, __sid, __ep, __pid, __adm).
    • hydrate() restores public properties from the verified state.
    • authorize() and authorizeAction($action) verify permissions.
    • For mutating verbs (POST, PUT, PATCH, DELETE), $session->CSRF->validate() is enforced automatically. For GET / QUERY, only query* methods are permitted.
    • executeAction() invokes the target method, then render() returns the updated HTML fragment.
<?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>";
}
}
  • setView(string $viewPath): Delegates HTML rendering to a PHP view file inside componentsPath, executed safely by ConfinedViewRenderer.
  • setEndpointUrl(string $url) / setStateKey(string $key): Overrides the component’s target endpoint URL or hx__state field key when nesting multiple components on one page.
  • enableRenderCache(int $ttlSeconds): Enables HtmxCache fragment caching for expensive read-heavy components.

Next steps