Cakephp Data Validation How to Avoid Duplicate Records with isUnique

Let’s say you build a CakePhp app to allow a used car dealership to edit their stock of vehicles. It would be helpful if it the validation rules when adding a new vehicle prevent a user from entering the same vehicle more than once. Fortunately using CakePhp this is easy.

If we have a Model called Car and it’s display field is set to “registration” we can add the isUnique rule to the Validation array. So if you look at the sample code below you’ll see that when a user tries to enter the same vehicle more than once they will be prevented from doing so and will receive the message “‘a car with that registration already exists”.

<?php
App::uses(‘AppModel’, ‘Model’);
/**
* Car Model
*
*/
class Car extends AppModel {

/**
* Display field
*
* @var string
*/
public $displayField = ‘registration’;

/**
* Validation rules
*
* @var array
*/
public $validate = array(

‘registration’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
//’message’ => ‘Your custom message here’,
//’allowEmpty’ => false,
//’required’ => false,
//’last’ => false, // Stop validation after this rule
//’on’ => ‘create’, // Limit validation to ‘create’ or ‘update’ operations
),
),

‘registration’ => array(
‘rule’ => ‘isUnique’,
‘required’ => true,
‘allowEmpty’ => false,
‘on’ => ‘create’, // here
‘last’ => false,
‘message’ => ‘a car with that registration already exists’
),

);

}

Also don’t forget to RTFM – http://book.cakephp.org/2.0/en/models/data-validation.html

Advertisements
Posted in Cakephp

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: