Validate ajax dynamic checkbox fields (this value is not valid)

715 views Asked by At

I have a form with tags which have dependencies with a category field

Category 1
    tag a
    tag b
    tag c

Category 2
    tag d
    tag e
    tag f

...

When loading the page, I have "Category 1" and "the list of his tags" Then when I change the category to "Category 2", I replace the list of tags via ajax.

When I submit the form, I get "This value is not valid". I guess that it's because the fact that the form expect values from the initial list.

So, I don't know how to proceed to get my tags to be validated.

Here is the code which generate the form

->add('category', null, array(
    'choices' => $this->cat_tree, 
    'label' => 'Category',
    'required' => true, 
    'empty_value' => '', 
))
->add('tags', 'entity', array(
    'class' => 'MyappServicesBundle:Category',
    'query_builder' => function(EntityRepository $er) use ($parent_id)  {
        return $er->createQueryBuilder('c')
            ->where('c.parent = :parent_id')
            ->setParameter('parent_id', $parent_id)
            ->orderBy('c.title', 'ASC');
    },
    'required' => false, 
    'multiple' => true,
    'expanded' => true, 
    'label' => 'Tags',
))

And here is the ajax code which replace the tags list

$('#myapp_servicesbundle_category').change(function() {
    $.post( 
        "/tag/ajax/search", 
        { parent_id: $(this).val() }, 
        function( data ) {
            var newtags = '';   
            jQuery.each( data, function( i, val ) {         
                newtags += '    <input type="checkbox" value="'+val.id+'" name="myapp_servicesbundle[tags][]" id="myapp_servicesbundle_tags_'+val.id+'">';
                newtags += '    <label for="myapp_servicesbundle_tags_'+val.id+'">'+val.label+'</label>';
            });
            $('#myapp_servicesbundle_tags').html(newtags);              
        }, "json"
    );
}); 

Thanks in advance for your help

1

There are 1 answers

1
oligan On BEST ANSWER

from my experience you have to use an eventListener in Symfony. There is a quite clear example in the doc (more detailed in english than in french, be careful).

http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-submitted-data