I am trying to use a form class for add & edit. In add mode, iconFile is required. In edit mode, iconFile is optional (to replace the current icon). How can I acheive this?
I tried setting a mode in the constructor
class ItemForm extends AbstractType {
public function __construct($mode) {
$this->mode = $mode;
}
public function getDefaultOptions(array $opts) {
if ($mode == 'add') {
return array('validation_groups' => array('Default', 'add'));
} else {
return array('validation_groups' => array('Default'));
}
}
}
// doctrine entity, data_class of form
class Item {
/**
* @Assert\NotBlank(groups={"add"})
* @Assert\Image
*/
protected $iconFile;
}
// creating the form in controller
$form = $this->createForm(new ItemForm($mode));
Problem is even in edit mode, I still need to select an image. HTML5 validation triggers
In your
ItemFormconstructor, you are setting$modeto$this->mode, but you are then trying to access$modefromgetDefaultOptions().$modeobviously doesn’t exist within this scope – try changing to the following: