Allow id 0 in addition to dbValues

Allow id 0 in addition to dbValues

marwimarwi Posts: 33Questions: 9Answers: 0

Hi,

In Editor, I have a simple join, showing a select dropdown field with some labels and storing its id number in db. The input is validated using ->validator('Validator::dbValues')

I would like to make this select field optional (not requred), so user should be able to select nothing (=placeholder). I can setup the placeholder options (incl. placeholderDisabled: false, placeholderValue: 0). But how can I allow the value 0 to be allowed for the validator in the PHP file?

Best regards,
marwi

This question has an accepted answers - jump to answer

Answers

  • rf1234rf1234 Posts: 2,817Questions: 85Answers: 406
    edited December 2017

    Pretty difficult to give you advice without seeing any code. But you could try those events below and make sure there is no create or update when the id field is < 1. Of course you could set all editor fields to false in that case which will effect that there is no insert or update at all.

    ->on('preCreate', function ( $editor, $values ) {
            if ($values['table']['id'] < '1') {
                $editor->field('table.id')->set( false );
                $editor->field('table.anotherField')->set( false );
            }
        })
        ->on('preEdit', function ( $editor, $id, $values ) {     
            if ($values['table']['id'] < '1') {
                $editor->field('table.id')->set( false );
                $editor->field('table.anotherField')->set( false );
            }
        })
    

    In addition you would need to change the ->validator that it allows a 0 without producing an error message or have no validator at all for that field.

    ->validator( function ( $val, $data, $opts ) {
                    if ($val < 0) {
                       return 'wrong id';
                    }
                   return true;
                } )
    
  • allanallan Posts: 62,241Questions: 1Answers: 10,211 Site admin
    Answer ✓

    The dbValues validator actually allows you to pass an array of static values that can be used for exactly this sort of thing:

    Editor 1.7+:

    ->validator(Validator::dbValues(null, null, null, null, [0]));
    

    Editor 1.6-:

    ->validator('Validator::dbValues', [
      "valid" => [ 0 ]
    ] )
    

    Allan

This discussion has been closed.