Search code examples
phpdatatablesserver-side

Using Variable to DataTables Server-Side Column value Formatter


I want to pass PHP function on each cell of DataTables via Server-side Formatter, but PHP Function is dynamic. Here is example code:

$func_apply = $_GET['function_name']; // trim | strip_tags | md5 | ucwords

$columns[] = array(
'db'        => $field,
'dt'        => '3',
'formatter' => function( $d, $row ) {
                return $func_apply($d);
            }
);

But this way I am getting PHP error Undefined variable: $func_apply And if I put global $func_apply; within anonymous function then it gives Fatal error: Function name must be a string in ...


Solution

  • I have solved the issue by using the PHP Closures:

    $func_apply = $_GET['function_name']; // trim | strip_tags | md5 | ucwords
    
    $columns[] = array(
    'db'        => $field,
    'dt'        => '3',
    'formatter' => function( $d, $row ) use ($func_apply) {
                return $func_apply($d);
            }
    );