Finalmente consegui! mas tem um detalhe... como faço pra receber varios telefones?
View:
<?= $this->Form->input('telefone', ['class'=>'form-control', 'label' => false) ?>
<?= $this->Form->input('telefone', ['class'=>'form-control', 'label' => false) ?>
<?= $this->Form->input('telefone', ['class'=>'form-control', 'label' => false) ?>
ResponsaveisTable:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class ResponsaveisTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->hasMany('Telefones',[
'foreignKey'=>'id_responsavel'
]);
}
}
TelefonesTable:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class TelefonesTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->belongsTo('Responsaveis');
}
}
ResponsaveisController:
<?php
namespace App\Controller;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
class ResponsaveisController extends AppController {
public function index(){
$responsaveisTable = TableRegistry::get('Responsaveis');
$responsavel = $responsaveisTable->newEntity();
$this->set('responsavel',$responsavel);
}
public function cadastrarResponsavel(){
$dados = $this->request->data();
$dados['id_user'] = $this->Auth->user('id_user');
//print_r($dados);
$responsaveisTable = TableRegistry::get('Responsaveis');
$responsavel = $responsaveisTable->newEntity($dados);
//print_r($telefones);
$telefone= $responsaveisTable->Telefones->newEntity();
$telefone->telefone = $dados['telefone'];
$responsavel->telefones = [$telefone];
if($responsaveisTable->save($responsavel)){
$msg = 'Responsável cadastrado com sucesso!';
$this->Flash->set($msg,['element'=>'success']);
}
else{
$msg = 'Erro ao cadastrar responsável!';
$this->Flash->set($msg,['element'=>'error']);
}
$this->redirect('/responsaveis');
}
}