[英]Create multiple forms on one page for different models in cakephp 3.x
我有2个模型:User和UserInfo具有关系1-1(一个用户有一个userinfo)。
用户(ID)是用户和的UserInfo(USER_ID) 主键是外国键和的UserInfo 主键 。
2个模型具有相同的属性:电子邮件,密码。
添加新用户时,我想向UserInfo插入“ user_id”,“ email”,“ password”。
但是,尽管用户已成功保存,但似乎可以插入到UserInfo中。
我认为它在($ this-> User-> UserInfos-> save($ userinfo))运行时停止。
有人可以帮忙吗? -这是我的代码-
///**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add() {
$user = $this->Users->newEntity();
$userinfo = $this->Users->UserInfos->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
$userinfo = $this->Users->UserInfos->patchEntity($userinfo, [
'user_id' => $user['User']['id'],
'email' => $user['User']['email'],
'password' => $user['User']['password'],
]);
if ($this->User->UserInfos->save($userinfo)) {
$this->Flash->success(__('The userinfo has been saved.'));
}
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user', 'userinfo'));
$this->set('_serialize', ['user', 'userinfo']);
}
//Code in add.php
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Add User') ?></legend>
<?php
echo $this->Form->radio('user_type',
[
['value' => '0', 'text' => 'Personal'],
['value' => '1', 'text' => 'Company'],
]);
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->hidden('status', ['value' => '0']);
echo $this->Form->hidden('authority', ['value' => '0']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
我认为您可以参考Bookmarker教程 ,因为在本教程中,在创建新Bookmarks
同时会创建新Tags
。 您可以将其视为创建UserInfo
的想法。
好吧,我也是CakePHP的新手,但针对您的情况有这个想法。
在您的控制器controller \\ UserController中,操作add()
创建User实体:
public function add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->User->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']); // same controller's index action, or you can set others
}
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
在模型model\\Table\\UserTable.php
,创建一个名为afterSave()
的函数,该函数在保存用户实体后创建UserInfo
$this->UserInfo->newEntity();
因此,在newEntity()
内部,您实际上设置了一些User没有的数据和UserInfo拥有的数据,除了user_id(如果已经设置了它们的关联 ,则应该设置user_id)
我强烈建议您遵循所有基本教程。
备注:我建议您明确定义模型的名称,因为CakePHP约定应该是CakePHP开发人员的重要主题。 因此,对于我输入的上述代码/文件名,如果它们与您的情况不完全匹配,可能会出错。 例如,用户/用户/ UsersInfo / UserInfo等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.