This blog is about the PHP solutions I have to think of when I'm developing systems almost every single day...

Tuesday, March 25, 2008

Fixing habtm in cakephp

Okay... One of the cool things about cakephp is it's habtm (Has and belongs to many) relationship. It is great and works more the less out of the box if all your settings are correct (Hint: use cake bake to get it right). But I found some undefined behavior if you are editing a form with more than 1 habtm field. If you select the second item in the first list, it will also save the second item in your second list even if you did not select it. After much bashing my head over it, I finally tracked it all the way to the file cake/libs/model/models.php. It looks like the $newValues used at line 1301 is not unset for the second loop. So just add:


unset($newValues);


Right after the insertMulti line. And it will be working alright.

But there is another problem. If you use the 'multiple'=>'checkbox' option in your form, you will get an error if you uncheck all the options. That is because it will not set the $value for line 1284. Add the whole block in an:

if(is_array($value)){
....
}


And all will be okay. Hope that helps

8 comments:

Anonymous said...

Yes!

Great tip - thanks man. I was beginning to look at the trac changes in the bakery and wondering how we were ever going to get multiple HABTMs working, but hey presto..

Good stuff, thanks again..

Nick

Abdullah Zainul Abidin said...

You're welcome. Glad you find it useful.. :)

Abdullah Zainul Abidin said...

Note: This post is extremely outdated. It has been fixed in Cakephp for a long time. But the fix has not been moved to trunk at the time of my writing. If you want the latest, check out the branches of cakephp. Just do an:
svn co https://svn.cakephp.org/repo/branches/1.2.x.x/ cakephp

And that will check out the latest that you'll need to get your work done.

Daniel said...

Hi

Thanks for the tip
I know this is outdated, but since they didnt update the trunk, I still have the same problem. :)

Thanks for the tip

Abdullah Zainul Abidin said...

You're welcome daniel.. :)

sdf said...

Salam Abdullah,
I've problem in Multi selecbox,

if you have a friend in group1
then you unselect (group1) and select (group2 & group3)
=> when you save
it saves all the 3 groups and can't understand that i unselect the group 1

acutally it was working perfectly in this version: 5811 of 1.2.xx

but when i upgrade cake to :7296
this problem appears,

if you can help me, you'll be my hero

thank you for your amazing plug:)

Hussain said...

Hi,

I solved it by :
$this->Friend->query('delete from groups_friends where friend_id='.$this->data['Friend']['id']);

and it works fine,
any other ideas ?

thanks bro

Victor piousbox said...

thanks much! This actually helped a lot.

About Me

My Photo
Abdullah Zainul Abidin
I am what I am because of what I am...
View my complete profile