0

I have these models:

class Prefix extends AppModel {
    public $displayField = 'prefix';

    public $hasMany = array(
        'State' => array(
            'className' => 'State',
            'foreignKey' => 'prefix_id',
            'dependent' => false,
        ),
    );
}

class State extends AppModel {
    public $displayField = 'name';

    public $belongsTo = array(
        'Prefix' => array(
            'className' => 'Prefix',
            'foreignKey' => 'prefix_id',
        ),
    );
}

Then I have this admin_add method, from the automatic scaffolder:

public function admin_add() {
    if ($this->request->is('post')) {
        $this->Peefix->create();
        if ($this->Prefix->save($this->request->data)) {
            $this->redirect(array('action' => 'index'));
        } else {
                            // Error message
        }
    }
    $states = $this->Prefix->State->find('list');
    $this->set(compact('states'));
}

I also have the list of them in my form:

<?php echo $this->Form->input('State', array('multiple' => 'checkbox', 'type' => 'select',)); ?>

Now I can set the States for the Prefix. However, when I submit the form, the selection disappears. It is not saved in the database.

What did I do wrong?

4

2 回答 2

1

您将模型链接起来,好像每个前缀只有一个状态,并且许多前缀“分配”到一个状态。这意味着您不能使用'multiple' => 'checkbox'. 因此,要么删除它,要么将模型关联更改为 HABTM。

于 2013-05-10T10:24:39.043 回答
0

hasMany首先,和的两个外键belongsTo必须相同。如果在您提供的父模型invoice_circle_id中作为键,那么在子模型中也必须提供相同的值。显然,该字段必须存在于子表中。有关更多信息,请参阅此http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

其次 - 您可能希望使用 saveAll() 或 saveAssociated() 方法来保存链接模型数据。再次 - http://book.cakephp.org/2.0/en/models/saving-your-data.html包含您需要的所有信息规范。

至于为 的输入字段命名hasMany,您可以这样命名它们:

$this->Form->input('ParentModel.fieldname');
$this->Form->input('ChildModel.0.fieldname');
于 2013-05-10T08:36:37.557 回答