Created
March 12, 2013 11:03
-
-
Save dbu/5142035 to your computer and use it in GitHub Desktop.
i needed a form type that determines based on the bound data if it
should be required or not (to make file upload required if we create
a new entity, but optional when editing the entity with the file.
as this happens in a embedded sonata, i have no way of knowing the actual
data when creating the form in the form builder. this is what i came up…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ImageType extends AbstractType | |
{ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
if ($options['required_auto'] && ! $options['required']) { | |
$builder->addEventListener(\Symfony\Component\Form\FormEvents::PRE_SET_DATA, array($this, 'determineRequired')); | |
} | |
} | |
public function setDefaultOptions(OptionsResolverInterface $resolver) | |
{ | |
$resolver->setDefaults(array('required_auto' => true, 'required' => false)); | |
} | |
public function determineRequired(FormEvent $event) | |
{ | |
$data = $event->getData(); | |
$form = $event->getForm(); | |
if (! $data->isNew()) { // my model data knows if it is new or not | |
$config = $form->getConfig(); | |
$reflection = new \ReflectionClass($config); | |
$reflection = $reflection->getParentClass(); | |
$prop = $reflection->getProperty('required'); | |
$prop->setAccessible(true); | |
$prop->setValue($config, true); | |
} | |
} | |
} |
This question have a answer on: https://knpuniversity.com/screencast/question-answer-day/symfony2-conditionally-required-field#play
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This might be a rather old problem but is still valid.
Altering the options of a form type based on its data still doesn't seem possible without hacks such as this.