Reputation: 3192
I have a collection in Symfony form with multiple buttons and I need to determine which button was clicked. I know It can be done calling isClicked()
method on that button element, but I'd like to map this clicked button into data class, is that possible?
My basic form:
$builder->add(
'items',
'collection',
[
'type' => new ItemForm(),
'label' => FALSE,
]
);
ItemForm
:
$builder->add(
'isRemoved',
'submit'
);
And data class for ItemForm
:
class ItemFormData
{
/**
* @var bool
*/
private $isRemoved = FALSE;
/**
* @return boolean
*/
public function isIsRemoved()
{
return $this->isRemoved;
}
/**
* @param boolean $isRemoved
*/
public function setIsRemoved($isRemoved)
{
$this->isRemoved = $isRemoved;
}
}
And what I need is to map TRUE to isRemoved
property if appropriate button was clicked. I'm using Symfony 2.7.
Upvotes: 3
Views: 659
Reputation: 3192
Actually, I've found the solution. It can be easily done using form events:
$builder->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$formData = $event->getData();
$form = $event->getForm();
if ($form['isRemoved']->isClicked()) {
$formData->setIsRemoved(TRUE);
}
}
);
Upvotes: 6
Reputation: 119
Peter.
I'm not sure that you can do like that.
IMO you can simple do something like that:
Create hidden field in form:
$builder->...
->add('isRemoved', 'hidden')
->...;
In template just simply render it:
{{ form_rest(form) }}
And set it field with JS:
$('#<form_selector>').on('submit', function () {
$('#<is_removed_vields_selector>').val();
});
Or use on button click event.
Upvotes: 0