Question

I am creating a dynamic form similar to what is wanted here.

Well i managed to get it working. But i would like that the native fields of the type could appear AFTER the dynamic dropdowns. This is not out of box because dropboxes are added to the form in the PRE_SET_DATA event (after the form is build and name field is added) as you can see:

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('country', 'entity', array(
        'class'=>'TestBundle:Country', 
        'property'=>'name', 
        'property_path'=>false //Country is not directly related to City
    ));
    $builder->add('name');

    $factory = $builder->getFormFactory();

     (...)

     $builder->addEventListener(FormEvents::PRE_SET_DATA, function (DataEvent $event) use ($refreshStates, $setCountry)
    {
        $form = $event->getForm();
        $data = $event->getData();

        if($data == null)
            return;

        if($data instanceof City){
            $country = ($data->getId()) ? $data->getState()->getCountry() : null ;
            $refreshStates($form, $country);
            $setCountry($form, $country);
        }
    });

I tried to do the same for the name field adding this to the beginning of buildForm Function:

$addBaseFields = function ($form) use ($factory)
    {
        $form->add($factory->createNamed('text', 'name'));
    };

and then i added it in the event:

 $builder->addEventListener(FormEvents::PRE_SET_DATA, function (DataEvent $event) use ($refreshStates, $setCountry)
    {
        $form = $event->getForm();
        $data = $event->getData();

        if($data == null)
            return;

        if($data instanceof City){
            $country = ($data->getId()) ? $data->getState()->getCountry() : null ;
            $refreshStates($form, $country);
            $setCountry($form, $country);
            $addBaseFields($form);
        }
    });

This kind of works. But, html5 field validation stopped working. For example: if i define name as 'number' type instead of 'text': $form->add($factory->createNamed('number', 'name')); it will accept anything, any text.

Is there a better way to do this so i can still use number browser validation?

Was it helpful?

Solution

This is a Symfony Bug on versions 2.0 and 2.1 and has nothing to do with Form Events.

When a string such '9fgda' is input in a 'number' field, there is no validation error and the string value '9fgda' is converted in the numeric value '9' and gives no error.

This is because of NumberFormatter and should be fixed for version 2.2.

More information on this bug here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top