Symfony2 forms with multiple dependent fields

霸气de小男生 提交于 2019-12-12 02:52:22

问题


I am creating a registration from which have the following format.

If country changes then i need to change the child fields accordingly.

1- Country States Cities Suburbs

In my COMPANY BRANCH entity i am saving suburb key as one-many. Company branch located in which suburb.

if i change the company group then it should change the child's.

2- Company Group Company

In my COMPANY BRANCH entity i am saving company key as foreign key. One- many relationship. Company has many branches and one branch only belong to one company.

3- Branch address (text)

4- some other text fields.

QUESTION: How to achieve this either Embedded forms, collections or simple Ajax calls.

i have tried Dependent forms tutorial, but i have two dependencies. Country and Company group. For me its difficult to map the stuff in my project. If someone provide detail description how to do it. That would be great. Thanks,


回答1:


In my opinion the best way to achieve this is to set your child fields as "disabled", to set an empty value to each of them, and to attach a jQuery listener to each of your parent dropdown lists.

That way, you'll be able to get the values for your child fields with an ajax call to a controller which would send you back a JSON array.

For example, your first parent/child element is "Country" and "States" :

<select name="country_list">
    <option value="1">USA</option>
</select>

<select name="states_list">
    <option value="0">-- empty value --</option>
</select>

Then your jQuery should be something like this :

$("#country_list").change(function() {
    var countryId = $('#country_list').val();
    var callUrl = 'CONTROLLER URL TO CALL';

    // make your ajax call here
    $.ajax({
       url : callUrl,
       type : 'GET',
       dataType : 'json',
       success : function(response){
                     // populate the child list with the JSON values
                     $.each(response,function(key, value) {
                         $('#states_list').append('<option value=' + key + '>' + value + '</option>');
                     });

                     // enable the child list 
                     $('#states_list').prop('disabled', false);
                 }
    });
});

Of course your controller should return a JSON array.



来源:https://stackoverflow.com/questions/32062618/symfony2-forms-with-multiple-dependent-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!