Can we have an action (create, edit ...) in field validation ?

Can we have an action (create, edit ...) in field validation ?

Benoit87Benoit87 Posts: 15Questions: 5Answers: 2
edited January 24 in Editor

Hello,

I would like to know if it's possible to have a validator only on specific action at field level :
Here, there is never 'test' in my log, what is wrong ?
But with Global validator, it works fine.

        // Fields Validator
        ->fields(
            Field::inst( 'USERID' )
                ->validator(function ($editor, $action, $data){
                    if ($action === Editor::ACTION_EDIT){
                        error_log('test');
                    }
                    return true;
                })

This question has an accepted answers - jump to answer

Answers

  • Benoit87Benoit87 Posts: 15Questions: 5Answers: 2

    I found i think, it could be correct ?

            // Fields Validator
            ->fields(
                Field::inst( 'USERID' )
                    ->validator(function ($editor, $action, $data, $host){
                        error_log(print_r($host['action'], true));
                    })
    
  • allanallan Posts: 63,872Questions: 1Answers: 10,527 Site admin

    Use the preCreate and preEdit events to add a validator to a field based on what action is being performed.

    Allan

  • Benoit87Benoit87 Posts: 15Questions: 5Answers: 2
    edited January 24

    thank you can you give me a sample please

  • allanallan Posts: 63,872Questions: 1Answers: 10,527 Site admin
    ->on( 'preCreate', function ( $editor, &$values ) {
      $editor->field('USERID' )->validator(function ($editor, $action, $data, $host){
        error_log(print_r($host['action'], true));
      });
    })
    

    Allan

  • Benoit87Benoit87 Posts: 15Questions: 5Answers: 2
    Answer ✓

    Thanks you very much, finally i did this :
    It seem to works fine in field now.
    What's impact to put it to preCreate ? It's just a best practice ?

        $editor = Editor::inst( $db, 'TABLE1', 'IDENT' )
            // Fields Validator
            ->fields(
                Field::inst( 'USERID' )
                    ->validator( function ( $val, $data, $field, $host ) {
                        if ($host['action'] === 'create') {
    
                        }
                        return true;
                    } )
    
  • allanallan Posts: 63,872Questions: 1Answers: 10,527 Site admin

    That will work as well. preCreate is how I've always done it, I think the resulting code is a little cleaner, but its up to you :)

    Allan

  • Benoit87Benoit87 Posts: 15Questions: 5Answers: 2

    ok thanks you for your fast support you can close topic.

Sign In or Register to comment.