CakePHP 2.3 - 保存相关模型数据

时间:2013-04-23 06:21:55

标签: cakephp validation cakephp-appmodel cakephp-2.3

我正在尝试遵循食谱中的惯例,但我没有运气。我烘焙了所有的CRUD和模型关联,需要自定义管理员添加视图(管理员有1个用户)。当我尝试验证时,我收到管理员模型但不是用户模型的相应错误消息。这是我用于表单的内容......

/* User Data */
echo __('<h3>Setup Login Information</h3>');
echo $this->Form->input('User.0.username');
echo $this->Form->input('User.0.password',  array('type'=>'password'));
echo $this->Form->input('User.0.password_confirm',  array('type'=>'password'));
echo $this->Form->input('User.0.user_role_id' );

/* Administrator Data */
echo __('<h3>User Information</h3>');
echo $this->Form->input('Administrator.first_name');
echo $this->Form->input('Administrator.last_name');
echo $this->Form->input('Administrator.title');
echo $this->Form->input('Administrator.email_address');
echo $this->Form->input('Administrator.phone_number');

这是我在控制器中设置的内容......

if( !empty($this->request->data) ) {
    // Use the following to avoid validation errors:
    unset($this->Administrator->User->validate['Administrator_id']);
    $this->Administrator->saveAssociated($this->request->data);
}

$users = $this->Administrator->User->find('list');
$userRoles = $this->User->UserRole->find('list');
$this->set(compact(array('users', 'userRoles')));

1 个答案:

答案 0 :(得分:2)

如果管理员有1个用户,则无需在表单输入中指定索引:

echo $this->Form->input('User.0.username');
echo $this->Form->input('User.0.password',  array('type'=>'password'));
echo $this->Form->input('User.0.password_confirm',  array('type'=>'password'));
echo $this->Form->input('User.0.user_role_id' );

实际应该是:

echo $this->Form->input('User.username');
echo $this->Form->input('User.password',  array('type'=>'password'));
echo $this->Form->input('User.password_confirm',  array('type'=>'password'));
echo $this->Form->input('User.user_role_id' );