Announcement

Collapse
No announcement yet.

Configuring the After Relate Hook to Execute Only for Specific Relationships

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Configuring the After Relate Hook to Execute Only for Specific Relationships

    In the after Relate Hook code, I want to prevent it from executing for all relationships. How can I configure the code so that it only runs for the specific relationship linked to myEntity?help please

  • #2
    I think I figured it out
    PHP Code:
    <?php

    namespace Espo\Custom\Hooks\YourEntity;

    use 
    Espo\Core\Hooks\Base;

    class 
    AfterRelate extends Base
    {
        public function 
    afterRelate($entity, array $options, array $params)
        {
            
    // Define the target relationship and entity type
            
    $targetRelationName 'myEntityRelationshipName'// relationship name
            
    $targetEntityType 'MyEntity'// the related entity type

            // Check if this is the specific relationship
            
    if ($params['relationName'] === $targetRelationName && $params['relatedEntityType'] === $targetEntityType) {
                
    // Custom logic for this specific relationship
              
                
                // Example: Update a field or perform an action
                // $entity->set('fieldName', 'newValue');
                // $this->getEntityManager()->saveEntity($entity); // Save if changes are made
          
            
    }
        }
    }

    Comment


    • rabii
      rabii commented
      Editing a comment
      don't extend base hook instead implement Interface.
      Last edited by rabii; 10-29-2024, 11:45 AM.

  • #3
    Something like below

    PHP Code:
    <?php
    namespace Espo\Custom\Hooks\YourEntity;

    use 
    Espo\Core\Hook\Hook\AfterRelate;
    use 
    Espo\ORM\Entity;
    use 
    Espo\ORM\EntityManager;
    use 
    Espo\ORM\Repository\Option\RelateOptions;


    /**
     * @implements AfterRelate<YourEntity>
     */
    class YourHook implements AfterRelate
    {
        public function 
    __construct(private EntityManager $entityManager){}

        public function 
    afterRelate(
            
    Entity $entity,
            
    string $relationName,
            
    Entity $relatedEntity,
            array 
    $columnData,
            
    RelateOptions $options
        
    ): void {

            if (
    $options->get(SaveOption::SILENT)) {
                return;
            }

            
    $relationName $relationName ?? null;
            
    $relatedEntity $relatedEntity ?? null;

            if (
    $relationName === 'somRelationsShipLinkHere' && $relatedEntity) {
                
    // Your code here
            
    }
        }
    }
    Rabii
    Web Dev

    Comment

    Working...
    X