Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Best way to validate form input and save it to db

Hello,

I am new to Phalcon and wonder what the best way would be to save validated data to a database. I read the Forms page in the docs, but when I implement a model wich validates input data:

class Test extends Form {

    public function initialize(){

        $name = new Text('name', array(
            'placeholder' => 'Name'
        ));

        $name->addValidators(array(
            new PresenceOf(array(
                'message' => 'The name is required'
            ))
        ));

        $this->add($name);
    }

}

What is the best way to write the controller and the view if I have model like this?

Sparkling Soda



15.9k
Accepted
answer
edited Aug '14

In Phalcon there are two kind of validators: * from namespace Phalcon\Validation\Validator... - there are e.g. for forms * from namespace Phalcon\Mvc\Model\Validator... - these are for models

I always implement validators inside models to be sure that data are valid.

One of the reason is that I create objects from several source of data - not only forms.

Another problem is when the data from one form feeds more than one model. E.g. order form can feed PaymentsMethod model and DeliveryAddress model. In such situation I declare validators both in model and in the form. Form validators are used to produce user-friendly error messages and model validators.

Maybe sb have better solution.