Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

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 with. horrible of course, but how can this be done in a sane way?

View ImageType.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.