2013-09-21 57 views
0

選擇默認值下拉(鍵值陣列)這裏是表單中的下拉列表:在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));?> 
+0

不要直接在表單中使用「值」(''value'=> $ customers'),它會在POST失效後殺死「表單狀態」。也不要使用read()。使用find()來代替。 – mark

回答

1

最好的辦法是利用控制器此

if ($this->request->is('post')) { 
    $this->Model->create(); 
    if ($this->Model->save($this->request->data)) { 
     ... 
    } else { 
     ... 
    } 
} else { 
    /* Now here you can put your default values */ 
    $this->request->data['Model']['field'] = ...; 
} 

對於詳情見http://www.dereuromark.de/2010/06/23/working-with-forms/

+0

我試圖這樣設置: $ this-> request-> data ['Project'] ['customer_id'] == $ customer_id; 但我得到的總是數組中的第一項被選中。 – Domas

+0

爲什麼兩個'=='?提示:發佈您的表單。當你調試'$ this-> request-> data'時,你的數組數據看起來像這樣,然後是它應該看起來像預先選擇正確的默認值。 – mark

+0

我已將控制器功能和表單添加到問題中。 ==是錯誤的答案。 – Domas