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

Monday, February 25, 2008

What will you find?

Hmm... The lack of clear documentation is getting clearer and clearer as I find that I have to code dive more and more to learn how to use CakePHP. Latest one is how on earth do you use the find method?

According to the api, the declaration is like this:

function find($conditions = null, $fields = array(), $order = null, $recursive = null) {

So it accepts conditions, then fields, order and recursive value. But if you had searched a little more on the internet before looking at the api you might have found some people did this:

$model->find('list',array('conditions'=>array('id'=>1)));

And looking into the code you will find that if $conditions is a string and it is a valid find method then you are left with pretty much just two variables. $conditions become the type of find you want, $fields become an array of variables pertaining to the search which could have keys consisting of 'conditions' (like the example above), 'fields', 'limit', 'offset', 'order', 'page' and an array of 'joins'. The type (which we get from the variable $conditions) could either be 'count', 'first' or 'list'. The default (aka if you didn't set it in $conditions and it uses all the variables like the way they are named) is 'first'.

The reason why I was diving into the code initially was I wanted to make a list for the select box option. I was pretty sure that cakephp could easily take care of that. And inside the code I see it. The 'list' find type is already suited for this and it uses $this->displayField to display the option to be selected by the user and $this->primaryKey for the value to put into that option. The $this->primaryKey seems to default to id which is already good enough but $this->displayField should really be set in your model so that it would be used automatically. Once it is set, you're good to go. Just:

$this->Model->find('list',array('conditions'=>array('parent_id'=>'1')))

And you would already have all the data you need for your select box. It's pretty convenient but to get there is the real challenge.

0 comments: