Hello everyone,
I need some help with creating a relation in a logic hook.
I have three modules: ‘Projects’, ‘Emails’ and ‘Notes’. My projects has several Emails, so the relation is a (Projects) one-to-many (Emails). My emails contains notes, so I have (Emails) on-to-many (Notes). Now I want my notes to show in my projects, so I created a (Project) many-to-many (Notes) relation and I want to show all notes from by related Emails in a submenu.
It is not possible to do that with a Workflow so I created a logic hook. The code works fine, but when I want to add the notes to project, it only adds one and then the method stops.
My code:
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class GenerateRelations
{
function addNoteRelation($bean, $event, $arguments)
{
LoggerManager::getLogger()->error('addNoteRelation');
// Check if related module is 'Emails'-module
if ($arguments['related_module'] == 'Emails') {
$emailBean = BeanFactory::getBean($arguments['related_module'], $arguments['related_id']);
// Get all the 'Notes' from the 'Emails'
if ($emailBean->load_relationship('notes')) {
$emailNotes = $emailBean->notes->getBeans();
$newNotes = array();
$bean->load_relationship('project_notes_1');
$projectNotes = $bean->project_notes_1->getBeans();
// Check for all notes in the related Email
foreach ($emailNotes as $emailNote) {
LoggerManager::getLogger()->error('email notes: ' . $emailNote->id);
// Check if email-note not already exists in the project-notes
if (!in_array($emailNote, $projectNotes)) {
LoggerManager::getLogger()->error('add new e-mail in list: ' . $emailNote->id);
$newNotes[] = $emailNote;
}
}
// Add all the newNotes to the project
foreach ($newNotes as $newNote) {
LoggerManager::getLogger()->error('$newNote->id' . $newNote->id);
$bean->project_notes_1->add($newNote->id);
}
}
}
}
}
The foreach doesn’t work in combination with the add relation function. It only adds the first note in the list.