tags:

views:

32

answers:

2

hi, this is my problem i,ve to create a dropdown list box from a table states('id','state_name') which is not my default model( which has many fields one of the field is 'state' in which i store states('id') . so i used loadModel to populate the drop down box. in my controller i used

$this->loadModel('State');
$this->set('states',$this->State->find('all'));

in the view side

$form->select('State_id',$states);

in the output the table name, the id and name are displaying.

when i printed $states using pr(); what i got was

Array
(
    [0] => Array
        (
            [State] => Array
                (
                    [id] => 1
                    [state_name] => state1
               )

        )

    [1] => Array
        (
            [State] => Array
                (
                    [id] => 2
                    [state_name] => state2
                )

        )

and so on

how to create an array like array(1=>state1, 2=>state2) from the above array or is there any other way to create a dropdown listbox

kindly help

A: 

The below code will create the array you wanted from the original array

$newstates = array();

foreach($states as $state) {
    $state = $state['State']
    $newstates[$state['id']] = $state['state_name'];
}

pr($newstates);

Array
(
    [1] => state1
    [2] => state2
)
Lizard
While this works, it's not the best way to do it. It'll prove awkward to understand at a later date. Better is to use the cakephp wrapper - the 'list' option of find().
Leo
its throwing error to acess the value i have to use $states[0]['State']['state_name'] for state1leo answer is the one i was searching
chinni776
A: 

This is the way:

$fields = array('id','state_name');
$states = $this->State->find('list',array('fields'=>$fields));
$this->set(compact('states'));

or in one line:

$this->set('states',$this->State->find('list',array('fields'=>array('id','state_name'))));
Leo
find('list') is a very useful option to know:http://book.cakephp.org/view/449/find
Leo
thank u for u help i was struggling for the past two hours to solve itand also i'll read the above article
chinni776
If you do the above and put `$form->input('state_id')` in your view, Cake will automatically create and populate a select dropdown if it can find your `$states` variable. Cake is magic.
deizel