Chaining formatters?

Chaining formatters?

Loren MaxwellLoren Maxwell Posts: 411Questions: 101Answers: 10

I want to 1) trim a field and 2) convert an empty string into a null.

So I've written the following code:

        Field::inst( 'field_name' )
            ->setFormatter( function ( $val, $data, $opts ) { return trim( $val ); } )
            ->setFormatter( 'Format::ifEmpty', null )
            ->validator( 'Validate::notEmpty' ),

This will trim or it will convert an empty string to null, but will not do both in conjunction.

For example, if I submit " " it will trim it down to an empty string and then insert the empty string into the database without converting it to null or even flagging it with the validator.

However, if I go back and edit the same record, it will now flag the empty field properly and not allow me to update it.

Is there a way to chain these functions?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,892Questions: 1Answers: 10,530 Site admin
    Answer ✓

    Hi,

    I'm afraid that there is currently no option to chain the formatter methods at the moment. The validation methods can be chained, but not the formatters.

    What you would need to do is extend your custom function:

    $val = trim( $val );
    
    if ( $val === '' ) {
      return null;
    }
    return $val;
    

    Allan

  • Loren MaxwellLoren Maxwell Posts: 411Questions: 101Answers: 10

    Thanks, Allan.

This discussion has been closed.