選擇默認值下拉(鍵值陣列)這裏是表單中的下拉列表:在CakePHP
echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));
的$客戶是一個鍵值數組是這樣的:
array(
(int) 2 => 'Best customer',
(int) 5 => 'Good customer',
(int) 9 => 'Customer')
創建下拉菜單後,我需要預先選擇一個值。我試圖選擇一個默認值作爲int id和客戶名稱,但他們都沒有工作。
這裏是控制器編輯功能:
function edit($id = null) {
$this->Project->id=$id;
$this->Project->recursive = 0;
$customers = $this->Customer->find('list', array('conditions'=>array('company_id'=>$this->Auth->user('company_id'))));
$this -> set('customers', $customers);
if(!$this->Project->exists()){
throw new NotFoundException('Invalid project');
}
if($this->request->is('post')|| $this->request->is('put')){
if($this->Project->save($this->request->data)){
$this->Session->setFlash('The project has been edited');
$this->redirect(array('controller'=>'projects', 'action'=>'view', $id));
} else{
$this->Session->setFlash('The project could not be edited. Please, try again');
}
}else{
$this->request->data = $this->Project->read();
$this->request->data['Project']['customer_id'] = 'New customer';
}
}
這裏是編輯表單:
<?php echo $this->Form->create('Project');?>
<fieldset>
<legend><?php __('Edit Project'); ?></legend>
<?php
echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));
echo $this->Form->input('name');
echo $this->Form->input('project_nr', array('type'=>'text', 'label'=>'Case number'));
echo $this->Form->input('address');
echo $this->Form->input('post_nr');
echo $this->Form->input('city');
echo $this->Form->input('start_date', array('label'=>'Start Date', 'class'=>'datepicker', 'type'=>'text'));
echo $this->Form->input('finish_date', array('label'=>'End Date', 'class'=>'datepicker', 'type'=>'text'));
echo $this->Form->input('company_id', array('value' => $current_user['company_id'], 'type'=>'text', 'type'=>'hidden'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
不要直接在表單中使用「值」(''value'=> $ customers'),它會在POST失效後殺死「表單狀態」。也不要使用read()。使用find()來代替。 – mark