Search code examples
validationcakephpcakephp-3.0cakephp-model

cakephp 3.x model validation not showing when Saving data into 2 tables


I have two tables employees and user employees has field user_id relation between them us user hasOne employee and employee belongs to user, i have following code in my view file

<?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');
?>

my EmployeeController code is

<?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.'));
            }
        }
?>

Its saving the data if all thing going good and perfect but if there are some validation errors like username already exist or email already exist than its simple show the flash message that employee could not be saved please try again its not showing the model validation error message under the fields as shown in the attached image when i try to save data in single table enter image description here

Please tell me what is the problem in my view or controller file so that if any of two model has validation errors than its show error message under the related field

Sorry for my bad english Thanks


Solution

  • Try this for your form. You shouldn't need to provide the name of the top-level model.

    echo $this->Form->input('name');
    echo $this->Form->input('user.email');
    echo $this->Form->input('user.username');
    echo $this->Form->input('employee_level');
    

    And in your controller, you never use $user, so no point in creating it, and since you're patching the employee entity with the request data, you don't need to initialize it the same way.

    $employee = $this->Employees->newEntity();
    if ($this->request->is('post')) {
        $employee = $this->Employees->patchEntity($employee, $this->request->data, [
            'associated' => ['Users']
        ]);
    ...