Symfony3 Forms: How to know which button was clicked in the form?

advertisements

Symfony3 Forms: I have managed to build and render the form as shown below:

<form action="/member/john/actions" method="post" name="form">
    <input type="submit" value="Block John" name="block">
    <input type="submit" value="Remove from my friends" name="remove">
    <input type="hidden" value="LeiajURspTa9c8JEUYtvepki0b_CdL9dMWqEZxOYvfk" name="form[_token]" id="form__token">
</form>

When I click the the buttons "Block John" or "Remove from my friends", the controller routes it to the desired location (member_friend_actions) and it is able to show the debug dump values along with "Submitted!" text, before dying.

My controller with route "member_friend_actions" is set-up as shown below:

/**
 * A common post location to catch all operations like add/remove/cancel/block friends
 *
 * @Route("/{username}/actions", name="member_friend_actions")
 * @Method("POST")
 */
public function allActionsFriendAction(Request $request, User $friend)
{
    $form = $this->createAllActionsFriendForm($friend);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        //$clicked = $form->getData();
        $clicked = $form->getClickedButton()
        \Doctrine\Common\Util\Debug::dump($clicked);
        die("Submitted!");

    }

    return $this->redirectToRoute('member_profile', array("username" => $friend->getUsername()));
}

I want to know which button was clicked that brought it here (block or remove here; but there can be more buttons in other places). I tried using the methods:

$form->getData() => which gives array(0) { } and
$form->getClickedButton() => gives NULL, so are not helping.

How can this be achieved?


It depends how you added the SubmitType to your form. For example if you used something like this:

->add('block_john', SubmitType::class, array(
        'label' => 'Block John'
))

Then in your controller you can then use something like:

$form->get('block_john')->isClicked()

See this link for more info: http://symfony.com/doc/current/form/multiple_buttons.html