0

这是表单中的下拉列表:

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

1 回答 1

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/

于 2013-09-21T18:27:03.900 回答