diff --git a/application/Espo/Modules/Crm/Entities/Contact.php b/application/Espo/Modules/Crm/Entities/Contact.php index 936d1e8577..df7e0d3899 100644 --- a/application/Espo/Modules/Crm/Entities/Contact.php +++ b/application/Espo/Modules/Crm/Entities/Contact.php @@ -44,6 +44,8 @@ class Contact extends Person public const string ATTR_ACCOUNT_ID = 'accountId'; /** @since v9.3.0. */ public const string FIELD_ACCOUNTS = 'accounts'; + /** @since v9.3.0. */ + public const string FIELD_ACCOUNT = 'account'; /** @since v9.3.0. */ public const string RELATIONSHIP_ACCOUNT_CONTACT = 'AccountContact'; diff --git a/application/Espo/Modules/Crm/Hooks/Contact/Accounts.php b/application/Espo/Modules/Crm/Hooks/Contact/Accounts.php index 2006edd8f2..23d3df1a0c 100644 --- a/application/Espo/Modules/Crm/Hooks/Contact/Accounts.php +++ b/application/Espo/Modules/Crm/Hooks/Contact/Accounts.php @@ -31,19 +31,22 @@ namespace Espo\Modules\Crm\Hooks\Contact; use Espo\Core\Field\Link; use Espo\Core\Field\LinkMultipleItem; +use Espo\Core\Hook\Hook\AfterRelate; use Espo\Core\Hook\Hook\AfterSave; use Espo\Core\Hook\Hook\BeforeSave; use Espo\Modules\Crm\Entities\Contact; use Espo\ORM\Entity; use Espo\ORM\EntityManager; use Espo\ORM\Name\Attribute; +use Espo\ORM\Repository\Option\RelateOptions; use Espo\ORM\Repository\Option\SaveOptions; /** * @implements BeforeSave * @implements AfterSave + * @implements AfterRelate */ -class Accounts implements BeforeSave, AfterSave +class Accounts implements BeforeSave, AfterSave, AfterRelate { private const string COLUMN_ROLE = Contact::COLUMN_ACCOUNTS_ROLE; private const string ATTR_TITLE = 'title'; @@ -54,7 +57,6 @@ class Accounts implements BeforeSave, AfterSave { $this->setPrimary($entity); $this->restoreAccounts($entity); - } public function afterSave(Entity $entity, SaveOptions $options): void @@ -146,4 +148,29 @@ class Accounts implements BeforeSave, AfterSave $entity->setAccounts($accounts); } + + public function afterRelate( + Entity $entity, + string $relationName, + Entity $relatedEntity, + array $columnData, + RelateOptions $options, + ): void { + + if ($relationName !== Contact::FIELD_ACCOUNTS) { + return; + } + + if ($entity->getAccount()) { + return; + } + + $relation = $this->entityManager->getRelation($entity, Contact::FIELD_ACCOUNT); + + if ($relation->findOne()) { + return; + } + + $relation->relate($relatedEntity); + } }