Tuesday, June 25, 2013

HABTM and forms

Hi everybody,

I'm struggling with a particular hasAndBelongsToMany form data problem and need some help.

Quickly:

1. A recipe can have many ingredients.
2. An ingredient can be in many recipes.
2. An ingredient in a recipe can be mandatory or optional (or not present).
4. an ingredient in a recipe should be present in a certain weight.

I don't simply need to add or remove ingredients but also to set some value for each of them.

These are my tables:

CREATE TABLE `ingredients` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE `recipes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE `ingredients_recipes` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `recipe_id` int(10) NOT NULL DEFAULT '0',
  `ingredient_id` int(10) NOT NULL DEFAULT '0',
  `mandatory` enum('M','O') DEFAULT NULL,
  `weight` int(10) DEFAULT '0',
  PRIMARY KEY (`id`)
)

There's an obvious hasAndBelongsToMany relation between recipes and ingredients.
I guess models could be something like this:

class Recipe extends AppModel
{
    public $hasAndBelongsToMany = array('Ingredient');
}

class Ingredient extends AppModel
{
    public $hasAndBelongsToMany = array('Recipe');
}


When I edit a recipe, I would like to select each single ingredient from a list.
In each line of the list I would like to have three radio buttons (or a "select" with three values) and a in input field for the weight:

  (*) do not select
  ( ) mandatory
  ( ) optional

  weight: NNNNN

Values are validated before saving. If "do not select" is set, the row is not saved (or deleted, if present).


Can anybody please suggest me some sample controller and view code for implementing such a form?


--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments: