1

I am using the following code to add a new record.

jQuery("#list").jqGrid('editGridRow',"new",{height:545, width:425,recreateForm:true,reloadAfterSubmit:false,addedrow:'first',closeAfterAdd:true,top:110,left:350,modal:true});

I am using reloadAfterSubmit:false which means that when the new record is added to the grid, the ID field which I have is blank.

Can someone explain VERY simply how to get the ID of the new record and put it into the ID field in my grid.

I have found a previous answer here which seems to be what im looking for but I cant understand how to get it to work. The documentation says afterSubmit: function (response,postdata) {return [true, '', new_id];} but I have no how to implement this.

Im new so I need it put very simply.

Thanks for any help.

UPDATE: SERVER RESPONSE: response.responseText

( ! ) Notice: Undefined offset: 1 in D:\wamp\www\EstimateTracker\UpdateEstimates.php on line 32 Call Stack #TimeMemoryFunctionLocation 10.0036402872{main}( )..\UpdateEstimates.php:0
( ! ) Notice: Undefined offset: 2 in D:\wamp\www\EstimateTracker\UpdateEstimates.php on line 32 Call Stack #TimeMemoryFunctionLocation 10.0036402872{main}( )..\UpdateEstimates.php:0 String

UPDATE 2:

$(function () {
    $("#list").jqGrid({
        url:'GetEstimates.php',
        datatype: 'xml',
        mtype: 'GET',
        colNames:['ID','Campaign Name','ClientsID','Client Name','Buyer Name','Client Ref','Description','Sales','Estimator', 'Date Received', 'Date Required','Status','Product Type','Date Submitted','Price (&pound)', 'Keren No.','Reason Lost','Won Price (&pound)','Notes'],
        colModel :[ {name:'ID', key:true,index:'ID', width:45,align:'center',editable:true,editoptions:{readonly:true,size:10, height:5}, {name:'CampaignName', index:'CampaignName', width:175, align:'left',editrules:{required:true},editable:true,editoptions:{size:35}}, {name:'ClientsID', index:'ClientsID', width:120, align:'left',editable:true,hidden:true}, {name:'ClientName', index:'ClientName', width:120, align:'left',editrules: required:true,custom_func:notEmpty,custom:true},editable:true,edittype:'select', editoptions:{dataUrl:'ClientDropDownGrid.php',dataInit: function () {
        var thisval = $("#ClientsID").val();
        $.get('GetBuyersGrid.php?id='+thisval, function(data) {
            var res = $(data).html();
            $("select#BuyerName").html(res);
        }); // end get
    }//end func
    ,dataEvents:[{type:'change',fn: function(e) {
        var thisval = $(e.target).val();
        $.get('GetBuyersGrid.php?id='+thisval, function(data){
            var res = $(data).html();
            $("select#BuyerName").html(res);
        }); // end get
    }//end func
    } // end type
    ] // dataevents
    }}, 
    {name:'BuyerName', index:'BuyerName', width:100, align:'left',editable:true,edittype:'select',editoptions:{dataUrl:'BuyerDropDownGrid.php'}},
    {name:'ClientEstimateRef', index:'ClientEstimateRef', width:125, align:'left', align:'left',editable:true,editoptions:{size:25}},
    {name:'Description', index:'Description', width:125, align:'left', align:'left',editable:true,editoptions:{size:25}},
    {name:'SalesName', index:'SalesName', width:100, align:'left',editrules:{required:true,custom_func:notEmpty,custom:true},editable: true,edittype:'select',editoptions:{dataUrl:'SalesDropDownGrid.php'},formoptions:{elmsuffix: '<a id="AddSales" href="AddSales.php">Add Sales</a>' }},
    {name:'EstimatorName', index:'EstimatorName', width:100, align:'left',editrules:{required:true,custom_func:notEmpty,custom:true},editable: true,edittype:'select',editoptions:{dataUrl:'EstimatorDropDownGrid.php'} },
    {name:'DateReceived', index:'DateReceived', width:80, align:'center',editrules:{required:true,custom_func:isValidDateRec,custom:true},editable:true,editoptions: {size: 15, maxlength: 10,dataInit: function(element) {$(element).datepicker({dateFormat: 'dd/mm/yy'}) } }}, 
    {name:'DateRequired', index:'DateRequired', width:80, align:'center',editrules:{required:true},editable:true,editoptions: {size: 15, maxlength: 10,dataInit: function(element) {$(element).datepicker({dateFormat: 'dd/mm/yy'}) } }}, 
    {name:'Status', index:'Status', width:100, align:'left',editable: true,edittype:'select',editoptions:{dataUrl:'StatusDropDownGrid.php', defaultValue:'4'} },
    {name:'ProductType', index:'ProductType', width:100, align:'left',editrules:{required:true,custom_func:notEmpty,custom:true},editable: true,edittype:'select',editoptions:{dataUrl:'ProductTypeDropDownGrid.php'} },
    {name:'DateSubmitted', index:'DateSubmitted', width:80, hidden:false, align:'center',editable:true,editoptions: {size: 15, maxlength: 10,dataInit: function(element) {$(element).datepicker({dateFormat: 'dd/mm/yy'}) } }},
    {name:'Price', index:'Price', width:60, align:'right',editrules:{required:true,custom_func:isCurrency,custom:true},editable:true, formatter:currencyFmatter, unformat:unformatCurrency,editoptions:{size:15,defaultValue:'0.00'}, formoptions:{elmsuffix: 'GBP'}},
    {name:'KerenNo', index:'KerenNo', width:80, align:'left',editable:true,editoptions:{size:20}},
    {name:'ReasonLost', index:'ReasonLost', width:120, align:'left',editable: true,edittype:'select',editoptions:{dataUrl:'ReasonLostDropDownGrid.php'} },
    {name:'WonPrice', index:'WonPrice', width:60, align:'right',editrules:{required:true,custom_func:isCurrency,custom:true},editable:true, formatter:currencyFmatter, unformat:unformatCurrency, editoptions:{size:15,defaultValue:'0.00'}, formoptions:{elmsuffix:'GBP'}},
    {name:'Notes', index:'Notes', width:125, align:'left', align:'left',editable:true,edittype:'textarea',editoptions:{dataInit: function(elem){$(elem).width(200); $(elem).height(45);}}}
    //{name:'total', index:'total', width:80, align:'right'}, 
    //{name:'note', index:'note', width:150, sortable:false} 
    ],
        pager: '#pager',
        rowNum:20,
        rowList:[10,20,30],
        sortname: 'ID',
        sortorder: 'asc',
        viewrecords: true,
        gridview: true,
        caption: 'Estimates',
        width:880,
        height:400,
        multiselect:true,
        editurl:'UpdateEstimates.php',
        shrinkToFit:false
    });
    //edit row
    $("#editButton").click(function(){
        var gr = jQuery("#list").jqGrid('getGridParam','selrow');    
        if( gr != null ) jQuery("#list").jqGrid('editGridRow',gr,{height:545, width:425,recreateForm:true,reloadAfterSubmit:false,closeAfterEdit:true,top:110,left:350,viewPagerButtons:false,modal:true,beforeShowForm: function(form) { $('#tr_DateSubmitted', form).show();}});
        else alert("Please Select Row");
    });

    //add row
    $("#addButton").click(function(){
        //var gr = jQuery("#list").jqGrid('getGridParam','selrow');
        jQuery("#list").jqGrid('editGridRow',"new",{height:545, width:425,recreateForm:true,reloadAfterSubmit:false,afterSubmit: function(response){return [true,'','45765'];},addedrow:'first',closeAfterAdd:true,top:110,left:350,modal:true});
    });

});
Community
  • 1
  • 1
JC75
  • 77
  • 2
  • 4
  • 12
  • 1
    did you try `reloadAfterSubmit:true`? – jeffery_the_wind Apr 09 '12 at 17:26
  • 1
    yes, this works but the newly added record disappears when you reload the data. I want the newly added record to be displayed as the first record in the grid – JC75 Apr 09 '12 at 17:30
  • You can check my answer, if you set the `sortname` and `sortorder` attributes of the grid, then your newly added row should show up first. – jeffery_the_wind Apr 09 '12 at 17:36
  • Hi Jeffrey - I have search criteria linked to the grid which means if i reload the grid , the newly added record wont neccesarily be displayed at all. – JC75 Apr 09 '12 at 17:54
  • @JC75: You can read [here](http://meta.stackexchange.com/a/22189/147495) how to format the code (or HTML fragmant) which you include in the text of your question. – Oleg Apr 10 '12 at 20:03

2 Answers2

1

The answer don't contains the code which you included. It just describes that afterSubmit should get the id of the new added row from the server response in some way and then returns [true, '', new_id] where new_id is the id of new row.

In the simplest form you can return the id of the new added row just in the body of the server response. So the value of the id will be probably in response.responseText. In the case you should use

afterSubmit: function (response) {
    return [true, '', response.responseText];
}
Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Hi Oleg - Thanks for the quick response. I have put that bit of code in and it gives me an error saying object required jquery-1.5.2.min.js. When you say the value of the id is in the server response, how do i get to the id? – JC75 Apr 09 '12 at 17:43
  • @JC75: You wrote about "bit of code", but I don't found any. To answer on your question I need know how the server response on `'editGridRow',"new"` looks like. You can use [Fiddler](http://www.fiddler2.com/fiddler2/), [Firebug](http://getfirebug.com/) or "Network" tab of Developer Tools of the IE or Chrome to catch the HTTP traffic. The exact code of `afterSubmit` can depend from other jqGrid options which you use. Especially the `ajaxEditOptions` (if you use it) can change it. – Oleg Apr 09 '12 at 17:56
  • Hi Oleg - the bit of code was the bit you gave me: 'afterSubmit: function (response) { return [true, '', response.responseText]; } ' OK I will try and post the server response. Thanks for your help so far. – JC75 Apr 09 '12 at 17:58
  • Hi Oleg - I dont know how to catch the server response. Im using Developer Tools in IE8. Any ideas? – JC75 Apr 09 '12 at 18:31
  • Hi Oleg - Sorry i think ive managed it. I have had to post the server response in the question as it is too long to post as a comment. – JC75 Apr 09 '12 at 18:43
  • Hi Oleg - I have given up for today. Life is too short!!! I might come back to it at a later time. Thanks for your help. – JC75 Apr 09 '12 at 19:16
  • @JC75: The server response which you posted contains information about errors in your server code instead of the ID of the new added row. So you should first debug your server code to make it working. – Oleg Apr 09 '12 at 19:28
  • OK Thanks Oleg. I will try again in the morning! Sorry if i seem very slow!! You are very patient! – JC75 Apr 09 '12 at 19:38
  • @JC75: You are welcome! We can't solve all our problems in one day. – Oleg Apr 09 '12 at 19:39
  • Hi Oleg - I have managed to debug my server code and it is working now. My server response is now returning the ID of the newly added record. I now have this in my code `'afterSubmit: function(response){return [true,'',response.responseText];}` Not sure what to do now to get the ID into the grid? Can you help? Thanks – JC75 Apr 10 '12 at 10:26
  • @JC75: Is the above code of `afterSubmit` not already work? How exactly the server responds looks like? Do you tried "Network" tab of Developer Tools of the IE to catch the HTTP traffic? Press "F12" to start Developer Tools, click on "Nefwork" tab (submenu bar), click on "Start capturing". Alternatively you can just insert `alert(response.responseText);` in the `afterSubmit`. – Oleg Apr 10 '12 at 10:39
  • Hi Oleg - Im not sure what the code `afterSubmit: function(response){return [true,'',response.responseText];}` is doing? I have put in `alert(response.responseText);` and I get the ID (eg. '4572'). But the ID in my grid is still blank - Thanks – JC75 Apr 10 '12 at 11:00
  • @JC75: You should just use `jquery.jqGrid.src.js`, set breakpoint inside of `afterSubmit` and debug some next steps inside of `editGridRow` where the returned value are used. You should find your error very quickly. – Oleg Apr 10 '12 at 11:57
  • Hi Oleg. I have debugged as you said. But there is no error? In debug it gets to `addRowData oper="add" id="45757"` 45757 being the ID of the record I just added and it has all the data for each field (eg Name,Date,Description) but the ID field is blank. I dont understand how to populate the ID grid field of the new record with my response.responseText. Hope this makes sense! – JC75 Apr 10 '12 at 14:33
  • Hi Oleg - Someone has suggested using the `setcell` method, which I have used in the `afterComplete` event. This sets the value of the ID cell to be the response.responseText. It seems to work. Not sure if this is the best way or not? – JC75 Apr 10 '12 at 15:02
  • @JC75: We spend so many time in the discussion of the subject. Why you not post here the server response on `editGridRow ("new"`? I described you step by step how you get it. The usage of `afterSubmit` (not `afterComplete`!!!) is the correct way. jqGrid use the returned value (see [here](https://github.com/tonytomov/jqGrid/blob/v4.3.1/js/grid.formedit.js#L707)) and then use `addRowData` to add the data. So no additional call of `setcell` method is needed. – Oleg Apr 10 '12 at 15:24
  • The server response is the ID of the record eg(45757 or 45758). It has two squares in front of it. Is this the problem? – JC75 Apr 10 '12 at 15:31
  • My code is now `jQuery("#list").jqGrid('editGridRow',"new",{height:545, width:425,recreateForm:true,reloadAfterSubmit:false,afterSubmit: function(response){return [true,'',response.responseText]},addedrow:'first',closeAfterAdd:true,top:110,left:350,modal:true});` The responseText is the ID of the new record. Everything works except the ID field in my grid is blank! – JC75 Apr 10 '12 at 15:36
  • @JC75: So is the server response: `[45757]` or `["45757"]`? Is `response.responseText` equal to `[45757]` or `response` is equal to `[45757]`? The `[45757]` or `["45757"]` means that the server return **array** of ids instead of id itself. In the case you can modify the body of `afterSubmit` from `{return [true,'',response.responseText]}` to `{return [true,'',$.parseJSON(response.responseText)[0]];}` – Oleg Apr 10 '12 at 17:07
  • OK. But how do I get the response.responseText into the cell in the grid? Is this automatic? – JC75 Apr 10 '12 at 19:09
  • @JC75: I wrote before that jqGrid uses [addRowData](https://github.com/tonytomov/jqGrid/blob/v4.3.1/js/grid.formedit.js#L714) to add new row to the grid. The `addRowData` has id parameter. If you use `afterSubmit` the value of id will be `ret[2]` where `ret` is array returned by `afterSubmit` (see [here](https://github.com/tonytomov/jqGrid/blob/v4.3.1/js/grid.formedit.js#L682)). Do you implemented my last suggestion? Do you have correct id of the new added row? – Oleg Apr 10 '12 at 19:20
  • Is this the rowid or the id stored on the database? – JC75 Apr 10 '12 at 19:26
  • @JC75: If you fill the grid correctly it should be *the same*. You never posted the full code which you use and never posted JSON data returned from the server. So I don't know why you have different id and rowid values. In any way if you has column in the grid which contains the database id you can add `key: true` to the column. In the case jqGrid will use rowid the same as the values from the column. – Oleg Apr 10 '12 at 19:30
  • I have hard coded the response.responseText in `afterSubmit`,it is now `{return [true,'','45757']}` and it still doesnt work? – JC75 Apr 10 '12 at 19:44
  • @JC75: Sorry, but you just spend my time. I wrote you before that to be able to help you one need 1) to see jqGrid definition which you use 2) to see the exact JSON response from the HTTP traffic. Without the things I see no sense to continue the discussion. Moreover stackoverflow is not a help forum. Nobody will do your job. The code which I posted you should solve the problem. If it don't solve it you have another bugs in another parts of your code. You should debug your code to find the reason. I can't debug it for you especially without ever have seen it. – Oleg Apr 10 '12 at 19:50
  • the response is just the 45757. I dont know what more i can say? Should it be more? Should it be an array of the whole record? I have pasted the jqgrid in my question. – JC75 Apr 10 '12 at 19:54
  • @JC75: You wrote before that the response is 45757, next you wrote about two squares in front of it. So I still don't know what is the real response. I described you step by step how to catch the HTTP traffic with respect of Developer Tools and posted links to more comfortable tools Fiddler and Firebug. Why you don't use it and not post the full response inclusive the HTTP headers? – Oleg Apr 10 '12 at 19:57
  • @JC75: By the way I don't see any jqGrid definition (the code which creates the grid). Where you post it? – Oleg Apr 10 '12 at 19:59
  • Its not easy debugging you know! Its not exactly user friendly! I will try again. – JC75 Apr 10 '12 at 20:06
  • @JC75. First of all you should catch the HTTP traffic. See [here](http://msdn.microsoft.com/en-us/library/gg130952(v=vs.85).aspx) how to use IE developer tools and [here](http://www.fiddler2.com/Fiddler/help/video/default.asp) how to use Fiddler. Debugging with respect of IE Developer tools seems very comfortable for me. You should just set breakpoint on the line inside of `afterSubmit`. You can examine here exactly `response.responseText` or any other data and goes step by step in the jqGrid code. You should use of cause `jquery.jqGrid.src.js` instead of `jquery.jqGrid.min.js`. – Oleg Apr 10 '12 at 20:24
  • Just to clarify. The `addrowdata` only needs the id of the record and it will automatically add the record and all its fields into the grid? – JC75 Apr 10 '12 at 20:24
  • Thanks again for all your help Oleg! I do appreciate it! I will sit down tomorrow and go through all your advice again properly. Sorry if I have bothered you too much. Im sure this should be easy. It must just be me! thanks – JC75 Apr 10 '12 at 20:28
  • @JC75: I don't sure what you mean under "**automatically** add". It is just a method which add new `` row in the ``. It get the id of the `` (named as rowid) from the first parameter and use the second parameter to construct the cell content (the content of `
    `) for the new row. With the last parameters one can specify the position of the new row relatively to existing rows.
    – Oleg Apr 10 '12 at 20:30
  • @JC75: You are welcome! I recommend you to read the videos about Fiddler tool from [here](http://www.fiddler2.com/Fiddler/help/video/default.asp). The tool saved a lot of my time since I use it. – Oleg Apr 10 '12 at 20:32
  • OK Thanks again Oleg. I will go away and take a look – JC75 Apr 10 '12 at 20:34
0

You can try this for your new record function:

jQuery("#list").jqGrid('editGridRow',"new",{
    height:545,
    width:425,
    recreateForm:true, 
    addedrow:'first',
    closeAfterAdd:true,
    top:110, 
    left:350,
    modal:true,
    afterComplete: function(response, postdata, formid) {
        //force update of row data @ row 0 and column = ID, change the name of ID if your column name is different.  
        //We are using row 0 because we are assuming your new data is not in the first row
        $('#list').jqGrid('setCell', 0, 'ID','','','',true);
    }
});

This should reload the grid after you submit, if your submit was successful and your changes were saved to your data source, then when the grid reloads it will populate with the newly saved data, including the new ID.

To make the new ID show up as the first record, you need to set the sortname: 'ID' option in your grid and also sortorder: 'desc'. Then when you reload the grid, the highest ID will show up first.

** EDIT **

It looks like you can use the setCell method, and set the forceup property to true. check it out here: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods

jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160
  • But when the grid reloads the new record wont neccesarily be the first record anymore. It will go to its place in whatever the default sort is. – JC75 Apr 09 '12 at 17:41
  • I think I need reloadAfterSubmit:false. because the new record I add may not show up in the refreshed grid if it doesnt match the search criteria selected – JC75 Apr 09 '12 at 17:47
  • I see, is the new ID automatically generated by the database on submit, or do you give the value when editing the new record form? – jeffery_the_wind Apr 09 '12 at 19:20
  • it is automatically generated by the database on submit – JC75 Apr 09 '12 at 19:23
  • I'm sorry I have done a little looking for you, and it seems that you should just be able to use the `addedrow` property, and your row should be added there. I bet that jqGrid is using the `postdata` string to update the new row, which will NOT contain the ID of your new row. You would need to query the database again to get the newly generated ID. I did not find how to change the ID field with programming without editing, but I think you could utilize the `afterComplete` function, return the new ID in the `response` from your AJAX script, then update the ID field this way. – jeffery_the_wind Apr 09 '12 at 19:43
  • OK Thanks Jeffery - I will have a look in the morning! Thanks for your help – JC75 Apr 09 '12 at 19:54
  • @JC75 - i found something that might work, check my answer above for the `setCell` method. – jeffery_the_wind Apr 10 '12 at 13:28
  • Thanks jeffery. Its not working. What do you mean when you say row id? How do I get the row id? – JC75 Apr 10 '12 at 14:27
  • Hi Jeffery. Ignore my previous comment. I think I might have got it to work! Looks OK! Thanks for all your help!! Much appreciated! Sorry if it took me a while! Im new to this! – JC75 Apr 10 '12 at 14:48