Populating a SELECT box with distinct values
Let’s say you log events into a database table Log. Attribute event holds event type and you want to filter the log listing just by that.
Here’s what you probably try at first:
-
-
$this->set(‘events’,
-
$this->Log->find(‘list’,
-
It’s not gonna work and you will have to use find(’all’) and Set::combine() to get what you want:
-
-
$events = $this->Log->find(‘all’,
-
$this->set(‘events’,
-
Set::combine($events, ‘{n}.Log.event’, ‘{n}.Log.event’));
-
January 16th, 2009 at 5:54 am
Ok,
I’m still perplexed with simply populating a SELECT box with distinct values from a table column.
Something like:
$this->set(’citylist’, $this->Zldinput->find(’list’, array(’fields’=>’Zldinput.City’, ‘group’=>’Zldinput.City’)));
gets me close, but as you mention my array has elements of the id and City thus my SELECT gets
BOSTON
where I want the ……value=”BOSTON”>BOSTON.
your solution is close but combine throws an error on $events
Cheers, Steve
January 16th, 2009 at 2:03 pm
Hi Steve, that’s weird that you’re getting an error.
I’m using CakePHP 1.2.0.7692 RC3 and my real code differs from the example I have given in my post only in that I specify additional options like “order” and “recursive” for the find() call.
My best guess is that your find call doesn’t return a valid search result array (e.g. because of a typo in a field name), or you changed the variable name that holds it but forgot to change it later in the combine call as well. I create this kind of errors all the time.
Petr
September 25th, 2009 at 9:34 am
How about this…
$list = $this->find(’list’, array(’fields’ => array(’Model.field’)));
return array_unique($list);
September 25th, 2009 at 11:07 am
Ming, your code wouldn’t work for several reasons:
array(0 => value1, 1 => value2 …)
and thus if I choose value1 in the SELECT box it’s in fact “0″ that gets submitted.
We need
array(value1 => value1, value2 => value2 …)
because we want value1 submitted.
array(0 => value1, 1 => value2 …)
But thanks for commenting. Expressing opinions, making suggestions. That’s what these comments are for.
December 8th, 2009 at 1:56 am
After a lot of tests, I finally solved this problem with this ridiculous line:
$years = $this->Payments->find(’list’, array(’fields’ => array(’year’, ‘year’)));
Sorry for my bad english, I am Brazilian.