Call an external function from within getFormatter

Call an external function from within getFormatter

INTONEINTONE Posts: 153Questions: 58Answers: 6
edited May 2017 in Editor

I am trying to call a external function from within getFormatter like this:

Field::inst( 'Users.createdBy' )
            ->getFormatter( function ( $val, $data, $opts ) {
             
               return showName($val);
              
            } )

my problem is that I cannot get a database instance in the function without doing:

return showName($val,$db);

but that cannot work because ->getFormatter is using an anonymous function and anonymous functions cannot see a value unless it is passed direction in as a parameter. Is there a way I can do this. I just want to get the name of the user using the $val variable. If there is a better way to do it, please let me know. For clarity, I am using the pdo sql server driver as my database abstraction layer.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,726Questions: 1Answers: 10,109 Site admin
    Answer ✓

    You have to tell PHP that you want to use the $db variable in your function by using the use statement:

    Field::inst( 'Users.createdBy' )
                ->getFormatter( function ( $val, $data, $opts ) use ( $db ) {
                  
                   return showName($val, $db);
                   
                } )
    

    The PHP documentation has full details about this.

    Allan

  • INTONEINTONE Posts: 153Questions: 58Answers: 6

    Thank you,

    That is awesome.

This discussion has been closed.