I'm working with Symfony PHP. I have a checkbox, and depending of it is checked or not, I want to display a combobox in a form. If the checkbox is checked, I want to display the combo with all options, but if it is not checked, I want to disable the combo, but the widget must have a default or hardcoded value when the form is saved. I don't know how to do, because when I set the combobox disabled, the form saves the widget as null, and I can't set a predefined value. Anyone can help me?
1 Answer
You can alter a form's submitted data in the bind() method. Use this is if you want to change the behaviour of the form depending on what the user has selected/submitted.
If you want to alter how the object is altered after form data has been validated and ready to be persisted to the database, then take a look at the updateObject() method.
class myForm
{
public function configure()
{
// configuration
}
public function bind($taintedValues = array(), $taintedFiles = array())
{
// I can alter the behaviour of the form here, depending on the data submitted
if (isset($taintedValues['do_not_store_my_personal_details'])) {
// Change the value of a form field. If the form doesn't pass validation, the user will see any information entered into the phone_number fields has been deleted
$taintedValues['phone_number'] = null;
}
return parent::bind($taintedValues, $taintedFiles);
}
public function updateObject($values = null)
{
if ($values === null) {
$values = $this->getValues();
}
// Override the data stored with the object
if ($values['do_not_store_my_personal_details'] == true) {
$values['phone_number'] = null;
}
return parent::updateObject($values);
}