Pergunta

Does anyone know how to add a column index to a server-side processed DataTable? Basically like http://www.datatables.net/examples/api/counter_columns.html, but this example builds the index by client, which is not supported by using the common server-side version.

The author Allan gave three hints, but actually I don't get it:

  • Modify the data at the server (the ideal solution)
  • Modify the data as it comes back from the server
  • Edit the draw callback function to take into account the page start position.

I stumble and stumble - and I don't know how to start and how to do it. Maybe YOU could help me out? That would be awesome!

Foi útil?

Solução

I am referring to the simple.html example here.

In server_processing.php replace the last lines with:

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * If you just want to use the basic configuration for DataTables with PHP
     * server-side, there is no need to edit below this line.
     */
    require( 'ssp.class.php' );
    $result=SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns );
    $start=$_REQUEST['start'];
    $idx=0;
    foreach($result['data'] as &$res){
        $res[0]=(string)$start;
        $start++;
        $idx++;
    }
    echo json_encode($result);

This will generate an row-id to the array that is returned. Also you need to shift the number in the $colums array by 1 since the id is inserted at position 0.

$columns = array(
    array( 'db' => 'first_name', 'dt' => 1 ),
    array( 'db' => 'last_name',  'dt' => 2 ),
    array( 'db' => 'position',   'dt' => 3 ),
    etc ...

Finally you need to add an additional id column to your html:

    <thead>
        <tr>
            <th>ID</th>
            <th>First name</th>
            <th>Last name</th>
            etc ...

That is what Allan meant with "Modify the data as it comes back from the server". And this has some drawbacks. When using server sided processing sorting, filtering and searching happens in the genrated sql query that fetches the data from your db. Since you don't seem to have an incremental id field in you db: No sorting the ID for you, come back one year!

This brings us to Allans suggestion Nr.1 "Modify the data at the server (the ideal solution)" which basically means: Give your db an incrementing id and use it as a simple field. This can be done with a simple update query. Of course if you don't want to sort after row id this answer will do.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top