2

What is the value in using a hidden actionInput vs an action attribute on a form?

<form method="post">
    {{ actionInput('path/to/controller-action') }}
</form>

vs

<form method="post" action="/actions/path/to/controller-action">
</form>

I understand you get the actionTrigger automatically added, but you could use the actionUrl function to generate that as well.

1 Answer 1

2

Just like a lot of things in Craft or in computer science in general, there's multiple ways to do things.

The actionInput function is just a shortcut for outputting a hidden input:

<input type="hidden" name="whatever" value="whatever">

...much like {{ entry.title }} in Twig is really a shortcut in PHP for something like <?php echo twig_escape_filter(...) ?>.

However, the 2 snippets you posted are not necessarily equivalent.

When you put the "action" attribute on a form:

<form method="post" action="whatever">

... a web browser is actually sending a POST request to that location, versus when you leave it off:

<form method="post">

... a browser will POST to the current page.

The difference seems subtle but say your form has errors, you probably don't want to be POSTing to your controller "directly", you want to reload the same page. (And you don't typically don't want someone bookmarking your controller action.)

The older Craft 2.X documentation has a great little bit about this:

When you leave your form’s ‘action’ attribute blank, browsers will default to the current request’s URL. Which is great in the event that your controller needs to reload the previous page without a redirect. A common example of this is when the user’s input didn’t validate, and you want to pass the errors back to your template (ideally tucked away within a model).

Craft/Yii handles the nitty-gritty routing behind the scenes.

1
  • 1
    Gotcha thanks. The route params are the big difference from what I can tell, which you can sorta work around with flashes and session in your own controllers. This is mostly just coming up because we are playing with adding turbo.hotwire.dev and it doesn't play nicely with the action input. May 19, 2021 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.