Reputation: 2039
I would like to do some transformation on the submitted data based on which button on my form was clicked. Here is the scenario:
chain
which holds the command chain.command
text field that holds the last command.Send
and Send chain
.When Send
is clicked, chain
is set to command
, erasing whatever was in it before. When Send chain
is clicked, however, the contents of command
are added to the end of chain
after a delimiter, effectively creating a chain of commands.
I need to be able to check to see which of these two buttons was clicked so that I can set chain
to the appropriate value.
Why am I not doing this in the controller? The problem is that I need to modify the value of chain
. Since I cannot modify the values of an already-submitted form, I need to do this in an event, I assume. As I mentioned above, I need chain
to either be equal to command
, or chain + [delimiter] + command
.
Upvotes: 1
Views: 1873
Reputation: 2039
Here is what I needed to do:
POST_submit
event because I couldn't transform the data after submission.isClicked()
of both buttons returned false
in other events, because the form hadn't been submitted yet.The solution is something like this:
$data = $event->getData();
if (isset($data['send']) {
// transform the values here
}
In other words, the only way to check if a particular button was clicked is to check to see if its name exists as an index in the array returned by $event->getData()
.
Upvotes: 2
Reputation: 3762
If I understood you correctly, you don't need an event at all. There is a built in method isClicked()
since @2.3. Example from documentation:
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
}
Link to chapter.
Update
Normally, the code I showed can be used in event - FormEvents::POST_SUBMIT
to be precise, but as you already pointed out, you can not modify form data after submission. To be honest I can't come up with perfectly working example, so I will share an idea hoping it will lead to something, or at least until someone else suggest something else.
How about you add a hidden non mapped field to your form. Then (assuming you are allowed to use javascript in your form) you can attach event listener on when form is submitted and based on which button was clicked you can populate that hidden field with specific value. After that you can add event listener to your FormType and read the value of this hidden field, using FormEvents::POST_SET_DATA
.
I am sorry I can not be more helpful as of now. If I came up with something I will edit my post.
Upvotes: 2