Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version
WARNING: You are browsing the documentation for Symfony 3.3 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

How to Submit a Form with Multiple Buttons

How to Submit a Form with Multiple Buttons

When your form contains more than one submit button, you will want to check which of the buttons was clicked to adapt the program flow in your controller. To do this, add a second button with the caption “Save and add” to your form:

$form = $this->createFormBuilder($task)
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->add('save', SubmitType::class, array('label' => 'Create Task'))
    ->add('saveAndAdd', SubmitType::class, array('label' => 'Save and Add'))
    ->getForm();

In your controller, use the button’s isClicked() method for querying if the “Save and add” button was clicked:

if ($form->isSubmitted() && $form->isValid()) {
    // ... perform some action, such as saving the task to the database

    $nextAction = $form->get('saveAndAdd')->isClicked()
        ? 'task_new'
        : 'task_success';

    return $this->redirectToRoute($nextAction);
}

Or you can get the button’s name by using the getClickedButton() method of the form:

if ($form->getClickedButton() && 'saveAndAdd' === $form->getClickedButton()->getName()) {
    // ...
}

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.