CakePHP - Saving associations

0

I'm trying to save the information in a table, but first I need to get the id's from the records of related tables ...

I have the Coordinator table, which has reference to Contact, to save Coordinator, I first need to save Contact and get the id ...

CoordinatorsTable:

$this->belongsTo('Contacts', [
    'foreignKey' => 'contact_id',
    'joinType' => 'INNER'
]);

ContactsTable:

$this->hasMany('Coordinators', [
            'foreignKey' => 'contact_id'
        ]);

View:

<?= $this->Form->create($coordinator) ?>
<fieldset>
    <legend><?= __('Cadastrar novo cordenador') ?></legend>
    <?php
        echo $this->Form->control('name', ['label' => 'Nome', 'class' => 'form-control']);
        echo $this->Form->control('registry', ['label' => 'R.A.', 'class' => 'form-control']);
        echo $this->Form->control('contact.tel_phone', ['label' => 'Telefone', 'class' => 'form-control']);
        echo $this->Form->control('contact.cel_phone', ['label' => 'Celular', 'class' => 'form-control']);
        echo $this->Form->control('contact.email', ['label' => 'E-mail', 'class' => 'form-control']);   
    ?>
</fieldset>
<?= $this->Form->button(__('Cadastrar curso', ['class' => 'btn btn-success waves-effect'])) ?>
<?= $this->Form->end() ?>

Controller:

public function add()
{

    $coordinator = $this->Coordinators->newEntity();
    $contact = $this->Coordinators->Contacts->newEntity();
    if ($this->request->is('post')) {
        $coordinator = $this->Coordinators->patchEntity($coordinator, $this->request->getData());
        $contact = $this->Coordinators->Contacts->patchEntity($contact, $this->request->getData('contact'));
        $coordinator->contacts = $contact;
        if ($this->Coordinators->save($coordinator)) {
            $this->Flash->success(__('Cadastro efetuado com sucesso!'));

            return $this->redirect(['action' => 'index']);
        }
        else
        {
            $this->Flash->error(__('Erro ao efetuar cadastro...'));
        }
    }   
    $this->set(compact('coordinator', 'courses', 'addresses', 'contacts', 'authentications', 'institutions'));
    $this->set('_serialize', ['coordinator']);
}

Can anyone help me?

    
asked by anonymous 20.03.2018 / 05:03

0 answers