Search code examples
phpjquerydatatabledatatables

Combining two columns in Datatables Server-side


I want to combine two columns (covered_from and covered_to) data in my datatables. Here is my code:

$columns = array(
    array( 'db' => 'employee_number', 'dt' => 0 ),
    array( 'db' => 'employee_name', 'dt' => 1 ),
    array( 'db' => 'leave_type', 'dt' => 2 ),
    array( 
        'db' => 'covered_from', 
        'dt' => 3, 
        'formatter' => function( $d, $row) {
            $from = $row['covered_from'];            
            $from = date('F d, Y', strtotime($from));
            return $from;
        }
    ),
    array( 
        'db' => 'covered_to', 
        'dt' => 4, 
        'formatter' => function( $d, $row) {
            $to = $row['covered_to'];     
            if(empty($to) || $to == "Halfday") {
                $to = "";
            }
            return $to;
        }
    ),
    array( 'db' => 'reason', 'dt' => 5 ),
    array( 'db' => 'number_of_days', 'dt' => 6 ),
    array( 'db' => 'cutoff', 'dt' => 7 ),
    array( 'db' => 'status', 'dt' => 8 ),
);

The result should be like this,

array( 
        'db' => 'covered_from', 
        'dt' => 3, 
        'formatter' => function( $d, $row) {
            $from = $row['covered_from'];
            $to= $row['covered_to'];
            
            $from = date('F d, Y', strtotime($from));
            $to = date('F d, Y', strtotime($to));

            return $from . " - " .$to;
        }
    ),

How can I achieve that? Thanks for the help!


Solution

  • I already solved my problem by adding these codes I've found in the internet.

    "columnDefs": [
                {
                    "render": function ( data, type, row ) {
                        return data + " - " +row[4];
                    },
                    "targets": 3
                },
                { "visible": false,  "targets": [ 4 ] }
            ],
    

    Thanks!