Search code examples
jqueryspring-mvcjqgridjqgrid-php

Jquery form serialize - Multiple select on jqgrid


I have a jqGrid where I am sending a string value to the colmodel for a particular property called "equipments". Everything is ok so far as the value is showing perfectly on the grid. I have also added an Add and Edit button and all is well and working fine, the forms are showing as expected. (Forgive the apparantly long post but its extremely easy to follow)

I modified field called equipments on the add form and injected my very own multiple select like this

colModel

            {name:'equipments',index:'equipments', width:6, editable:true, edittype:'custom',
              editoptions:{
                  custom_element:function(){                                  
                        return $('<div id="mytrensferselect"><div class="transfer"><select id="select1" multiple="multiple"></select><a href="#" id="addbutton">add</a></div><div class="transfer"><select id="select2" multiple="multiple"></select><a href="#" id="removebutton">remove</a></div></div>');  
                      },
                      custom_value:function(ele){
                                return ele.val();           
                      }                               
                  }                           
            }

Add Button - beforeShowForm option

                    bSubmit: "Save and New",
                    bCancel: "Cancel",
                    beforeShowForm: function(form) {
                            $.get('<c:url value="/moduleinstances/retrieveequipments?miId="/>' , function(data){  //load in my list of equipments as json string
                                var obj = jQuery.parseJSON(data);  //parse the resulting json in order to populate select1 and select2
                            $("#select1").html(obj.remaining);
                            $("#equipments").removeAttr("name").removeAttr("id").removeClass("customelement");
                            $("#select2").html(obj.owning).attr("name","equipments").attr("id","equipments").addClass("customelement");
                            $('#addbutton').click(function() {
                                return !$('#select1 option:selected').remove().appendTo('#equipments');
                            });
                            $('#removebutton').click(function() {
                                return !$('#equipments option:selected').remove().appendTo('#select1');
                            });
                            }); //End AJAX CALL abd CUSTOM Transfer Select logic

//Start Logic For Custom Save and Close Button

                        $('<a href="#">Save and Close<span class="ui-icon ui-icon-disk"></span></a>').click(function() {
                            if($.isNumeric($(form.selector+" #rateOfPay").val())){
                                $.post('<c:url value="/moduleinstances/create/${courseModule.id}"/>', $('#FrmGrid_list2').serialize() , function(data){
                                    $('#list2').trigger("reloadGrid");
                                    $("#cData").trigger('click');
                                }); 
                            }else{
                                    alert("Pay Rate must be numeric");
                            }                      
                        }).addClass("fm-button ui-state-default ui-corner-all fm-button-icon-left")
                        .prependTo("#Act_Buttons>td.EditButton");
                        $('#title').attr('value','${courseModule.name}'); 
                        $("#leadLecturer").val( '${lecturer.id}' );
                    }

Here is the relevant part of my add form.

enter image description here

The functionality is working fine when I click on Save and New which is the submit button I decleared via bSubmit: "Save and New" above. The postdata for this is shown on your left. When I click on the Save and close button which is my custom button. The post data is shown on your right.

enter image description here

The Save and Close uses jquery to serialize the entire form like this $('#FrmGrid_list2').serialize(), this is where it gets hairy.

If we look at what was posted for equipments in both cases we can see the name difference. It seems like jqGrid is intelligent enough to figure out its an array of values, while jquery serialize() didn't in the way i want it to. I am using Spring MVC 3.0 and here is where my equipments data goes to the action.

@RequestMapping(value = "update", method = RequestMethod.POST)
public @ResponseBody String update(Model uiModel,
        @RequestParam("id") Long mId,
        @RequestParam("campus") Long cId,
        @RequestParam("leadLecturer") Long lId,//This is actually a Person ID.
        @RequestParam("semesterStartDate") @org.springframework.format.annotation.DateTimeFormat(pattern = "MMMM dd, yyyy") java.util.Calendar semesterstartdate,
        @RequestParam("semesterEndDate") @org.springframework.format.annotation.DateTimeFormat(pattern = "MMMM dd, yyyy") java.util.Calendar semesterenddate,
        @RequestParam("tuitionStartDate") @org.springframework.format.annotation.DateTimeFormat(pattern = "MMMM dd, yyyy") java.util.Calendar tuitionstartdate,
        @RequestParam("tuitionEndDate") @org.springframework.format.annotation.DateTimeFormat(pattern = "MMMM dd, yyyy") java.util.Calendar tuitionenddate,
        @RequestParam("rateOfPay") Double rateOfPay,
        @RequestParam("equipments[]") ArrayList<String> equipments,
        HttpServletRequest httpServletRequest) { Bla...bla...bla }

Look at the very last @RequestParam, Spring is capable of handling the array of items, but when it gets posted with jQuery serialize, the action cannot find the paramiter called "equipments[]" I saw a link here about this, can I simply do this instaed?

Any ideas


Solution

  • Ok so for the benefit of others, what I did to solve the problem was manually serialize the form as a well formed json-string and send that string variable to the server. Something like

    //select each form element and get its value using jquery
        var customPostData = '({ sessionNumber: "'+$("#sessionNumber").val()+'", sessionDate: "'+$("#sessionDate").val()+'", starttime: "'+$("#starttime").val()+'", endtime: "'+$("#endtime").val()+'", sessionStatus: "'+$("#sessionStatus").val()+'", sessionType: "'+$("#sessionType").val()+'", topic: "'+$("#topic").val()+'", id: "'+myId+'", equipments:'+selectedequips.toSource()+'})';
        var submitdata = eval('(' + customPostData + ')'); //use parseJSON insted of eval
    
        $.post("my-url", submitdata , function(data){
           //use the returning information in the data variable
        });