p27
p27

Reputation: 2222

form validation in cakephp

I have one model login - it has 5 fields. At time of registration I am validating all the fields, but when I edit the record I want to validate only some fields before saving the data.

I am using this code:

if ($this->Login->validates(array('fieldList' => array('password','name')))) {
    if ($this->Login->save($this->data)) {
        echo 'helllo';exit;
        //$this->Session->setFlash('Your post has been updated.');
        //$this->redirect(array('action' => 'profile'));
    }else {

    }
} else {

}

But it's not working.

Upvotes: 1

Views: 701

Answers (3)

deceze
deceze

Reputation: 521995

You should properly do this by setting on to create in the validation rule. Repeating this logic in the controller every time is bad.

The specific problem in your case is that save is validating again, and validating all fields. In fact, the first call the validates is entirely superfluous. You will have to use the third $fieldlist parameter of the save function if you only want to save/validate certain fields:

$this->Login->save($this->data, true, array('password','name'))

Upvotes: 2

Ross
Ross

Reputation: 17967

If I understand you correctly, you only want the validation to apply on create, and not update. Cake has this functionality built in.

In your model, where each fields validation rules are, you will have something similar to:

var $validate = array(
    'fieldName1' => array(
        'rule' => 'ruleName', // or: array('ruleName', 'param1', 'param2' ...)
        'required' => true,
        'allowEmpty' => false,
        'on' => 'create', // or: 'update'       ** here **
        'last' => false,
        'message' => 'Your Error Message'
    )
);

Might resolve your issue.

Upvotes: 0

Deele
Deele

Reputation: 3684

You better seperate everything, at first you validate, if everything goes ok, only then, save any data.

Validation should return some data, where it has failed, additionally, there are different data types, different things to check, for each field - there should be some classification for your site, what are limits, for specific field.

Upvotes: 0

Related Questions