Adding Criteria To Validation Rules

Sometimes you want your validation rules to be just a little bit more than the standard options available to you like ‘numeric’, ‘length’ or ‘safe’.

Occasionally you might need a value to be unique within it’s database column:

array('username', 'unique', 'className' => 'User');

But sometimes you want unique to be more intelligent with it’s unique validation…

array('username', 'unique', 'className' => 'User', 'criteria' => array(                 'condition' => 'active = 1',         ) )

The test above will only match when username is not unique AND active = 1. In the case of unique, criteria you define is appended to the existing check which would always take place.

Adding conditions to Yii model relations

Something I realised today is the power of adding conditions to model relations. This allows you to specify which records are returned as part of the relationship, which therefore allows you to set up several relationships for different situations.

for example:

'users' => array(self::MANY_MANY, 'User', 'user2project(project_id, user_id)', 'condition' => 'accepted = 1'),

This only brings back users who have accepted an invitation.

I can then also set up a new relation, called ‘invitedUsers’ where the condition is the opposite.

This allows me to access the users easily:

$project = Project::model()->findByPk(1); $users = $project->users; $invitedUsers = $project->invitedUsers;