Select2 - setting current cell value, and updating cell after change?

Select2 - setting current cell value, and updating cell after change?

cdelstadcdelstad Posts: 11Questions: 2Answers: 0
edited June 2016 in Free community support

Is their a built in way to have the select2 dropdown have the cells current value selected when it opens?
Also, when I set a value in the select2 dropdown, then change focus, the value in the datatable does not update the cell with the new value.
I have to assume both of these should be built in functionality so I am not sure what I am misisng.
Here's some example code:

      var editor = new $.fn.dataTable.Editor( {
          table: "#manifestSummaryDT",
          idSrc:  'manifestId',
          fields: [ {
                  label: "Manifest Creation:",
                  name: "statusNm",
                  type:  "select2",
                  ipOpts: [{"label":"Line","value":"1"},{"label":"Bar","value":"2"},{"label":"Pie","value":"3"}]
              }
          ]
      } );

Assuming the current value of the datatable cell is "Bar", how do I have that be the selected value when the dropdown opens?
Then, lets say I select "Pie" and leave the cell. How does that value get set back to the cell - or the cell get updated to the new value?

Any help would be greatly appreciated. I am new to datatables, the editor, and select2. So some things are not yet intuitive to me.
Thanks in advance,
-Chad

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

This question has an accepted answers - jump to answer

Answers

  • cdelstadcdelstad Posts: 11Questions: 2Answers: 0

    The regular select dropdown also performs the same way. Is there something I need to set to integrate the dropdown and datatables?
    I am trying to do a proof of concept quickly to present so we can get approval to buy the Editor. Any help would be greatly appreciated.
    Thanks in advance,
    -Chad

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    It sounds like you are running into a label / value issue. You have statusNm as the data property for the field in question. Is that "1", "2", etc? If not, and it is in fact "Line", "Bar", etc, that is the issue.

    You need the value of the property to match the value options.

    If you ave a look at the join example you will be able to see how I handle this - the data structure from the server contains both the label (for display in the DataTable) and the value (for use with Editor).

    Allan

  • cdelstadcdelstad Posts: 11Questions: 2Answers: 0
    edited June 2016

    Here is the datatable column def for this column:

                 { 'data' : 'statusNm', 'title' : 'Manifest Creation', 'name' : 'statusNm', 'customType' : 'string-like', className: 'editable'},
    

    And the data displaying in the datatable is like the 'name' column in the dataList object below.

    I have removed Select2 from my code. I'm just trying to get a select to work at this point. ONce I can get that working, I plan to re-implement Select2.

    Here is my current editor code:

      var dataList =  [{"active":true,"code":"BLANK","desc":null,"id":46,"name":" "},{"active":true,"code":"APPRVD","desc":null,"id":53,"name":"Approved"},{"active":true,"code":"CMPLTD","desc":null,"id":52,"name":"Completed"},{"active":true,"code":"INPRGRSS","desc":null,"id":51,"name":"In Progress"},{"active":true,"code":"NOTSTRTD","desc":null,"id":50,"name":"Not Started"},{"active":true,"code":"PEND","desc":null,"id":49,"name":"Pending"},{"active":true,"code":"RJCTD","desc":null,"id":48,"name":"Rejected"},{"active":true,"code":"SBMTTD","desc":null,"id":47,"name":"Submitted"}];
    
      var editor = new $.fn.dataTable.Editor( {
          table: "#manifestSummaryDT",
          idSrc:  'manifestId',
          fields: [ {
                  label: "Manifest Creation:",
                  name: "statusNm",
                  type:  "select",
                  ipOpts: dataList.map(function(item) {
                      return {
                          value : item.id,
                          label : item.name
                      };
                  })
              }
          ]
      } );
    
      // Activate an inline edit on click of a table cell
      $('#manifestSummaryDT').on( 'click', 'tbody td.editable', function (e) {
          editor.inline( this );
      } );
    

    ...

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Thanks - that confirms what I suggested above. You are trying to use statusNm as both the label (to show in the DataTable) and the value (for Editor). That won't work.

    You need to have both the label and the value in the JSON data source for the table.

    If that isn't an option, you need to have just the value (not the label!) and use a client-side renderer to show the label in the DataTable.

    Allan

  • cdelstadcdelstad Posts: 11Questions: 2Answers: 0
    edited June 2016

    OK, adding the label to the dataset now has the select correctly selecting the correct select option upon opening the dropdown. Thank you.

    The data being returned to the datatable has reviewResultCode = INVALID, and reviewResultName = Invalid. So I am not loading the select options list to each record, just adding to the editor select config.

    I also added a render to display the label instead of the code/value:

                                 {'data': 'reviewResultCode', 'title':'Review Result*', 'name': 'reviewResultCode', 'orderable' : false, 'searchable' : false, className: 'editable', render: function (data, type, row) {
                                     if (type === "display") {
                                         return row.reviewResultName;
                                     }
                                     return data;
                                 }},
    

    Now on to the second issue, which is setting the changes value back to the datatable cell.

    I am massaging the data as follows:

             var dataList = [{"active":true,"code":"BLANK","desc":null,"id":46,"name":" "},{"active":true,"code":"INVALID","desc":null,"id":46,"name":"Invalid"},{"active":true,"code":"APPRVD","desc":null,"id":53,"name":"Approved"},{"active":true,"code":"CMPLTD","desc":null,"id":52,"name":"Completed"},{"active":true,"code":"INPRGRSS","desc":null,"id":51,"name":"In Progress"},{"active":true,"code":"NOTSTRTD","desc":null,"id":50,"name":"Not Started"},{"active":true,"code":"PEND","desc":null,"id":49,"name":"Pending"},{"active":true,"code":"RJCTD","desc":null,"id":48,"name":"Rejected"},{"active":true,"code":"SBMTTD","desc":null,"id":47,"name":"Submitted"}];
    
                dataList = dataList.map(function(item) {
                    return {
                        value : item.code,
                        label : item.name
                    };
                });
    

    How would you recommend I approach getting updates back to the datatable cell?
    Thanks again,
    -Chad

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    How would you recommend I approach getting updates back to the datatable cell?

    It should be in the JSON data returned from the server in response to the Ajax request that Editor makes on create or edit.

    The join example demonstrates this as well.

    Allan

  • cdelstadcdelstad Posts: 11Questions: 2Answers: 0

    So I can't really use select2 like this if I want to upate in the datatable without making an extra call to get the dropdown data? So since the data is already in the json response, I would just use ipOpts to load the data to Select2?

                var editor = new $.fn.dataTable.Editor( {
                    table: "#dtDataVarianceField",
                    idSrc:  'reviewResultCode',
                    fields: [ {
                            label: "Review Result:",
                            name: "reviewResultCode",
                            type:  "select2",
                            opts: {
                                ajax: {
                                    url: '/rest/path',
                                    delay: 250,
                                    processResults: function (resp) {
                                      var data = resp.data;
                                        return {
                                            results :
                                                data.map(function(item) {
                                                    return {
                                                        id : item.id,
                                                        text : item.name
                                                    };
                                                })
                                        };
                                    }
                                  },
                                allowClear: true
                            }
                        }
                    ]
                } );
    

    Or, can I inject the select options data in to my retrieved json, something like this?

               var dataList = [{"active":true,"code":"BLANK","desc":null,"id":46,"name":" "},{"active":true,"code":"INVALID","desc":null,"id":46,"name":"Invalid"},{"active":true,"code":"APPRVD","desc":null,"id":53,"name":"Approved"},{"active":true,"code":"CMPLTD","desc":null,"id":52,"name":"Completed"},{"active":true,"code":"INPRGRSS","desc":null,"id":51,"name":"In Progress"},{"active":true,"code":"NOTSTRTD","desc":null,"id":50,"name":"Not Started"},{"active":true,"code":"PEND","desc":null,"id":49,"name":"Pending"},{"active":true,"code":"RJCTD","desc":null,"id":48,"name":"Rejected"},{"active":true,"code":"SBMTTD","desc":null,"id":47,"name":"Submitted"}];
    
                            'ajax' : {
                                'url' : "/rest/path/",
                                'dataSrc': function (json) {
                                    json.dataList = dataList; <-- dataList has been retrieved separately
                                    return json.data; <-- The data node has my data from the server
                                }
                            },
    

    Thanks again,
    -Chad

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    If you have the options for Select2 in the JSON data feed, you can use the initComplete method, which has the JSON passed into it, and then use the update() field method of the Select2 field type.

    Allan

  • cdelstadcdelstad Posts: 11Questions: 2Answers: 0
    edited June 2016

    I am feeling like a complete idiot here. I cannot get this to work. :( i get TN #2, #4, or #11, or no error/no data.

    Here is the JSON coming form the server:

    {"code":200,
    "data":[{"acctky":1234567890,"businessName":"Fully Indexed Payment At Orig","changeDateTime":"2016-05-19T06:11:21.000Z","columnName":"FULLY_IDX_PI_AMT","currentValue":"2595","dataChangeNtfyId":24,"exportDate":null,"exportUser":null,"includeInExport":null,"newValue":"2595","originalValue":"2695","qmReview":true,"reviewResultCode":"INVALID","reviewResultName":"Invalid","sorLocation":"CORE-Product Pricing and Rates","systemCode":null,"taskId":09876543321,"user":null},{"acctkey":1234567890,"businessName":"Monthly Debt Amount","changeDateTime":"2016-05-19T06:11:21.000Z","columnName":"TOT_LIAB_MO_PMT_AMT","currentValue":"5800","dataChangeNtfyId":5,"exportDate":null,"exportUser":null,"includeInExport":null,"newValue":"5800","originalValue":"5804","qmReview":true,"reviewResultCode":"BLANK","reviewResultName":" ","sorLocation":"CORE-Product Pricing and Rates","systemCode":null,"taskId":09876543321,"user":null},{"acctkey":1234567890,"businessName":"Original Loan Amount (pre-modification)","changeDateTime":"2016-05-19T06:11:21.000Z","columnName":"NT_AMT","currentValue":"619300","dataChangeNtfyId":22,"exportDate":null,"exportUser":null,"includeInExport":null,"newValue":"619300","originalValue":"619200","qmReview":false,"reviewResultCode":"BLANK","reviewResultName":" ","sorLocation":"CORE-Product Pricing and Rates","systemCode":null,"taskId":09876543321,"user":null},{"acctkey":1234567890,"businessName":"Original Maturity (pre-modification)","changeDateTime":"2016-05-19T06:11:21.000Z","columnName":"MAT_DT","currentValue":"2045-4-10","dataChangeNtfyId":23,"exportDate":null,"exportUser":null,"includeInExport":null,"newValue":"10-APR-45","originalValue":"01-APR-45","qmReview":false,"reviewResultCode":"BLANK","reviewResultName":" ","sorLocation":"CORE-Product Pricing and Rates","systemCode":null,"taskId":09876543321,"user":null},{"acctkey":1234567890,"businessName":"Original P And I (pre-modification)","changeDateTime":"2016-05-19T06:11:21.000Z","columnName":"INIT_PI_PMT_AMT","currentValue":"2684.8","dataChangeNtfyId":4,"exportDate":null,"exportUser":null,"includeInExport":null,"newValue":"2684.8","originalValue":"2694.8","qmReview":false,"reviewResultCode":"BLANK","reviewResultName":" ","sorLocation":"CORE-Product Pricing and Rates","systemCode":null,"taskId":09876543321,"user":null},{"acctkey":1234567890,"businessName":"Qualifying Income","changeDateTime":"2016-05-19T06:11:21.000Z","columnName":"TOT_MO_INCM_AMT","currentValue":"20600","dataChangeNtfyId":6,"exportDate":null,"exportUser":null,"includeInExport":null,"newValue":"20600","originalValue":"20758","qmReview":true,"reviewResultCode":"BLANK","reviewResultName":" ","sorLocation":"CORE-Product Pricing and Rates","systemCode":null,"taskId":09876543321,"user":null}],
    "dataList":[{"active":true,"code":"BLANK","desc":null,"id":0,"name":" "},{"active":true,"code":"INVALID","desc":"Invalid","id":6,"name":"Invalid"},{"active":true,"code":"VALID","desc":"Valid","id":5,"name":"Valid"}],"draw":null,"fieldMessages":null,"formMessages":null,"message":null,"messageDetails":null,"messages":null,"page":{"firstPage":true,"lastPage":true,"number":0,"numberOfElements":6,"size":6,"totalElements":6,"totalPages":1},"recordsFiltered":6,"recordsTotal":6,"redirectUrl":null,"status":"success"}
    

    Here is the datatable config:

     'ajax' : {
                                'url' : "rest/path",
    //                            'dataSrc': function (json) {
    //                                //dataList = json.dataList;
    //                                json.dataList = json.dataList.map(function(item) {
    //                                  return {
    //                                      value : item.code,
    //                                      label : item.name
    //                                  };
    //                              });
    //                                console.log(json);
    //                                return json;
    //                            }
                            },
                            'columns' : [
                                 {'data': 'data.businessName', 'title':'Field', 'name': 'data.businessName', 'orderable' : false, 'searchable' : false},
                                 {'data': 'data.sorLocation', 'title':'Location', 'name': 'data.sorLocation', 'orderable' : false, 'searchable' : false},
                                 {'data': 'data.originalValue', 'title':'Prior', 'name': 'data.originalValue', 'orderable' : false, 'searchable' : false},
                                 {'data': 'data.newValue', 'title':'New', 'name': 'data.newValue', 'orderable' : false, 'searchable' : false},
                                 {'data': 'data.currentValue', 'title':'Current', 'name': 'data.currentValue', 'orderable' : false, 'searchable' : false},
                                 {'data': 'data.changeDateTime', 'title' : 'Date', 'name' : 'data.changeDateTime', 'render' : function(data, type) {
                                     if (type === 'display' && data !== null) {
                                         var dateFormat = WF.util.Date.format(new Date(data), {format : '%m/%d/%Y %r'} );
                                         return dateFormat;
                                     } else {
                                         return '';
                                     }
                                 }},
                                 {'data': 'data.systemCode', 'title':'System', 'name': 'data.systemCode', 'orderable' : false, 'searchable' : false},                         
                                 {'data': 'dataList.code', 'title':'Review Result*', 'name': 'dataList.code', 'orderable' : false, editField: 'reviewResultCode', 'searchable' : false, className: 'editable'},
                                 {'data': 'data.qmReview', 'title':'QM Field', 'name': 'data.qmReview', 'orderable' : false, 'searchable' : false, 'render': function ( data, type, full, meta ) {
                                     var YNInd = 'No';
                                     if (data) {
                                         YNInd = 'Yes';
                                     } else {
                                         YNInd = 'No';
                                     }
                                     return YNInd;
                                 }
    }
                            ],
                            'order' : [[0, 'desc']]
    

    Here is the Editor code:

               var editor = new $.fn.dataTable.Editor( {
                    table: "#dtDataVarianceField",
                    //idSrc:  'reviewResultCode',
                    fields: [ {
                            label: "Review Result:",
                            name: "reviewResultCode",
                            type:  "select"
                            ipOpts: dataList
                        }
                    ]
                } );
                
                // Activate an inline edit on click of a table cell
                $('#dtDataVarianceField').on( 'click', 'tbody td.editable', function (e) {
                    editor.inline( this );
                } );
    

    Thanks again,
    -Chad

  • cdelstadcdelstad Posts: 11Questions: 2Answers: 0

    I apologize. I just realized I wasn't clear at all about what I cannot get to work.
    What I cannot get to work is when I change the option in the dropdown in either the select/select2 dropdown, it will not update the datatable cell. As soon as focus is changed and the select input is removed, the value shows as the original value.
    I've tried half a dozen examples and suggestions and cannot get any of them to work. For the join and return from server examples, I tried setting the data and name attributes in the datatable column to the second dataset with the options, and I get unknown dataList.code, even tried changing dataList to 'options', etc.I tried several different permutations.
    I am able to get the select2 to load options with the initComplete() and update(). Thank you.
    -Chad

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    As soon as focus is changed and the select input is removed, the value shows as the original value.

    There is no ajax option in your Editor configuration. Currently you must have that option so the data is submitted somewhere and it is saved to a database (or whatever data store you are using) and then the JSON for the row returned. See the client / server interchange documentation for full detains.

    Apologies I missed that point before.

    Editor 1.6 will not require that option, and allow data to be updated in table directly.

    Allan

  • cdelstadcdelstad Posts: 11Questions: 2Answers: 0
    edited June 2016

    We want to do multi-change submits managed by a separate submit button on the page. We send DTO's back and forth to our App Stack for processing via SpringMVC. They are a different team and want to stick to this model.
    Is there a short term solution we can use until 1.6 is ready? How long before 1.6 is released?
    Thanks again,
    -Chad

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    This will be a bit easier with 1.6, but it will still require a bit of custom code. You will be updating the local table, but in order to submit it, you would need to use data() or similar to get the table's data and submit it - Editor will not do that part for you.

    In the short term, if you do want to do that, you could use a method such as that shown in this example. It basically uses an override for ajax and updates the row. Code for insert and remove would need to be implemented.

    1.6 should be later this summer, but I don't have a confirmed date.

    Regards,
    Allan

  • cdelstadcdelstad Posts: 11Questions: 2Answers: 0

    OK. Thank you. Would this also be the reason the row.add() and row.remove() are not working - because I do not have the ajax section populated in the datatable config?
    Thanks again,
    -Chad

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    They are DataTables API methods rather than Editor. The Editor configuration shouldn't effect their operation. So if they aren't working its probably something else I'm afraid.

    Allan

This discussion has been closed.