Mark empty or wrong input field when error is returned

Mark empty or wrong input field when error is returned

klinglerklingler Posts: 90Questions: 42Answers: 2

Good afternoon (o;

Is there a way to automatically mark the inputs fields in the editor which are either wrong or missing
from a returned ajax call?

So far I've only found a way to display an error message at the bottom of the form when my ajax returns it.

thanks in advance
richard

Answers

  • rf1234rf1234 Posts: 2,990Questions: 87Answers: 421
    edited February 2022

    If you use the field validators server side this happens automatically. You can also do field validation client side which is similar.

    Here are two code examples:

    Server side field validation:

    Field::inst( 'cashflow.element' )
            ->validator( function ( $val, $data, $opts ) use ($msg) {
                if ( $data['cashFlowElement'] <= '' ) {
                    return $msg[0];
                }
                return true;
            } )
    

    This will show an error message in the Editor form underneath the field and will highlight the field to be in error.

    Client side field validation:

    editor
    .dependent('someField', function (val, data, callback) {
        // since the field error is NOT induced server side
        // and "false" is not returned from the event handler, 
        // it will NOT prevent submission to the server.
        var thisField = this.field('yourField');
        if ( errorCondition ) { 
            thisField.error( "not ok" );
        } else {
            thisField.error("");
        }
    });
    

    This will do the same thing.

    You are probably using a global validator server side which does not highlight the fields in error but only displays an error message at the bottom of the form. Like this for example:

    if ($lang === 'de') {     
            $msg[0] = 'Feld darf nicht leer sein.';
            $msg[1] = 'Bitte wählen Sie mindestens eine Behörde aus.';
    
        } else {
            $msg[0] = 'Field may not be empty.';
            $msg[1] = 'Please select at least one public authority.';
        }
    ......
    ->validator( function ( $editor, $editorAction, $data ) use ( $msg ) {
        if ( $editorAction === Editor::ACTION_CREATE || 
             $editorAction === Editor::ACTION_EDIT       ) {
            foreach ( $data['data'] as $pkey => $values ) {
                if ( isset($values['gov-many-count']) ) {
                    if ( $values['gov-many-count'] <= 0 ) {
                        return $msg[1];
                    }
                }
            }
            return null;
        }
    } )
    
Sign In or Register to comment.