PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 16, 2022

[FIXED] association data is not saved in cakephp 3.6

 January 16, 2022     associations, cakephp, cakephp-3.0, php     No comments   

Issue

I want to save data in multiple tables using association in cakephp 3.6. I have two tables departments and users. Relationship is

  • Departments hasMany users
  • Users belongTo Departments

here is my code

DepartmentsController

<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
class DepartmentsController extends AppController
{
    public function register()
    {
        $this->loadModel('Departments');
        $department = $this->Departments->newEntity();
        if ($this->request->is('post')) {
            $department = $this->Departments->patchEntity($department, $this->request->data, [
                'associated' => [
                    'Users'
                ]
            ]);
            if ($this->Departments->save($department)){
                $resultJ = json_encode(['status' => true, 'result' => 'You are registered and can login']);
            } 
            else {
                $resultJ = json_encode(['status' => false, 'result' => 'Something went wrong! Please try again']);
            }
            $this->response->type('json');
            $this->response->body($resultJ);
            return $this->response;

        }
        $this->set(compact('department', 'user'));
        $this->set('_serialize', ['department']);
        $this->viewBuilder()->setLayout('login');
    }
}

register.ctp

<?php
$this->Form->setTemplates([
    'inputContainer' => '{{content}}'
]);
echo $this->Form->create($department, ['class' => 'registration-form']);
?>
    <div class="alert alert-danger display-hide">
        <button class="close" data-close="alert"></button>
        <span><?= __('Please fill the required fields.') ?> </span>
    </div>
    <?= $this->Flash->render() ?>
    <div class="row">
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('users.0.first_name', [
                'label' => false, 
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('First Name'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('users.0.last_name', [
                'label' => false, 
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('Last Name'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('users.0.email', [
                'label' => false, 
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('E-mail'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('users.0.password', [
                'label' => false, 
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('Password'),
                'autocomplete' => 'off',
                'type' => 'password'
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('name', [
                'label' => false,
                'id' => 'domain_name',
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('Department Name'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('domain', [
                'label' => false, 
                'id' => 'domain_slug',
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('Domain Name'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-4">
            <div class="forgot-password-link">
                <?= $this->Html->link(__('Already have an account?'), '/', ['class' => 'forget-password', 'id' => 'forget-password']) ?>
            </div>
        </div>
        <div class="col-sm-8 text-right">
            <?= $this->Form->button(__('Sign Up'), ['class' => 'btn blue']) ?>
        </div>
    </div>
<?= $this->Form->end() ?>

DepartmentsTable.php

<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class DepartmentsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('departments');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');
        $this->hasMany('Users', [
            'foreignKey' => 'department_id'
        ]);
    }

    public function validationDefault(Validator $validator)
    {
        $validator
            ->uuid('id')
            ->allowEmpty('id', 'create');

        $validator
            ->scalar('org_no')
            ->maxLength('org_no', 35)
            ->allowEmpty('org_no');

        $validator
            ->boolean('active')
            ->requirePresence('active', 'create')
            ->notEmpty('active');

        return $validator;
    }

    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['department_id'], 'Users'));
        return $rules;
    }
}

UsersTable.php

<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('users');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Departments', [
            'foreignKey' => 'department_id',
        ]);
    }
   public function validationDefault(Validator $validator)
    {
        $validator
            ->uuid('id')
            ->allowEmpty('id', 'create');
        return $validator;
    }


    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->isUnique(['email']));
        return $rules;
    }
}

Entity Model

Department.php

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

class Department extends Entity
{
    protected $_accessible = [
        'name' => true,
        'org_no' => true,
        'domain' => true,
        'active' => true,
        'created' => true,
        'modified' => true,
        'user' => true
    ];
}

The problem is data only save into departments table not in users table. How can I save data in users table using cakephp 3.6 associations?


Solution

In Department entity model you use "user" for accessible data. For the hasMany relationship, it must be changed in "users".Try with "users" => true

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

class Department extends Entity
{
    protected $_accessible = [
    'name' => true,
    'org_no' => true,
    'domain' => true,
    'active' => true,
    'created' => true,
    'modified' => true,
    'users' => true
    ];
}


Answered By - abdul karim
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing