Editor 'preCreate ' event - php script variable not accesible in on 'preCreate ' function.

Editor 'preCreate ' event - php script variable not accesible in on 'preCreate ' function.

tomekkietomekkie Posts: 30Questions: 6Answers: 1

What wrong is with the code below:

$ev = -1;
if (isset($_SERVER['QUERY_STRING'])) {$ev = (int)$_SERVER['QUERY_STRING'];}
$editor = Editor::inst( $db, 'stands', 'id' )
    ->fields(
        Field::inst( 'company_name' )
            ->validator( 'Validate::notEmpty' ),
        Field::inst( 'stand_number' ),
        Field::inst( 'event_id' ) ->set( Field::SET_CREATE )
);
$editor ->on( 'preCreate', function ( $editor, $values ) {
       $editor
         ->field( 'event_id' )
         ->setValue( $ev );
} );
if($ev != -1) $editor   ->where( 'event_id', $ev);
$editor ->process( $_POST )
    ->json();

and - for some reasons - the $ev variable is accesible only for "where", but not in 'preCreate' function.
As a result it throws system error and Unknown variable notice for the $ev variable occurence in the on 'preCreate' function. Help, please.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,522Questions: 1Answers: 10,473 Site admin
    Answer ✓

    Are you getting an error from that code, or in what way is it not doing want you expect?

    for some reasons - the $ev variable is accesible only for "where", but not in 'preCreate' function.

    That is how PHP closures work for some bonkers reason. You need to add use( $ev ) to the closure definition to be able to access the variable in the closure - see the PHP documentation.

    Allan

  • tomekkietomekkie Posts: 30Questions: 6Answers: 1

    Thanks. That really helped.

    $editor ->on( 'preCreate', function ( $editor, $values )  use( $ev ){ 
    
This discussion has been closed.