Announcement

Collapse
No announcement yet.

afterRemove hook

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

  • afterRemove hook

    I have 3nentities 'A','B','C' A is linked to both of them with one-many (2 links ab, ac), how to set up please a afterRemove hook to delete All the retaled Bs linked to an A after removing a A?
    thank you so much
    is this code correct?
    PHP Code:
    <?php

    namespace Espo\Custom\Hooks\A;

    use 
    Espo\ORM\Entity;

    class 
    AfterRemove extends \Espo\Core\Hooks\Base
    {
    public static 
    $order 10;

    public function 
    afterRemove(Entity $entity)
    {
    $entityManager $this->getEntityManager();

    // Get related 'B' entities
    $relatedBs $entityManager->getRepository('B')->where([
    'aId' => $entity->id
    ])->find();

    // Delete each related 'B' entity
    foreach ($relatedBs as $bEntity) {
    $entityManager->removeEntity($bEntity);
    }
    }
    }
    โ€‹
    Last edited by zerosix; 03-06-2024, 07:10 AM.

  • #2
    Don't extend from Hooks\Base. It's been as deprecated for a reason for long. See the documentation on hooks Use an IDE.

    Removal of entities seems to be correct.

    Comment


    • zerosix
      zerosix commented
      Editing a comment
      thank you yuri for your guidance, i will share the final code on next answer

    • zerosix
      zerosix commented
      Editing a comment
      if i remove extends \Espo\Core\Hooks\Base i got 500 error

  • #3
    Situation: I have 2 entities 'AAA','BBB', AAA is linked to BBB with one-many, i want to setup a afterRemove hook to delete All the retaled BBB linked to an AAA after removing a AAA.

    Solution:

    Step 1: Create a Custom Hook File
    First, create a custom hook file for the AAA entity. This file should be located in your EspoCRM's custom directory to ensure it's not overwritten by updates. The directory structure would look like: custom/Espo/Custom/Hooks/AAA/AfterRemove.php

    โ€‹Step 2: Implement the Hook
    Inside AfterRemove.php, implement the hook as follows:

    PHP Code:
    <?php

    namespace Espo\Custom\Hooks\AAA;

    use 
    Espo\ORM\Entity;

    class 
    AfterRemove extends \Espo\Core\Hooks\Base
    {
        public static 
    $order 10;

        public function 
    afterRemove(Entity $entity)
        {
            
    $entityManager $this->getEntityManager();

          
            
    $relatedBBBs $entityManager->getRepository('BBB')->where([
                
    'aAAId' => $entity->id  // Assuming 'aAAId' is the field on BBB that links to AAA
            
    ])->find();

            
    // Remove each related BBB entity
            
    foreach ($relatedBBBs as $bbbEntity) {
                
    $entityManager->removeEntity($bbbEntity);
            }
        }
    }
    โ€‹
    โ€‹
    Step 3: Clear Cache
    Last edited by zerosix; 03-06-2024, 08:54 AM.

    Comment


    • #4
      For whomever reading it in the future, do not extend \Espo\Core\Hooks\Base.

      Comment


      • zerosix
        zerosix commented
        Editing a comment
        if i remove extends \Espo\Core\Hooks\Base i got 500 error

    • #5
      try this instead, it all in the documentation

      PHP Code:
      <?php

      namespace Espo\Custom\Hooks\AAA;

      use 
      Espo\Core\Hook\Hook\AfterRemove;

      use 
      Espo\ORM\Entity;
      use 
      Espo\ORM\EntityManager;
      use 
      Espo\ORM\Repository\Option\RemoveOptions;

      /**
       * @implements AfterRemove<AAA>
       */
      class RemoveBEntities implements AfterRemove
      {
          public static 
      $order 10;

          public function 
      __construct(private EntityManager $entityManager) {}

          public function 
      afterRemove(Entity $entityRemoveOptions $options): void
          
      {
              
      $relatedBBBs $this->entityManager
                          
      ->getRDBRepository('BBB')
                          ->
      where([
                              
      'aAAId' => $entity->getId()
                          ])
                          ->
      find();
              if (!
      count($relatedBBBs)) {
                  return;
              }

              
      // Remove each related BBB entity
              
      foreach ($relatedBBBs as $bbbEntity) {
                  
      $this->entityManager->removeEntity($bbbEntity);
              }
          }
      }
      โ€‹

      Comment


      • zerosix
        zerosix commented
        Editing a comment
        thank you so much rabii, i tried it it's giving me error 500

      • rabii
        rabii commented
        Editing a comment
        share your code to verify it, also check what error in the log.

      • zerosix
        zerosix commented
        Editing a comment
        thank you rabii, i have just posted the code+error log,

    • #6
      Thank you Rabii, the code is
      PHP Code:
      <?php

      namespace Espo\Custom\Hooks\AAA;

      use 
      Espo\Core\Hook\Hook\AfterRemove;

      use 
      Espo\ORM\Entity;
      use 
      Espo\ORM\EntityManager;
      use 
      Espo\ORM\Repository\Option\RemoveOptions;

      /**
       * @implements AfterRemove<AAA>
       */
      class RemoveBEntities implements AfterRemove
      {
          public static 
      $order 10;

          public function 
      __construct(private EntityManager $entityManager) {}

          public function 
      afterRemove(Entity $entityRemoveOptions $options): void
          
      {
              
      $relatedBBBs $this->entityManager
                          
      ->getRDBRepository('BBB')
                          ->
      where([
                              
      'aAAId' => $entity->getId()
                          ])
                          ->
      find();
              if (!
      count($relatedBBBs)) {
                  return;
              }

              
      // Remove each related BBB entity
              
      foreach ($relatedBBBs as $bbbEntity) {
                  
      $this->entityManager->removeEntity($bbbEntity);
              }
          }
      }
      โ€‹
      and the error is
      PHP Code:
      [2024-03-07 09:51:43ERRORJobTaskFailed to run job '65e98e2f597bbd10d'Errorget_class_methods(): Argument #1 ($object_or_class) must be an object or a valid class name, string given  
      [2024-03-07 09:51:43ERRORJobTaskFailed to run job '65e98e2f58fc36b00'Errorget_class_methods(): Argument #1 ($object_or_class) must be an object or a valid class name, string given  
      [2024-03-07 09:51:43ERRORJobTaskFailed to run job '65e98e2f5a2f5734c'Errorget_class_methods(): Argument #1 ($object_or_class) must be an object or a valid class name, string given  
      [2024-03-07 09:51:47ERRORSlim Application Error TypeTypeError Code0 Messageget_class_methods(): Argument #1 ($object_or_class) must be an object or a valid class name, string given File: /var/www/html/application/Espo/Core/HookManager.php Line: 210 Trace: #0 /var/www/html/application/Espo/Core/HookManager.php(210): get_class_methods('Espo\\Custom\\Hoo...') #1 /var/www/html/application/Espo/Core/HookManager.php(157): Espo\Core\HookManager->readHookData('custom/Espo/Cus...') #2 /var/www/html/application/Espo/Core/HookManager.php(102): Espo\Core\HookManager->loadHooks() #3 /var/www/html/application/Espo/Core/Repositories/Database.php(298): Espo\Core\HookManager->process('AAA', 'beforeSave', Object(Espo\Core\Templates\Entities\Base), Array) #4 /var/www/html/application/Espo/ORM/Repository/RDBRepository.php(139): Espo\Core\Repositories\Database->beforeSave(Object(Espo\Core\Templates\Entities\Base), Array) #5 /var/www/html/application/Espo/Core/Repositories/Database.php(136): Espo\ORM\Repository\RDBRepository->save(Object(Espo\Core\Templates\Entities\Base), Array) #6 /var/www/html/application/Espo/ORM/EntityManager.php(244): Espo\Core\Repositories\Database->save(Object(Espo\Core\Templates\Entities\Base), Array) #7 /var/www/html/application/Espo/Core/Record/Service.php(751): Espo\ORM\EntityManager->saveEntity(Object(Espo\Core\Templates\Entities\Base), Array) #8 /var/www/html/application/Espo/Core/Controllers/RecordBase.php(181): Espo\Core\Record\Service->create(Object(stdClass), Object(Espo\Core\Record\CreateParams)) #9 /var/www/html/application/Espo/Core/Api/ControllerActionProcessor.php(87): Espo\Core\Controllers\RecordBase->postActionCreate(Object(Espo\Core\Api\RequestWrapper), Object(Espo\Core\Api\ResponseWrapper)) #10 /var/www/html/application/Espo/Core/Api/ControllerActionHandler.php(69): Espo\Core\Api\ControllerActionProcessor->process('AAA', 'create', Object(Espo\Core\Api\RequestWrapper), Object(Espo\Core\Api\ResponseWrapper)) #11 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(65): Espo\Core\Api\ControllerActionHandler->handle(Object(Slim\Psr7\Request)) #12 /var/www/html/application/Espo/Core/Api/RouteProcessor.php(222): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request)) #13 /var/www/html/application/Espo/Core/Api/RouteProcessor.php(149): Espo\Core\Api\RouteProcessor->processControllerAction(Object(Espo\Core\Api\ProcessData), Object(Slim\Psr7\Request), Object(Espo\Core\Api\ResponseWrapper)) #14 /var/www/html/application/Espo/Core/Api/RouteProcessor.php(127): Espo\Core\Api\RouteProcessor->processAfterAuth(Object(Espo\Core\Api\ProcessData), Object(Slim\Psr7\Request), Object(Espo\Core\Api\ResponseWrapper)) #15 /var/www/html/application/Espo/Core/Api/RouteProcessor.php(79): Espo\Core\Api\RouteProcessor->processInternal(Object(Espo\Core\Api\ProcessData), Object(Slim\Psr7\Request), Object(Espo\Core\Api\RequestWrapper), Object(Espo\Core\Api\ResponseWrapper)) #16 /var/www/html/application/Espo/Core/Api/Starter.php(109): Espo\Core\Api\RouteProcessor->process(Object(Espo\Core\Api\ProcessData), Object(Slim\Psr7\Request), Object(Slim\Psr7\Response)) #17 /var/www/html/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php(38): Espo\Core\Api\Starter->Espo\Core\Api\{closure}(Object(Slim\Psr7\Request), Object(Slim\Psr7\Response), Array) #18 /var/www/html/vendor/slim/slim/Slim/Routing/Route.php(358): Slim\Handlers\Strategies\RequestResponse->__invoke(Object(Closure), Object(Slim\Psr7\Request), Object(Slim\Psr7\Response), Array) #19 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(65): Slim\Routing\Route->handle(Object(Slim\Psr7\Request)) #20 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(65): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request)) #21 /var/www/html/vendor/slim/slim/Slim/Routing/Route.php(315): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request)) #22 /var/www/html/vendor/slim/slim/Slim/Routing/RouteRunner.php(68): Slim\Routing\Route->run(Object(Slim\Psr7\Request)) #23 /var/www/html/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php(45): Slim\Routing\RouteRunner->handle(Object(Slim\Psr7\Request)) #24 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(121): Slim\Middleware\RoutingMiddleware->process(Object(Slim\Psr7\Request), Object(Slim\Routing\RouteRunner)) #25 /var/www/html/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php(76): Psr\Http\Server\RequestHandlerInterface@anonymous->handle(Object(Slim\Psr7\Request)) #26 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(121): Slim\Middleware\ErrorMiddleware->process(Object(Slim\Psr7\Request), Object(Psr\Http\Server\RequestHandlerInterface@anonymous)) #27 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(65): Psr\Http\Server\RequestHandlerInterface@anonymous->handle(Object(Slim\Psr7\Request)) #28 /var/www/html/vendor/slim/slim/Slim/App.php(199): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request)) #29 /var/www/html/vendor/slim/slim/Slim/App.php(183): Slim\App->handle(Object(Slim\Psr7\Request)) #30 /var/www/html/application/Espo/Core/Api/Starter.php(76): Slim\App->run() #31 /var/www/html/application/Espo/Core/ApplicationRunners/Api.php(45): Espo\Core\Api\Starter->start() #32 /var/www/html/application/Espo/Core/Application/RunnerRunner.php(84): Espo\Core\ApplicationRunners\Api->run() #33 /var/www/html/application/Espo/Core/Application.php(78): Espo\Core\Application\RunnerRunner->run('Espo\\Core\\Appli...', NULL) #34 /var/www/html/public/api/v1/index.php(35): Espo\Core\Application->run('Espo\\Core\\Appli...') #35 {main} Tips: To display error details in HTTP response set "displayErrorDetails" to true in the ErrorHandler constructor.  
      zz0.wvgt98apkdzzโ€‹ 

      Comment


      • #7
        mate, you have to change the names to the correct name of your entities.

        what are the names of the your entities ? you can find the correct name under administration > entity manager > your entity

        Comment


        • zerosix
          zerosix commented
          Editing a comment
          I know chef, the names are AAA and BBB (entities for test)

        • rabii
          rabii commented
          Editing a comment
          It can't be (the name of entities is capitalised e.g Account - Contact etc) so the name can't be AAA and BBB - it should be Aaa and Bbb

      • #8
        the error manfest this properly (Error: get_class_methods(): Argument #1 ($object_or_class) must be an object or a valid class name, string given) retrieving a class AAA doesn't work because there is no class called AAA

        Comment


        • zerosix
          zerosix commented
          Editing a comment
          so Why this code is working:
          <?php

          namespace Espo\Custom\Hooks\AAA;

          use Espo\Core\Hook\Hook\AfterRemove;

          use Espo\ORM\Entity;
          use Espo\ORM\EntityManager;
          use Espo\ORM\Repository\Option\RemoveOptions;

          /**
          * @implements AfterRemove<AAA>
          */
          class RemoveBEntities implements AfterRemove
          {
          public static $order = 10;

          public function __construct(private EntityManager $entityManager) {}

          public function afterRemove(Entity $entity, RemoveOptions $options): void
          {
          $relatedBBBs = $this->entityManager
          ->getRDBRepository('BBB')
          ->where([
          'aAAId' => $entity->getId()
          ])
          ->find();
          if (!count($relatedBBBs)) {
          return;
          }

          // Remove each related BBB entity
          foreach ($relatedBBBs as $bbbEntity) {
          $this->entityManager->removeEntity($bbbEntity);
          }
          }
          }

        • rabii
          rabii commented
          Editing a comment
          it is the same code. not sure what you mean

        • zerosix
          zerosix commented
          Editing a comment
          yes it's working , i am so sorry๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™, i was confused
      Working...
      X