在cakePHP中为下拉列表(键值数组)选择默认值

时间:2013-09-21 16:36:53

标签: cakephp cakephp-2.0 cakephp-2.3

以下是表单中的下拉列表:

echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));

$ 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));?>

1 个答案:

答案 0 :(得分: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/