cakephp 3.x 将数据保存到 2 个表中时未显示模型验证
cakephp 3.x model validation not showing when Saving data into 2 tables
我有两个 tables 员工和用户员工有字段 user_id 他们之间的关系我们用户有一个员工和员工属于用户,我的视图文件中有以下代码
<?php
echo $this->Form->input('employee.name');
echo $this->Form->input('user.email');
echo $this->Form->input('user.username');
echo $this->Form->input('employee.employee_level');
?>
我的 EmployeeController 代码是
<?php
$employee = $this->Employees->newEntity($this->request->data);
$user = $this->Employees->Users->newEntity($this->request->data);
if ($this->request->is('post')) {
$employee = $this->Employees->patchEntity($employee, $this->request->data, [
'associated' => ['Users']
]);
if($this->Employees->save($employee)) {
$this->Flash->success(__('The employee has been saved.'));
} else {
$this->Flash->error(__('The employee could not be saved. Please, try again.'));
}
}
?>
如果一切顺利和完美,它正在保存数据,但如果存在一些验证错误,例如用户名已经存在或电子邮件已经存在,而不是简单地显示无法保存员工的闪现消息,请重试它没有显示当我尝试将数据保存在单个 table 中时,如附图所示的字段下的模型验证错误消息
请告诉我我的视图或控制器文件中的问题是什么,以便如果两个模型中的任何一个有验证错误而不是在相关字段下显示错误消息
抱歉我的英语不好
谢谢
为您的表格试试这个。您不需要提供顶级模型的名称。
echo $this->Form->input('name');
echo $this->Form->input('user.email');
echo $this->Form->input('user.username');
echo $this->Form->input('employee_level');
并且在您的控制器中,您从不使用 $user,因此没有必要创建它,并且由于您正在使用请求数据修补员工实体,因此您不需要以相同的方式对其进行初始化。
$employee = $this->Employees->newEntity();
if ($this->request->is('post')) {
$employee = $this->Employees->patchEntity($employee, $this->request->data, [
'associated' => ['Users']
]);
...
我有两个 tables 员工和用户员工有字段 user_id 他们之间的关系我们用户有一个员工和员工属于用户,我的视图文件中有以下代码
<?php
echo $this->Form->input('employee.name');
echo $this->Form->input('user.email');
echo $this->Form->input('user.username');
echo $this->Form->input('employee.employee_level');
?>
我的 EmployeeController 代码是
<?php
$employee = $this->Employees->newEntity($this->request->data);
$user = $this->Employees->Users->newEntity($this->request->data);
if ($this->request->is('post')) {
$employee = $this->Employees->patchEntity($employee, $this->request->data, [
'associated' => ['Users']
]);
if($this->Employees->save($employee)) {
$this->Flash->success(__('The employee has been saved.'));
} else {
$this->Flash->error(__('The employee could not be saved. Please, try again.'));
}
}
?>
如果一切顺利和完美,它正在保存数据,但如果存在一些验证错误,例如用户名已经存在或电子邮件已经存在,而不是简单地显示无法保存员工的闪现消息,请重试它没有显示当我尝试将数据保存在单个 table 中时,如附图所示的字段下的模型验证错误消息
请告诉我我的视图或控制器文件中的问题是什么,以便如果两个模型中的任何一个有验证错误而不是在相关字段下显示错误消息
抱歉我的英语不好 谢谢
为您的表格试试这个。您不需要提供顶级模型的名称。
echo $this->Form->input('name');
echo $this->Form->input('user.email');
echo $this->Form->input('user.username');
echo $this->Form->input('employee_level');
并且在您的控制器中,您从不使用 $user,因此没有必要创建它,并且由于您正在使用请求数据修补员工实体,因此您不需要以相同的方式对其进行初始化。
$employee = $this->Employees->newEntity();
if ($this->request->is('post')) {
$employee = $this->Employees->patchEntity($employee, $this->request->data, [
'associated' => ['Users']
]);
...