Save cakephp associations 3

Asked

Viewed 296 times

0

I am trying to save associated data in Cakephp 3, in the database I have two tables tabela entidades(id, nome_principal) and enderecos(id, entidade_id, cidade)

In EntidadesTable i performed the association:

$this->hasMany('Enderecos', array(
    'className' => 'Enderecos',
    'foreignkey' => 'entidade_id',
    'joinType' => 'INNER'
));

In the controller Entidades I save with the following data:

$entidade = $this->Entidades->newEntity();

if ($this->request->is('post')){
    $entidade = $this->Entidades->patchEntity($entidade, $this->request->getData());
    if ($this->Entidades->save($entidade)) {
        $this->Flash->success(__('Entidade cadastrada com sucesso!'));
        return $this->redirect(['action' => 'consultar']);
    } else {
        $this->Flash->error(__('Ops, algo deu errado, verifique se os campos foram preenchidos corretamente!'));
    }
}

$this->set(compact('entidade'));

And in the view, my form is like this:

<p><strong>Nome<strong><p>  
<p><input type="text" id="nome_principal" name="nome_principal" placeholder="Nome" class="form-control input-md"></p>
<p><strong>Cidade<strong><p>  
<p><input type="text" id="cidade" name="cidade" placeholder="Cidade" class="form-control input-md"></p>

The entity data normally saved in the database, but the entidade_id and cidade table enderecos can’t save me, someone can help me?

  • Please be sure to mention the exact version of Cakephp (last line vendor/cakephp/cakephp/VERSION.txt or lib/Cake/VERSION.txt)

1 answer

1


I edited the patchEntity by passing the key associated that informs the associated model that will be saved:

$entidade = $this->Entidades->patchEntity($entidade, $this->request->getData(), ['associated' => ['Enderecos']]);

Here I created your inputs using Formhelper following the associated data pattern:

echo $this->Form->control('nome_principal', ['id' => 'nome_principal', 'class' => 'form-control input-md', 'placeholder' => 'Nome', 'label' => 'Nome']);
// Enderecos controls (hasMany)
echo $this->Form->control('enderecos.0.cidade', ['id' => 'cidade', 'class' => 'form-control input-md', 'placeholder' => 'Cidade', 'label' => 'Cidade']);

Behold Saving Hasmany Associations and Converting Request Data into Entities for more details.

  • Close the balloon Rayann, thanks for your help!

Browser other questions tagged

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