CakePHP validation on => 'create', on => 'update'

I hope the cakephp experts can answer this Cake 2.1 question and model data validation.

Cake gives you an "on" key to use in the validate array. I understand what the docs say about this, but my question is what is the point of these two items.

Let's say I have a validation rule when a record is created. Verification ends and the record is created.

The user then goes over and edits that entry and changes it to no longer pass this particular check. But since I have my validation only triggered on creation, the validation passes and the record is updated with invalid data. It seems to me that this applies to any create / update rules. If the user wanted to bypass validation, just create a valid entry, then go ahead and edit it so that it is now invalid.

Can someone possibly help me understand when it might make sense to use when updating and building?

+3


source to share


3 answers


This is most useful when done with a rule required

. You must set certain fields as the minimum required for required

'on' => 'create'

. This causes the rule to fail if these fields do not exist in the dataset and the record cannot be created, but allows existing records to be updated without having to pass that field every time.

For example:



'email' => array(
    'required' => array(
        'on'         => 'create',
        'rule'       => 'notEmpty',
        'message'    => 'Enter your email address',
        'required'   => true,
        'last'       => true
    ),
    'notempty' => array(
        'rule'       => 'notEmpty',
        'message'    => 'Enter your email address',
        'allowEmpty' => false,
        'last'       => true
    ),
    'email' => array(
        'rule'       => 'email',
        'message'    => 'Not a valid email address',
        'last'       => true
    )
)

      

+11


source


I found it really useful in collaboration with profile pictures. You need it to be loaded on build (if needed), but I can stay blank on update => update will fail.



+1


source


'on' => null

will complete the task

EDIT:

Ok, let's say you have a profile model.

If you have a Date of birth field, you will probably use the rule that will apply to add and release.

You can also add a delete_picture checkbox to your form, which the user must select to delete their profile picture. When adding you do not have a profile, so this field is only meaningful at publish time, and then you will use on => update.

Let's say you also have a group field that is set when the object is created, but this will never be changed. Then you will use on => create.

0


source







All Articles