0
votes

I want to use model validation. lets i explain here clearly. in my view there is a file called "register.ctp". Also i have two table one is users and another is profiles, according to cakephp concept also i have two model that user model(User.php) and profile model(Profile.php). My register.ctp contains the follow fields

name, email, address and phone all are mandatory - when i submit, name and email will store in users table and address and phone will store in profiles table

when i use model validation i have tried by using the below code that is working only for name and email but not working on for other fields.

here is my code for for model validation in user model(User.php)

public $validate = array(
     'email' => array(
        'blank' => array(
            'rule' => 'notEmpty',
            'message' => 'Please enter Email.'
        )
    ),

    'name' => array(
        'rule'    => 'notEmpty',
        'message' => 'Please enter Name'
    ),
    'address' => array(
        'rule'    => 'notEmpty',
        'message' => 'Please enter Address'
    ),
    'phone' => array(
        'rule'    => 'notEmpty',
        'message' => 'Please enter Phone'
    ),

);

Thanks

2

2 Answers

0
votes

You need to set the validation per model.

So in User.php:

public $validate = array(
     'email' => array(
        'blank' => array(
            'rule' => 'notEmpty',
            'message' => 'Please enter Email.'
        )
    ),
    'name' => array(
        'rule'    => 'notEmpty',
        'message' => 'Please enter Name'
    )
);

And in Profile.php:

public $validate = array(
    'address' => array(
        'rule'    => 'notEmpty',
        'message' => 'Please enter Address'
    ),
    'phone' => array(
        'rule'    => 'notEmpty',
        'message' => 'Please enter Phone'
    )
);

And you need to validate both models in the Controller:

$this->User->set($this->data());
$valid = $this->User->validates();

$this->Profile->set($this->data);
$valid = $valid && $this->Profile->validates();
0
votes

See these two model methods.

See Model::saveAll() as well. It can be used to validate the whole set of records and associated records. This will only validate but not save the reocrds as well:

$this->saveAll($data, array('validate' => 'only'));

I recommend you to read the whole documentation about saveAll() to understand how it works and what it will return when you only validate the data.

There is no need to manually validate each model one by one like noslone suggested. The single line above will do it as well.