New in Symfony 2.3: Buttons support in Forms
May 6, 2013 • Published by Fabien Potencier
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
The first time I read about this feature, I was sceptical at best. Why would you want to manage buttons in your forms as buttons are only a display thing? I was wrong and once more, Bernhard did a great job implementing this new feature.
As of Symfony 2.3, you can add buttons to your forms, like any other fields:
1 2 3 4
$form = $this->createFormBuilder($task)
->add('name', 'text')
->add('save', 'submit')
->getForm();
When rendering the form with the canonical {{ form_widget(form) }}
instruction, the button will be rendered as well. But that alone would not be
very interesting. So, what is it really about?
Submit buttons in forms are not really useful except for when there are more than one; the logic that processes the form will probably be different depending on the button that was clicked by the user:
1 2 3 4 5
$form = $this->createFormBuilder($task)
->add('name', 'text')
->add('save', 'submit')
->add('save_and_add', 'submit')
->getForm();
And that's a situation where managing buttons in the form framework starts to
make sense. From your controller, you can now check which button was clicked
with the new isClicked()
method and act accordingly:
1 2 3 4 5 6 7 8 9 10
if ($form->isValid()) {
// ... do something
// the save_and_add button was clicked
if ($form->get('save_and_add')->isClicked()) {
// probably redirect to the add page again
}
// redirect to the show page for the just submitted item
}
But there is more than that: the validation group can be different for each button. That comes in handy when working with wizard forms:
1 2 3 4 5 6 7 8
$form = $this->createFormBuilder($task)
// ...
->add('nextStep', 'submit')
->add('previousStep', 'submit', array(
// disable validation
'validation_groups' => false,
))
->getForm();
Of course, this feature is entirely optional and for forms with only one submit button, you can keep the current way of doing things.
This new feature is fully documented in the official documentation; but having a look at the documentation pull request might be more convenient.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
completly just in one file
Thanks
Wonderful addition, thanks!
Thanks !