SCENARIO
There are times when there is a need to have the multiselect data updated / refreshed based on the selection of some other fields. This link provides a classic example / requirement.
SOLUTION
Lets take the similar example to reach to the solution. What is needed is to update the list of all the actors based on the selection of the module. Following is a pattern that can be used to achieve the same.
- Create a JS file which will have a code to hook to the module_id (on change). What the code will do is – it will hit an ajax call on the backend – passing up the module_id selected by the user. In return it gets a json data that have all the actors in list that are not related to module_id selected.
- Now before you update the list of the mutiselect, what you can do is grab all the values of the options that the user had already selected. You can achieve the same by following piece of code.
var items[]; $('#field-actors option:selected').each(function(){ items.push($(this.val()); });
- Now once you have grabbed the selected elements, empty up the field-actors. Now add up the newer elements to field-actors using jquery.
$("#field-actors").append("<option value='2999'>Amit Shah</option>"); ////this can be used to add the actors ............................. $("#field-actors").append("<option value='1999' selected='selected'>AAAAAAA</option>"); /////This way u can set it to have it selected
The above is just a sample as how u can add the same. For each element that you plan to add – if you found the same as it been selected by the user earlier, you can set it to be selected. Else you can have it set as regular option as shared above.
- Now what we have achieved is a refreshed / updated list of actors that dose not belong to module_id selected. Now simply update the options, refresh. The same can be achieved by the following piece of code.
$("#field-actors").multiselect('destroy'); $("#field-actors").multiselect();
There, its all the piece of logic you can use to achieve a similar solution for your issues / requirements.
Happy GCing 🙂