0

I have two database table 1) users 2) profiles

profiles has a field called bank_ac

I am trying to save it from user model.

I have created form input like

<?= $this->Form->create($user) ?>
   <?= $this->Form->control('profile.bank_ac'); ?>
<?= $this->Form->end() ?>

User model I have added associative like

$this->hasOne('Profiles');

After debug getting data like

[
    'name' => 'Jone',
    'email' => 'abcd@yahoo.com',
    'profile' => [
        'bank_ac' => '1212212'
    ]
]

after debug patch entity

object(App\Model\Entity\User) {

    'name' => 'Jone',
    'email' => 'abcd@yahoo.com',
    '[new]' => true,
    '[accessible]' => [
        'name' => true,
        'email' => true,
        'created' => true,
        'modified' => true
    ],
    '[dirty]' => [
        'name' => true,
        'email' => true,
        'profile' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[hasErrors]' => false,
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Users'

}

In UsersController/add I have applied code like

public function add(){

        $user = $this->Users->newEmptyEntity();

        $user = $this->Users->patchEntity($user, $this->request->getData());

        $this->Users->save($user, ['associated' => ['Profiles']]);

}

Profile data not saving , also not getting any error. How can I save this associative data ?

Niloy Rony
  • 602
  • 1
  • 8
  • 23

1 Answers1

1

Looking at your entity debug result, the profile field is missing from the accessibility config, hence disallowing its use in mass assignment (patching).

Add it to your User::$_accessible property, and it should work:

protected $_accessible = [
    // ...
    'profile' => true,
];

See also

ndm
  • 59,784
  • 9
  • 71
  • 110
  • 1
    @NiloyRony Depends on how the entity is built (manually, with user data, etc), and generally how much you can trust the process that creates the entity. Technically if you consider the entity creation process to be safe (ie users aren't able to assign data that you don't want them to be able to save in a specific action), then you wouldn't need to restrict the saving process. – ndm Feb 18 '20 at 16:37
  • 1
    @NiloyRony However first level associations can be patched and saved by default, so unwanted data slipping in can happen easily if something in your entity creation process changes, so that you might want to use the `associated` option for both, patching and saving, that way even when a supposedly safe entity turns out to be not trustworthy, saving would still be restricted. – ndm Feb 18 '20 at 16:37