Mirdrack
Mirdrack

Reputation: 790

Create a validation rule for colums of the join tables in CakePHP

I have a hasAndBelongsToMany association between two tables(Recipes and Ingredients) in a CakePHP joined with a linking table(ingredients_recipes).

My ingredients_recipes table has an amount colum in order to save the value of the ingredient for the recipe but i dont know how or where create a validation rule for allow only numbers in that colum.

I already look here and in the documentation but i cant found nothing.
If you need more information please let me know
Thnks

Upvotes: 0

Views: 165

Answers (2)

Anubhav
Anubhav

Reputation: 1623

Create validation rules in Recipe.php and Ingredient.php Models, example is shown below:

Step 1: Open Ingredient.php

Step 2: Edit Ingredient.php

Class Ingredient extends AppModel{
    var $name = 'Ingredient';
    public $validate = array(
      'ingredients_recipes' => array(
        'rule'    => 'numeric',
        'message' => 'Please supply the number of ingredients recipes.'
       )
    );
}

Step 3: Save and execute your code.

Now your Ingredient model validates ingredients_recipes for numeric vaidation and if fails then returns the "message".

Same way way you can create multiple validation rules for other models.

For ref: http://book.cakephp.org/2.0/en/models/data-validation.html

Upvotes: 0

Kai
Kai

Reputation: 3823

If you're storing additional fields on the join table, you will have to deal with the join table explicitly, rather than in a hasAndBelongsToMany, where CakePHP takes care of the join table behind the scenes, and therefore the validation rule should be on ingredients_recipes.

This type of relationship, by the way, is known as a hasManyThrough, and is basically just expressed as recipes hasMany ingredients_recipes and ingredients_recipes has many ingredients.

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through-the-join-model

Upvotes: 1

Related Questions