CakePHP在订购后选择框值不对

时间:2012-03-20 11:01:49

标签: php 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不会随用户名切换。

如果我在print_r($owners)数组正确之前执行了array_splice($owners, 0, 0, "All");。当print_r($owners)数组之后的array_splice($owners, 0, 0, "All");不正确 - 但我不知道为什么......我假设array_splice重新编号数组...怎么可以添加“任何”来数组没有弄乱我的关系?

2 个答案:

答案 0 :(得分:2)

您最好使用Form帮助程序的输入法的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'
));

答案 1 :(得分:0)

试试这个

$owners = $this->Ticket->Owner->find('list', array(
         'conditions' => array('Owner.id NOT'=>'0')
         'fields' => array('Owner.id', 'Owner.username')
         'order' => array('Owner.username' => 'asc')
));