Admin confirm over htmx htmx

An htmx GET to a state-changing admin action gets a confirm form in its target; Confirm posts the same URL with the token.

Options

OptionMeaning
_class('admin_post')->refusal($object, $action)In the action: null when it may run (a POST with the token); else the answer, for htmx htmx_confirm() or htmx_refused().
htmx_confirm($object, $action)With an HX-Target id: div.yf-admin-confirm (HX-Reswap: innerHTML, HX-Reselect: .yf-admin-confirm), Confirm = hx-post with the token and X-YF-Confirm: 1; without an id: HX-Redirect to the confirm page.
htmx_refused($answer)A POST without the token: 403, HX-Reswap: none, the text as a yf-toast event.

Example

Code

$post = _class('admin_post');
$hx = _class('htmx');
// the real helpers of the admin, on a demo action that changes nothing
if ($post->is_htmx() && ($_GET['hx'] ?? '') === 'purge') {
    if (main()->is_post()) {
        return $hx->_result($post->csrf_ok()
            ? '<div class="alert alert-success">Confirmed with the session token: a real action would purge now.</div>'
            : '<div class="alert alert-danger">Refused: the token is missing or wrong.</div>');
    }
    return $post->htmx_confirm('docs_demo', 'purge');
}
asset('htmx');
return '<div id="docs-ref-confirm-box" class="well">'
    . html()->button('Purge the demo cache', ['type' => 'danger', 'attr' => ['hx-get' => url('/@object/htmx/admin_confirm'), 'hx-vals' => '{"hx": "purge"}', 'hx-target' => '#docs-ref-confirm-box']])
    . '</div>';

Notes

  • The target needs an id (sent as HX-Target). After Confirm the action runs; a redirect of the module becomes HX-Redirect (yf_redirect::$HTMX_REDIRECT, framework redirects).
  • A boosted link and the history restore are page views: they get the confirm page, not the fragment (is_htmx()).
  • To skip the confirm, POST yourself: hx-post with hx-vals holding the token, or a form with token_input(). The whole POST / token / confirm rule of admin modules: misc admin_post.

See also: misc:admin_post, htmx/reswap, demo:security/admin_methods