How to pass a function as a parameter in admin class

181 views Asked by At

Good morning, I have a little problem using sonata admin bundle, let's suppose that I have a function which returns a String, I want to pass the result of this function into as a parameter in the datagrid : something like :

protected $datagridValues = array (
'email' => array ('type1' => 2, 'value' => function()), // type 2 : >
'_page' => 1, // Display the first page (default = 1)
'_sort_by' => 'id' 
);

Any one knows a way to do this ? Thank you

3

There are 3 answers

4
Michael Sivolobov On BEST ANSWER

You can override getFilterParameters() method to change your $datagridValues:

public function getFilterParameters()
{
    $this->datagridValues = array_merge(array(
            'email' => array ('type1' => 2, 'value' => function()),
        ), $this->datagridValues);

    return parent::getFilterParameters();
}
6
Rémi Becheras On

The problem is the function() in

'email' => array ('type1' => 2, 'value' => function())

Pass a correct var and it will work.

'email' => array ('type1' => 2, 'value' => 'myValue')

EDIT

To pass a function in arguments (named a callback function), you have to pass the callback name in argument, and use the call_user_func to run it then:

function mycallback(){
    // do things
}

protected $datagridValues = array (
    'email' => array ('type1' => 2, 'value' => 'mycallback')
    '_page' => 1,
    '_sort_by' => 'id' 
);

Then you can do in your script :

call_user_func($datagridValues['email']['value']);
3
Aniket Singh On

within array you cant call a function.. you can do this way.

$var = function_name();

protected $datagridValues = array (
'email' => array ('type1' => 2, 'value' => $var), // type 2 : >
'_page' => 1, // Display the first page (default = 1)
'_sort_by' => 'id' 
);