Monday 6 May 2013

New in Symfony 2.3: Buttons support in Forms





Contributed by

Bernhard Schussek

in #6528.




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.






Be trained by Symfony experts
- 2013-05-13 Paris
- 2013-05-13 Cologne
- 2013-05-13 Paris
crawled from : Symfony

No comments:

Post a Comment