Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP format find('all') to ('list') in view?

Tags:

php

cakephp

Is there a way to format the $this->find('all') array into the $this->find('list') in the view? The reason I ask is so that I can pass that new array into the form helper options and then use the $this->find('all') array to build some additional things I need?

Array ( 
[0] => Array ( [School] => Array ( [id] => 0 [name] => Nature [address] => 112 Main [max_students] => 25 [application_level] => 5 ) ) 
[1] => Array ( [School] => Array ( [id] => 1 [name] => Math [address] => 112 Smith [max_students] => 25 [application_level] => 0 ) ) 
[2] => Array ( [School] => Array ( [id] => 2 [name] => Art [address] => 112 Lane [max_students] => 25 [application_level] => 0 ) ) 
)

So this is the array I get when I do a find('all'). I want to build the array so it looks like:

Array (
[0] => 'Nature'
[1] => 'Math'
[2] => 'Art'
)

This is usually done by the $this->find('list') function. Though the reason I want the whole array is because I need to add the application_level into $this->Form->input() function. This is because I need to add the option of class with the application level attached so I show only the shows with the application level based on the previous selection.

EDIT: Can't I just do $this->find('list', [insert parameters here?]);? I just don't understand how you set up the additional parameters?

like image 807
pmac89 Avatar asked Nov 12 '13 03:11

pmac89


1 Answers

If your query isn't overly complicated and isn't going to return a excessive number of results, just run it twice (once for find all and once for find list).

Find all, list, first, whatever are all the same in terms of the paramaters you pass in. E.g.:

$this->Model->find('all', array(
    'conditions' => array(
        'field' => 500,
        'status' => 'Confirmed'
    ),
    'order' => 'id ASC'
));

... you literally replace all with list. In your case, probably easiest to do it twice, once for each. Like this:

$parameters = array(
    'conditions' => array(
        'field' => 500,
        'status' => 'Confirmed'
    ),
    'order' => 'id ASC'
);

$alldata = $this->Model->find('all', $parameters);
$listdata = $this->Model->find('list', $parameters);

Otherwise, you can loop through it and populate your own list:

$list = array();

foreach($findall as $row) {
    $id = $row['id'];
    $name = $row['name'];
    $list[$id] = $name;
}

$this->set('listdata', $list);

Short answer to your question is that there's no quick, easy way to select all and list from the same query, but you can re use your parameters (conditions, order etc) by passing them in as predefined arrays, or populate your own list.

like image 196
scrowler Avatar answered Sep 30 '22 02:09

scrowler