symfony 2 choice ajax validation fix

2019-09-04 09:50发布

问题:

I try something like that - Validating dynamically loaded choices in Symfony 2

but this when we get submited form check possible values - in my sitation any is correct.

i add modification to allow any value - like here

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $data = $event->getData();
        $event->getForm()->add('tags', 'tag', [
            'label'   => 'Sub Choice',
            'choices' => $data['tags'],
            'mapped'=>false,
            'required'=>false,
            'multiple'=>true,
        ]);
    });

but it not work - how to make it usable ?

tag is my input extens of choice (for js ajax chosen)

回答1:

ok i found problem. This example is ok but we need array_flip

here is working version

 $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $data = $event->getData();
        if(is_array($data['tags']))$data=array_flip($data['tags']);
        else $data = array();
        $event->getForm()->add('tags', 'tag', [
            'label'   => 'Sub Choice',
            'choices' => $data,
            'mapped'=>false,
            'required'=>false,
            'multiple'=>true,
        ]);
    });