MehdiB
MehdiB

Reputation: 906

Symfony :form fields not submitted after ajax call

I have a form which contains 3 select boxes. second select box options depend on the first select options. and the third select options depend on the second select options. I use ajax to populate options in the second and third select boxes. However after submitting the form, values of second and third selects are not posted.

this is my FormType:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Typ', EntityType::class, array(
                'class' => 'AppBundle:MaterialTypes',
                'placeholder' => 'Choose an option'
            ))
            ->add('Kategorie', ChoiceType::class, array(
                'placeholder' => 'Choose an option',
                'mapped' => false,
                'choices'  => array(),
                'choices_as_values' => false
            ))
            ->add('Bezeichnung', ChoiceType::class, array(
                'placeholder' => 'Choose an option',
                'mapped' => false,
                'choices'  => array(),
                'choices_as_values' => false
            ))
            ->add('anzahl',null, array('required'=> true))
            ->add('Preis',null, array('required'=> true));
        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $event->stopPropagation();
        }, 900);
    }

and this is the Ajax call:

var typeId = $('#Typ').val();
$.post( "/app_dev.php/material/"+typeId,
function( data ) {
    $('#Kategorie').empty();
    $('#Bezeichnung').empty();
    var result = JSON.parse(data);
    var options ='<option value="" disabled selected>Choose an option</option>';
    for (var i = 0; i < result.length; i++) {
        options +='<option value="'+result[i]['id']+'">'+result[i]['name']+'</option>'
    }
    $('#Kategorie').append(options);
});

The type (first select) is posted but the other 2 not. What am I missing?

Upvotes: 0

Views: 430

Answers (1)

Kep
Kep

Reputation: 5857

Check the docs for jQuery.post, the 2nd argument is the data to be POSTed - either as plain object or in string form.

You might aswell want to make use of the Twig path() function to save you from rewriting stuff later:

var typeId = $('#Typ').val();

var url = '{{ path('your_route_name', {'type': '__TYPE__'}) }}';

url = url.replace('__TYPE__', typeId);

$.post(
    url,
    $("#yourForm").serialize(),
    function( data ) {
        $('#Kategorie').empty();
        $('#Bezeichnung').empty();
        var result = JSON.parse(data);
        var options ='<option value="" disabled selected>Choose an option</option>';
        for (var i = 0; i < result.length; i++) {
            options +='<option value="'+result[i]['id']+'">'+result[i]['name']+'</option>'
        }
        $('#Kategorie').append(options);
    }
);

Upvotes: 3

Related Questions