Datatables - Merge columns together

2019-05-03 11:14发布

问题:

I have these database columns, but I want them to be in one column. How would I do that? With mRender, I think?

                    /* Address */  
        {"sTitle": "Address",
                    "bVisible": true,
                    "bSearchable": true},
        /* City */   
        {"sTitle": "City",
                    "bVisible": true,
                    "bSearchable": true},
        /* State */    
        {"sTitle": "State",
                    "bVisible": true,
                    "bSearchable": true},
        /* Zip */    
        {"sTitle": "Zip",
                    "bVisible": true,
                    "bSearchable": true},

回答1:

provided that the columns returned by the datatables get are address, city , state, zip 1-4

if your data returned is a regular array

   { "mData": 0 , //or address field
     "mRender" : function ( data, type, full ) { 
     //data = mData
     //full is the full array address= [0] city = [1] state=[2] zip=[3] 
        return data+', '+full[1]+', '+full[2]+', '+full[3];}
      },

if your data is an associate array

   { "mData": 'address' , 
     "mRender" : function ( data, type, full ) { 
        return data+', '+full['city']+', '+full['state']+', '+full['zip'];}
      },

or you can call mRender independent of mData (though it seems not needed for this situation)

   { "mData": null , 
     "mRender" : function ( data, type, full ) { 
        return full['address']+', '+full['city']+', '+full['state']+', '+full['zip'];}
      },

EDIT: for datatables 1.10, just change the names a bit, drop the "m"

   { "data": null , 
     "render" : function ( data, type, full ) { 
        return full['address']+', '+full['city']+', '+full['state']+', '+full['zip'];}
      },

*note i'm not taking into account whether you should store this data in one column, just showing how its done



回答2:

database table fields : id,first_name,last_name,email

datatable : full_name,email (without id) ?

"columns": [
            {
             "mData": null ,
             "mRender" : function ( data, type, full ) {
                return full['first_name']+' '+full['last_name'];
              }
             },


回答3:

$(document).ready(function() {
    $('#example').DataTable( {
        "columnDefs": [
            {
                // The `data` parameter refers to the data for the cell (defined by the
                // `data` option, which defaults to the column being worked with, in
                // this case `data: 0`.
                "render": function ( data, type, row ) {
                    return data +' ('+ row[3]+')';
                },
                "targets": 0
            },
            { "visible": false,  "targets": [ 3 ] }
        ]
    } );
} );