We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Use Form Validator InclusionIn with Model?

Is it possible to validate a Select input with Phalcon\Validation\Validator\InclusionIn()? Or is this done automatically when populating a select field from a model?



13.4k
Accepted
answer

I've managed to find a solution to this myself, although not ideal it does work as I expect it to.

Using the Underscore library ported to PHP (https://github.com/JonathanAquino/Underscore.php/) I was able to use results from a Model to validate against a Select element.

I have a database table that stores all Cities/Towns in the UK so using this I setup my Select field in the Form Builder as below:

$city = new Select('city', Cities::find(), array(
        'class' => 'form-control',
        'using' => array('id', 'name')
));

I then add the InclusionIn() validator to validate user input against the Model:

$city->addValidator(new InclusionIn(array(
        'message'   => 'Invalid City/Town entered',
        'domain'    => \__::flatten(Cities::find(array(
                    'columns'   => 'id'
                ))->toArray())
        )));

Could something like this be built into Phalcon? Then we can validate the user input before it even reaches the Model.