views:

918

answers:

2

I have a form with the following fields:

  • firstName
  • lastName
  • emailAddress

followed by (up to) ten name/email fields, like so

  • friendName-1
  • friendEmail-1
  • friendName-2
  • friendEmail-2 ... etc.

The firstName, lastName & emailAddress fields will be saved into a 'referrals' table, but 10 name/email pairs will go into a 'friends' table, containing a foreign key refferal_id.

Normally I use the cakephp 'automagic' forms, and set up my validation in the model, and do a $this->model->save(); If it fails I fall back on my model validation rules and the error messages get spat back into my form html. No problems.

How would I do this for TWO tables though? I'm thinking that the automagic stuff is not the way to go, but I feel I will lose a lot without it, such as validation in my models and custom error messages.

Is there a happy medium? I'm fairly new to cake so I'm wondering if theres a way to use automagic with multiple tables.

+3  A: 

See http://book.cakephp.org/view/84/Saving-Related-Model-Data-hasOne-hasMany-belongsTo

Create the relationship in your Referral model:

var $hasMany = array('Friend');

Essentially, make sure you name your fields correctly, e.g.

echo $form->create('Referral');
echo $form->input('first_name');
echo $form->input('last_name');
echo $form->input('email');
foreach (range(0,9) as $index) {
  echo $form->input('Friend.'.$index.'.name');
  echo $form->input('Friend.'.$index.'.email');
}
echo $form->end();

And in your referrals controller:

function add() {
   if(!empty($this->data)) {
      $this->Referral->saveAll($this->data, array('validate'=>'first'));
   }
}
neilcrookes
+1  A: 

First, I really hope that you don't have 20 fields in table called 'friendName-1', 'friendEmail-1', etc. Your second table should have 3 fields--your referral_id, friendname, and friendemail. If you don't want to normalize, then you don't need the second table.

But I digress, the way to keep your automagic forms is to put a "hasMany" in your referrals model and/or a "belongsTo" in your "friends" model. Then you can still use the FormHelper and Model->Save().

mgroves
:) no i didn't make myself clear enough. The horrible hard coded -1,-2 stuff is just for the html form. I will just loop through them and save them as individual rows in my friends table.
Pickledegg
Then I think as long as you use hasMany/belongsTo, you should be able to automagic.
mgroves