问题
I am trying to implement selectbox in my site.Option for that selectbox is set in my controller like below
$tmp_user = $this->User->find('first',array('id'=>$this->Auth->user('id')));
$zip_info = $this->Zipcode->find('first',array('id'=>@$tmp_user['User']['zip_id']));
$region_admins = $this->AdminRegion->find('all',array('conditions'=>array('AdminRegion.region_id'=>@$zip_info['Zipcode']['region_id'])));
if(!empty($region_admins)){
foreach($region_admins as $radmn):
//pr($radmn);
$admin_user = $this->User->find('list',array('conditions'=>array('id'=>$radmn['AdminRegion']['user_id']),'fields'=>array('id','username')));
pr($admin_user);
$this->set('users',$admin_user);
endforeach;
I am getting value like this when i print from controller
Array
(
[137] => governmentuser1
)
Array
(
[198] => testadmin
)
Array
(
[215] => adminregion
)
Array
(
[224] => testcompany1234
)
Array
(
[225] => testuser12345678
)
but only last value is set in select box.... Where did i made mistake?
回答1:
How about something like this:
<?php
$tmp_user = $this->User->find('first', array(
'id' => $this->Auth->user('id')
));
$zip_info = $this->Zipcode->find('first', array(
'id' => @$tmp_user['User']['zip_id']
));
$region_admins = $this->AdminRegion->find('list', array(
'conditions' => array(
'AdminRegion.region_id' => @$zip_info['Zipcode']['region_id']
),
'fields' => array('AdminRegion.user_id', 'AdminRegion.user_id')
));
$admin_users = $this->User->find('list', array(
'conditions' => array(
'id' => $region_admins
),
'fields' => array(
'id','username'
)
));
?>
A few side notes:
- Why do another query for the user data? Isn't it all in the session?
- I wouldn't use the @ anywhere, it's slower and suppresses errors. It will make debugging a nightmare too.
回答2:
I think you missed array:
$admin_user[] = $this->User->find('list',array('conditions'=>array('id'=>$radmn['AdminRegion']['user_id']),'fields'=>array('id','username')));
Hope it helps
来源:https://stackoverflow.com/questions/8276995/cakephp-findlist-for-select-box