Save entities related to cakephp-3

Asked

Viewed 109 times

-1

I don’t understand why related entities aren’t working with cakephp, for example: I have a company entity, and this company has a user. In my view, the company values correctly put [$company->cnpj] and the values for user, put through the relationship [$company->user->name], however, when saving the data, are not persisted. Follow my controller.

public function add()
{
    $empresa = $this->Empresas->newEntity();
    $tableUser = TableRegistry::get("Users");
    $user = $tableUser->newEntity();
    $empresa->user = $user;
    if ($this->request->is('post')) {
        $empresa = $this->Empresas->patchEntity($empresa, $this->request->data, ['associated' => ['Users.User']]);
        if ($this->Empresas->save($empresa,['associated' => ['User']])) {
            $this->Flash->success(__('Sua empresa foi cadastrada com sucesso!'));
            return $this->redirect(['controller' => 'Public', 'action' => 'boasvindas']);
        } else {
            $this->Flash->error(__("Ohh não! Houve um problema, por favor comunique-nos o quanto antes."));
        }
    }
    $users = $this->Empresas->Users->find('list', ['limit' => 200]);
    $this->set(compact('empresa', 'users'));
    $this->set('_serialize', ['empresa']);
}

I don’t know what $this->Companies->save($company,['Associated' => ['User']]) is wrong. I would like a help.

1 answer

1

The ['associated' => ['User']] needs to be thorough.

Try it like this:

$empresa = $this->Empresas->patchEntity($empresa, $this->request->data, ['associated' => ['user']]);

Remember that in the form also need to be minuscule the name of the associated fields:

echo $this->Form->input('user.0.id');
echo $this->Form->input('user.0.name');
echo $this->Form->input('user.1.id');
echo $this->Form->input('user.1.name');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.