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

Validation of Models and Forms

Hi all, How to share validation rules between Forms and Models? Say, I have User model and corresponding User form. I want to use the same validation rules in my form as in my model. For example, I may allow user to change its data using html form as well as API call. How can I achieve that? Thanks.



98.9k

You can implement the validations just in the model, in both cases they will be executed binding the data got from the request or directly binding the data to the model.

<?php

use Phalcon\Mvc\Model\Validator\InclusionIn,
    Phalcon\Mvc\Model\Validator\Uniqueness;

class Robots extends \Phalcon\Mvc\Model
{

    public $id;

    public $name;

    public $type;

    public function validation()
    {

        $this->validate(new InclusionIn(
            array(
                "field"  => "type",
                "domain" => array("Mechanical", "Virtual")
            )
        ));

        $this->validate(new Uniqueness(
            array(
                "field"   => "name",
                "message" => "The robot name must be unique"
            )
        ));

        return $this->validationHasFailed() != true;
    }

}

Directly assign values to model:

$robot = new Robots();
$robot->name = 'Voltron';
$robot->type = 'Mechanical';
$robot->save(); // validation is performed here
var_dump($robot->getMessages()); // get messages

Binding data from the form:

$robot = new Robots();
$form->bind($this->request->getPost(), $robot);

$robot->save(); // validation is performed here
var_dump($robot->getMessages()); // get messages


2.6k
edited Mar '14

Hi everyone!

I have very similar problem. I have validation implemented inside a model. Let's say that a user have submitted a form with some fields incorrect. So I want to show him the form again with his values and error messages.

The problem is that I want to display the field's error/validation messages directly below the field and add some error-class as well to highlight the incorrect fields . I don't know how to achive it. How to inform a form about field messages?

Can you help me? Thank you!