Validation rule for a composite unique index (non-primary) - validation

I am sure I am not the first who has composite unique keys in tables and who wants to validate them. I do not want to invent the bicycle so I ask here first. I have several tables that have 'id' columns as primary keys and two other columns as unique composite keys. It would be nice to have a validation rule to check that the submitted entry is unique and display a validation error if it is not. In Cakephp it could be done by a custom validation rule. I am pretty sure somebody has created such method already.
Ideally it would be a method in app_model.php that could be used by different models.

I am using that function:
function checkUnique($data, $fields) {
if (!is_array($fields)) {
$fields = array($fields);
}
foreach($fields as $key) {
$tmp[$key] = $this->data[$this->name][$key];
}
if (isset($this->data[$this->name][$this->primaryKey]) && $this->data[$this->name][$this->primaryKey] > 0) {
$tmp[$this->primaryKey." !="] = $this->data[$this->name][$this->primaryKey];
}
//return false;
return $this->isUnique($tmp, false);
}
basically the usage is:
'field1' => array(
'checkUnique' => array(
'rule' => array('checkUnique', array('field1', 'field2')),
'message' => 'This field need to be non-empty and the row need to be unique'
),
),
'field2' => array(
'checkUnique' => array(
'rule' => array('checkUnique', array('field1', 'field2')),
'message' => 'This field need to be non-empty and the row need to be unique'
),
),
So basically this will show the warning under each of the fields saying that it's not unique.
I am using this a lot and it's working properly.

In the CakePHP/2.x versions released in the last few years, the isUnique rule optionally accepts several columns:
You can validate that a set of fields are unique by providing multiple
fields and set $or to false:
public $validate = array(
'email' => array(
'rule' => array('isUnique', array('email', 'username'), false),
'message' => 'This username & email combination has already been used.'
)
);
I'm not sure of the exact version when the feature was available but there's a bug fixed in core as late as October 2014 filed against 2.3 and 2.4 branches.

You could put it in app model, but my suggestion would just be to add it to the model directly by placing the rule with it's $validate property.
Check out the built in isUnique rule.

Related

CakePHP Validate a specific rule only when a couple required fields aren't empty

I wrote a custom rule method for validating whether a record exists in the DB before adding a new record. I put the method in a behavior so I could share it with other models, but I've run into a chicken and egg situation.
In order to know whether a category has a specific group name already I need to have the category id, and the group name. So I pass those keys through using my custom rule (category_id and name). But, this won't work since if I don't choose a category_id by mistake then the query will occur on just the name, so I patched this with a couple lines, but need to return true if this is the case and bank on the category_id validation being invalid.
Is there a better way to implement this kind of validation? Is this not as bad as I think? Or just don't bother and in my controller drop hasAny() under my call to validates() if it passes.
MODEL:
public $validate = [
'category_id' => [
'rule' => 'notEmpty',
'message' => 'Category is required.'
],
'name' => [
'notEmpty' => [
'rule' => 'notEmpty',
'message' => 'Team is required.'
],
'recordExists' => [
'rule' => [ 'recordExists', [ 'category_id', 'name' ] ],
'message' => 'Group already exists.'
]
]
];
// BEHAVIOR:
public function recordExists( Model $Model, $conditions, $requireKeys )
{
// Overrite conditions to
$conditions = $Model->data[ $Model->name ];
// Trim all array elements and filter out any empty indexes
$conditions = array_map( 'trim', $conditions );
$conditions = array_filter( $conditions );
// Get the remaining non-empty keys
$conditionKeys = array_keys( $conditions );
// Only query for record if all required keys are in conditions
if (empty( array_diff( $requireKeys, $conditionKeys ) )) {
return !$Model->hasAny( $conditions );
}
// NOTE: seems wrong to return true based on the assumption the category_id validation has probably failed
return true;
}
Use the beforeValidate() callback of the model to check if the fields are present and if they're empty. If they're empty just unset() the recordExists validation rule in your models validation property. Copy them to a temporary variable or property in the case you want to set them back after your current operation.
And use $Model->alias, name will break if the model is used through an association that has a different name.
$conditions = $Model->data[ $Model->name ];

cakephp saveAssociated and validation foreign_key fails

I have two models that we're going to name Model and RelatedModel. Model has many RelatedModel. So if I add foreign key validation on validation array like:
public $validate = array(
'foreignKey' => array(
'rule' => 'numeric',
'required' => true,
'message' => 'The id of relatedmodel should be a number'
)
)
After I create a add() function to save new registers and in this function I use saveAssociated with validation true, this one fails throwing an error 'The id of relatedmodel should be a number'.
I'm debugging the code and saveAssociated checks validation of both models at the same time and before save Model.
Is this an issue?
I think what this function should do is to validate Model, save it, add foreignKey of RelatedModel and then validate it before save.
I came into this issue only recently. It's not an issue, saveAssociated() is designed to work this way unfortunately.
What you can do is alter the required => true on the fly using the model validator. Check out the book for more information.
http://book.cakephp.org/2.0/en/models/data-validation.html#dynamically-change-validation-rules
This is working as would be expected with your given rule. required in Cake means it expects the value of foreignKey to be set in the save data prior to saving. All the validation will happen before Cake saves the data (and therefore before foreignKey is generated).
You shouldn't need to validate that it is numeric if you are allowing Cake to generate this for you behind the scenes. If you want to check that it is being passed in the data for an UPDATE you could modify the required to be only for an update like this:-
public $validate = array(
'foreignKey' => array(
'rule' => 'numeric',
'required' => 'update',
'message' => 'The id of relatedmodel should be a number'
)
)
Personally I wouldn't bother validating foreign keys unless a user is setting them rather than Cake.
Update:
To validate the foreignKey if it exists in a form submission you can drop the required option from the validation rule:-
public $validate = array(
'foreignKey' => array(
'rule' => 'numeric',
'message' => 'The id of relatedmodel should be a number'
)
);
This will allow you to pass data where the foreignKey is not present without throwing a validation error whilst validating it if it is.

cakephp 2.x include userExists in validating login

I'm new to CakePhp, I'm using CakePhp 2.x.
I am probably going about solving the problem below the wrong way. And I just know I'm overlooked something real simple but,.....
I'm validating login details based on 'Between 5 to 15 characters' they are retuning errors as expected.
[The MODEL]
public $validate = array(
'username' => array(
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
)
);
[The CONTROLLER]
public function login() {
if ($this->request->data) {
$this->User->set($this->request->data);
if ($this->User->validates() && $this->Auth->login()) {
if ($user = $this->Auth->user()) {
$this->render($this->Auth->redirect());
}else{
//??
}
}else{
$this->User->create();
pr($this->User->invalidFields());
$errors = $this->User->validationErrors;
$data = compact('errors');
$this->set('errors', $data);
$this->set('_serialize', array('errors'));
$this->Session->setFlash('Your username/password combination was incorrect');
}
}
}
So, the problem is, if the fields follow the rules in the model above even if the login details (the user) doesn't exist, no errors will be returned (no good). Would it be correct to add an other validation for this, adding another rule to check if that user actually exists? If so how!?
Or, do I work this into the controllers login function checking if the user exists? I'm a little confused now. Maybe I've been looking at the screen for too long.
Thanks.
Would it be correct to add an other validation for this, adding
another rule to check if that user actually exists? If so how!?
You can add as many rules as you want. In this case you want the rule "unique". Read this section of the book about data validation.
Or, do I work this into the controllers login function checking if the
user exists?
All data manipulation and validation should happen in the model layer of the MVC stack. So put everything into a model method and pass the post data to it and validate it there. You can put all logic into the controller to but that's stupid in terms of not following the MVC pattern. Models can be shared between shells and controllers for example, a controller not. Again you could instantiate a controller in a shell but doing all of this negates any benefit and idea the MVC pattern has. Also a model is competitively easy to test. And yes, you should unit test your code. Check how our users plugin is doing it for example.
You can specify multiple rules per field...
Follow this link to learn more about it...
http://book.cakephp.org/2.0/en/models/data-validation.html#multiple-rules-per-field
a sample code is given below
<?php
[IN The MODEL]
//the following code checks if the username is notempty, is a valid email and is it already taken or not...
public $validate = array(
'username' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter a valid email.',
),
'email' => array(
'rule' => array('email'),
'message' => 'Please enter a valid email.',
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken.'
)
)
);
?>

Yii CGridview - search/sort works, but values aren't being displayed on respective cells

I am semi-frustrated with this Yii CGridView problem and any help or guidance would be highly appreciated.
I have two related tables shops (shop_id primary) and contacts (shop_id foreign) such that a single shop may have multiple contacts. I'm using CGridview for pulling records and sorting and my relation function in shops model is something like:
'shopscontact' => array(self::HAS_MANY, 'Shopsmodel', 'shop_id');
On the shop grid, I need to display the shop row with any one of the available contacts. My attempt to filter, search the Grid has worked pretty fine, but I'm stuck in one very strange problem. The respective grid column does not display the value that is intended.
On CGridview file, I'm doing something like
array(
'name' => 'shopscontact.contact_firstname',
'header' => 'First Name',
'value' => '$data->shopscontact->contact_firstname'
),
to display the contact's first name. However, even under circumstances that searching/sorting are both working (I found out by checking the db associations), the grid column comes out empty! :( And when I do a var_dump
array(
'name' => 'shopscontact.contact_firstname',
'header' => 'First Name',
'value' => 'var_dump($data->shopscontact)'
),
The dump shows record values in _private attributes as follows:
private '_attributes' (CActiveRecord) =>
array
'contact_firstname' => string 'rec1' (length=4)
'contact_lastname' => string 'rec1 lsname' (length=11)
'contact_id' => string '1' (length=1)
< Edit: >
My criteria code in the model is as follows:
$criteria->with = array(
'owner',
'states',
'shopscontacts' => array(
'alias' => 'shopscontacts',
'select' => 'shopscontacts.contact_firstname,shopscontacts.contact_lastname',
'together' => true
)
);
< / Edit >
How do I access the values in their respective columns? Please help! :(
Hmm, I have not used the with() and together() methods much. What's interesting is how in the 'value' part of the column, $data->shopscontacts loads up the relation fresh, based on the relations() definition (and is not based on the criteria you declared).
A cleaner way to handle the array output might be like this:
'value' => 'array_shift($data->shopscontacts)->contact_lastname'
Perhaps a better way to do this, though, would be to set up a new (additional) relation, like this in your shops model:
public function relations()
{
return array(
'shopscontacts' => array(self::HAS_MANY, 'Shopsmodel', 'shop_id'), // original
'firstShopscontact' => array(self::HAS_ONE, 'Shopsmodel', 'shop_id'), // the new relation
);
}
Then, in your CGridView you can just set up a column like so:
'columns'=>array(
'firstShopscontact.contact_lastname',
),
Cheers
Since 'shopscontact' is the name of the has-many relation, $data->shopscontact should be returning an array with all the shops related... did you modify the relation in order to return only one record (if I didn't get you wrong, you only need to display one, right?)? If you did it, may I see your filtering code?
P.S. A hunch to get a fast but temporal solution: have you tried 'value' => '$data->shopscontact['contact_firstname']'?

CakePHP Validation - isUnique OR inList

(New to CakePHP, so this may be an obvious thing, but I was unable to find a solution after searching for a couple of hours - the ambiguous nature of "or", I guess...)
I am trying to modify an existing CakePHP validation rule, which uses the isUnique rule, so that it will validate for values which satisfy either the isUnique rule or an inList rule.
The previous code:
'isUnique' => array(
'rule' => 'isUnique' ,
'message' => "We're sorry, but this QA number is already being used.",
'last' => TRUE,
),
My (faulty) code:
'isUnique' => array(
'rule' => array(
'isUnique' ,
array( 'inList' , array( '111213' , '141516' , '171819' , '202122' ) )
) ,
'message' => "We're sorry, but this number is already being used.",
'last' => TRUE,
),
So, (as simple as this may be), how can you string CakePHP validation rules together with an "OR" logical operator? I can see that you can apply a cascade of "AND" rules (with each testing for a specific issue and, if failing that test, rejecting the value), but "OR" rules have me scratching my head...
Any help appreciated.
You'll have to make that a custom validation rule. Add this in your model:
public function isUniqueOrInList(array $data, array $list) {
return in_array(current($data), $list) || $this->isUnique($data);
}
Then declare your rule like:
'rule' => array('isUniqueOrInList', array('111213', '141516', '171819', '202122'))

Resources