CakePHP选择框值不正确后
问题描述:
//My Owner Model
var $belongsTo = array(
'Owner' => array(
'className' => 'User',
'foreignKey' => 'owner',
),
);
//My Tickets Controller
//Find the owners of the ticket to build select box
$owners = $this->Ticket->Owner->find('list', array(
'fields' => array('Owner.id', 'Owner.username')
'order' => array('Owner.username' => 'asc')
));
//Add "All" to the array of owners at 0 (no owner ids are 0)
array_splice($owners, 0, 0, "All");
//Set owner variable in my view.
$this->set(compact('owners'));
//My template file or view
echo $this->Form->create('Ticket', array(
'url' => array_merge(array('action' => 'find'), $this->params['pass'])));
echo $this->Form->input('title', array('div' => false));
echo "<br /><br />";
//Build the selectbox ordered by username
echo $this->Form->input('owner', array('div' => false, 'options' => $owners, 'id' => 'EndUser'));
echo "<br /><br />";
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
当选择框建立时,选择框按用户名排序喜欢我喜欢 - 但他们的ID不切换用户名。CakePHP选择框值不正确后
如果我在array_splice($owners, 0, 0, "All");
之前做了print_r($owners)
这个数组是正确的。当我 array_splice($owners, 0, 0, "All");
后阵列是不正确的 - 但我不知道为什么...我假设array_splice
重新编号的数组...如何可以添加“任何”到阵列而不会搞乱我的关系?
答
你最好使用表单助手的输入法empty
选项。你可以沿着钥匙去与它擦肩而过,所以更改:
echo $this->Form->input('owner', array('div' => false, 'options' => $owners, 'id' => 'EndUser'));
要这样:
echo $this->Form->input('owner', array(
'div' => false,
'options' => $owners,
'empty' => array(0 => 'All'), // Add this line
'id' => 'EndUser'
));
+0
真棒 - 这甚至更好! 谢谢! – dingerkingh 2012-03-20 11:38:26
答
试试这个
$owners = $this->Ticket->Owner->find('list', array(
'conditions' => array('Owner.id NOT'=>'0')
'fields' => array('Owner.id', 'Owner.username')
'order' => array('Owner.username' => 'asc')
));
我想通了 - 但不能回答我的问题。显然你可以添加数组 - 谁知道! (我相信可能是大多数人! //全部添加到数组顶部 $ allarray = array(0 =>“All”); $ owners = $ allarray + $ owners; – dingerkingh 2012-03-20 11:12:17