1

大家好,我正在尝试使用带有连接关联的 hasMany 向数据库添加信息

Invoice - id, sender_id, receiver_id, template_id
Field - id, name, description, default_value, template_id
fields_invoices - id, invoice_id, field_id, entered_value

这是视图

<?php echo $this->Form->create('FieldsInvoice'); ?>
<?php foreach ($fields as $field): ?>
<?php echo $this->Form->hidden($invoice_id); ?>
<?php echo $this->Form->hidden($field['Field']['id']); ?>
<?php echo $this->Form->Input($field['Field']['name'], array('default' =>$field['Field']['default_value'])); ?>
<?php endforeach ;?>
<?php echo $this->Form->End('Submit');?>

这是控制器

public function create($id)
    {   
    $this->set('title_for_layout', 'Create Invoice');
    $this->set('stylesheet_used', 'homestyle');
    $this->set('image_used', 'eBOXLogoHome.png');   
    $this->layout='home_layout';


     if (!is_numeric($id)) throw new BadMethodCallException('I need an ID');
     $this->Invoice->id = $id;
     if (!$this->Invoice->exists()) throw new NotFoundException('Invalid ID');

    $this->set('invoice_id',$id);

    $names = $this->Invoice->find('list',array(
    'fields'=>array('template_id'),
    'conditions'=>array('id'=>$id)));

    $fields = $this->Field->find('all', array(
     'conditions'=>array(
     'template_id'=>$names)));

    $this->set(compact('fields'));
    $this->set(compact('invoice_id'));

    $this->set('name',$names);
    $this->Invoice->create();
    if(empty($this->data)){
        $this->data= $this->Field->read($id);
    } 
    else{
        if($this->request->is('post'))
        {
            die(debug($this->data));

            $this->Invoice->create();
            if($this->FieldsInvoice->save($this->request->data, array('deep'=>true)));
            {
            $this->Session->setFlash('The field has been updated');
            $this->redirect(array('controller'=>'invoices', 'action'=>'index'));

            }
            //else{
            $this->Session->setFlash('Could not be saved');
            //}
        }
    }
}

这是使用调试时打印的内容

\app\Controller\InvoicesController.php (line 134)
array(
    'FieldsInvoice' => array(
        (int) 87 => '',
        (int) 0 => '',
        'invoiceno' => 'test1',
        (int) 99 => '',
        'duedate' => 'test2',
        (int) 999 => '',
        'amount' => 'test3',
        (int) 9999 => '',
        'description' => 'test4'
    )
)

所有正确的信息都在那里,但没有提交到正确的地方,第一个 int 是invoice_id,其他其他 int 是field_id'test1','test2','test3','test4' 是entered_value. 不知何故,我需要对我的视图进行编码,以便将 , 保存invoice_idfield_id,test1同一个数组中,我该如何实现呢?

4

1 回答 1

1

不确定为什么要为每个字段创建 2 个隐藏字段。

首先阅读:http ://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto

echo $form->input('Account.0.name', array('label' => 'Account name'));
echo $form->input('Account.0.username');
echo $form->input('Account.0.email');

然后进一步阅读:http ://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-hasmany-through-data

于 2012-08-13T02:29:35.423 回答