Announcement

Collapse
No announcement yet.

Help for validate field value in sub-entity

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

  • Help for validate field value in sub-entity

    Hello,

    I have 3 entities:
    "A" related one-to-many with "B" which is related many-to-one with "C".

    I create one record of "A" then one or more of "B" with the module CRMPlus (Inline Link Multiple) of Eblasoft and from "B" I select one record of "C" as field.

    I can update field "Tot", which is stored in entity "C", when I insert a "value" in "B" through a rule in workflow (if a field of "A" is "Tipo" then Tot = Tot - value) and I developed a Hook Before Save for entity "B" so if the value set in entity "B" is higher then "Tot" the system generates an error that stops saving entity "B".

    The problem is that Espo saves entity "A" anyway and I would like to prevent saving of both entities if values in entity "B" are invalid.

    My first purpose was to validate the field "value" with a custom view but I'm not very good in javascript and also I don't know how to refer to related entity's field "Tot".

    The following is the code of the Hook:

    Code:
    <?php
    namespace Espo\Custom\Hooks\B;
    
    use Espo\ORM\Entity;
    use Espo\Core\ORM\EntityManager;
    use Espo\Core\Exceptions\Error;
    use Espo\Core\Exceptions\Conflict;
    
    class MyHook extends \Espo\Core\Hooks\Base
    {
    public function beforeSave(Entity $entity)
    {
    $entityManager = $this->getEntityManager();
    $value = $entity->get('valueB');
    $idC = $entity->get('idC');
    $idA = $entity->get('idA');
    
    $EntityC = $entityManager
    ->getRepository('C')
    ->where([
    'id' => $idC,
    ])
    ->findOne();
    
    $Tot = $EntityC->get('Tot');
    $NameC = $EntityC->get('name');
    
    $EntityA = $entityManager
    ->getRepository('A')
    ->where([
    'id' => $idA,
    ])
    ->findOne();
    
    $Type = $EntityA->get('type');
    
    
    if (($Type=="Tipo") && ($Tot < $value)) {
    throw new Conflict('Error with ['.$NameC.']. Edit: '.$value);
    }
    
    }
    }
    I hope someone can help me.
    Thank you
Working...
X