I have two controllers “Retreats” and “Activities” and both have many “Attendees”.
$this->hasMany('Attendees')
->setClassName('Attendees')
->setForeignKey('foreign_id')
->setConditions(array('Attendees.class' => 'Activity'))
->setDependent(true);
I am using a class and a foreign_id in my Attendees table to link them.
But adding a new attendee, I would like to retrieve information either from the related Retreat or Activity.
So in my add() function (AttendeesController) I am using an if statement to check the class. It works but I think it’s not the right way to proceed… There should be an easier way to achieve the same result I guess.
public function add($class, $foreignId)
{
if($class == "retreat")
{
$this->loadModel('Retreats');
$activity = $this->Retreats->find('all', ['conditions' => ['Retreats.id '=> $foreignId], 'contain' => ['Venues', 'Contacts']])->first();
}
elseif($class == "activity")
{
$this->loadModel('Activities');
$activity = $this->Activities->find('all', ['conditions' => ['Activities.id '=> $foreignId], 'contain' => ['Venues', 'Contacts']])->first();
}
$attendee = $this->Attendees->newEmptyEntity();
if ($this->request->is('post'))
{
$attendee = $this->Attendees->patchEntity($attendee, $this->request->getData() + ['class' => $class, 'foreign_id' => $foreignId]);
if ($this->Attendees->save($attendee))
{
$this->Flash->success(__('Merci. Votre inscription a bien été prise en compte.'));
return $this->redirect(['controller' => 'retreats', 'action' => 'view', $foreignId]);
}
$this->Flash->error(__('Un problème est survenu. Veuillez réessayer.'));
}
$this->set(compact('attendee', 'activity'));
}
Thanks for your help.