Tuesday, February 03, 2009

CakePHP Containable and Set::combine for MultipleDisplayField

A while ago I extended Daniel Albert's Multiple Display Field Behavior to support fields from related models. It works well enough but the catch is the "recursive" parameter that needs to be properly set for the related data to be available. Down the road I became uncomfortable with this unnecessary self imposed recursion especially considering the fact that I was successfully using the Containable behavior almost everywhere I needed related fields available in my views.
So the alternative is using Containable and processing the result trough Set::combine. And here I get to the reason of my post. Combine actually allows you to pass two arrays for paths so you can set the first one to the id path of your main model and the second one to an array of paths to the elements you need to compose your display value like this:


Set::combine( $res, '{n}.MainModel.id', array( '%s %s', '{n}.MainModel.name', '{n}.AssocModel.name' ));


The above code will give you a nice find('list') like result for populating a select element.
This subtle trick eluded me for a while but I found a comment on Track. Lost the link for it and I can't find it anymore, sorry. This Set class has so many obscure tricks that even Google fails to properly sort them out :)
So on a first thought having the stuff pulled automagically for you via a behavior looks appealing but when the going gets tough you're better off having a strong grip with the Containable and make custom compositions as needed. Although with Containable you still need to watch the number of db requests it generates...

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home