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' => '[email protected]',
    'profile' => [
        'bank_ac' => '1212212'
    ]
]

after debug patch entity

object(App\Model\Entity\User) {

    'name' => 'Jone',
    'email' => '[email protected]',
    '[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 ?

2
  • For further insight, debug your patched $user entity.
    – ndm
    Commented Feb 18, 2020 at 15:41
  • Updated my question, Thank you.
    – Niloy Rony
    Commented Feb 18, 2020 at 15:47

1 Answer 1

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

2
  • 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
    Commented Feb 18, 2020 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
    Commented Feb 18, 2020 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.