Wednesday, December 3, 2008

Re: How to add item using HABTM relation

You need to structure the data so that it has the right data and keys
for each record that will be added.

Your $this->data['Contract']['Person'] would be an array of the data
required for the person.

Since it appears you are doing this in your contracts controller, you
would need to get the ID for the person, then save the contract just
as you've shown.

I do something similar in my code: I have a "signup" sheet that uses
the currently logged in user's ID to add a row to the signup slots:

$this->User->create();
if ( $this->User->save($this->data) ){
$this->data['User']['user_id'] = $this->User-
>getLastInsertId();
$this->data['UserSlot']['user_id'] = $this->data
['User']['user_id'];

$this->User->UserSlot->create();

if ($this->User->UserSlot->save($this->data
['UserSlot'])) {
$user_slot_id = $this->User->UserSlot-
>getLastInsertId();


Basically I create the user, get the user ID, set the UserSlot's
user_id, and save the UserSlot ...

So as long as you set the data for the HATBM id's correctly, the rows
will be created.

On Dec 3, 9:57 am, Zeugme <zeu...@uku.co.uk> wrote:
> Hi,
>
> How to add an item to a HABTM relation ?
>
> I have a Person and I have to add a Contract to that person.
> Here are the data on a view :
>
> data[Contract][type] : 12
> data[Contract][name] : contract-AAaa
> data[Contract][Person] : 26 // Should I put the person id here ?? or  
> something else ??
>
> In fact, that contract added to person 26 could be later on added to  
> another Person, that's why its HABTM.
> Currently, I'm trying to add a new contract to an existing person, so  
> the question, but later I'm not sure how to just link an existing  
> contract to an existing person ...
>
> Here is the code on the controller to receive that data :
>      function add() {
>          if (!empty($this->data)) {
>                         $this-> Contract->create();
>                         if ($this-> Contract->save($this->data)) {
>                             $this->set('returncode', 'Contract '.$this-> Contract->id.'  
> saved');
>                         } else {
>                                 $this->set('returncode', 'ERROR : Contract '.$this-
>  >data['Contract']['name'].' not saved');
>                         }
>          }
>      }
>
> Thanks !
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: