Announcement

Collapse
No announcement yet.

Workflow Formula - Check If Parent isNew

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

  • Workflow Formula - Check If Parent isNew

    I'm trying to put together a Workflow so that an email can be sent to Team members when a Ticket receives an email reply from a user.

    I can't seem to figure out how to create a formula which checks whether the Parent Ticket of the Email isNew?

    Can anyone advise, please?

  • #2
    Hi.
    Maybe here you will find some tips https://forum.espocrm.com/forum/gene...between-emails.

    Comment


    • #3
      You can use a hook instead of workflow, here's an example:

      I have a Tenancy entity which is related to a Property entity in a many-to-one relationship, when a Tenancy is created the system changes the Property "status" from "Vacant" to "Occupied".

      file: custom/Espo/Custom/Hooks/Tenancy/TenancyHooks.php
      Code:
      <?php
      namespace Espo\Custom\Hooks\Tenancy;
      use Espo\ORM\Entity;
      
      class TenancyHooks extends \Espo\Core\Hooks\Base
      {
      
          public function beforeSave(Entity $entity, array $options=array())
          {
                  // if it's a new tenancy, change the status of the property to 'Occupied'
                  if ($entity->isNew()) {  
                      $entityManager = $this->getEntityManager();
                      $propertyId = $entity->get('propertyId');
                      $propertyObject = $entityManager->getRepository('Property')->where(['id'=>$propertyId])->findOne();
                      $propertyObject->set('status','Occupied');                
                  }        
          }
      
      }
      Note about relationships: In a one-to-many relationship, the "child" table contains a field {{parentname}}_id (eg: the table tenancies has a "property_id" field) whereas in a parent-child relationship, the child table contains two fields: parent_type and parent_id, the first value is the parent entity name (eg: "Property") and the second value is the actual property.id value.

      Thus, in my example above, the proper code for a parent-child relationship, to modify a parent record based on a child's status would be:
      Code:
                  if ($entity->isNew()) {  
                      $entityManager = $this->getEntityManager();
                      $parentId = $entity->get('parentId');
                      $parentType = $entity->get('parentType');
                      $propertyObject = $entityManager->getRepository($parentType)->where(['id'=>$parentId])->findOne();
                      $propertyObject->set('status','Occupied');                
                  }
      Hooks are a great tool to perform a lot of tasks using plain vanilla PHP and the ORM.
      https://www.espocrm.com/documentatio...lopment/hooks/
      Last edited by telecastg; 06-20-2019, 06:13 PM.

      Comment


      • #4
        Hooks - of course. For some reason I always forget about hooks!

        Thank you for the example.

        Are you aware if its possible to trigger a Workflow (or send an email) from a Hook?

        Comment


        • #5
          You are welcome, sorry, I am not familiar with Workflows or any other extensions, I only work with the basic Espo system for now in order to better understand it and be able to customize as needed.

          It is perfectly possible to send an email through a hook, see the following code which will send an email to a group of users when a service request is received.

          file: custom/Espo/Custom/Hooks/ServiceTicket/ServiceTicketHooks.php
          Code:
          <?php 
          
          namespace Espo\Custom\Hooks\ServiceTicket;
          use Espo\ORM\Entity;
          
          class ServiceTicketHooks extends \Espo\Core\Hooks\Base
          { 
              public function beforeSave(Entity $entity, array $options=array())
          
              {
                  $entityManager = $this->getEntityManager(); 
                  // get the ticket submitter record
                  $authorObject = $this->getUser();
                  // if the service ticket is new:        
                  if ($entity->isNew()) {  
                      // prepare the list of users to be notified by email about the insert event of the service ticket 
                      $distributionList=[];
                      // get the email of users belonging to target roles
                      $roleNames = ["Property Manager","Maintenance Coordinator","Manager Assistant"];
                      foreach($roleNames as $targetRole) {
                          $roleObject = $entityManager->getRepository("Role")->where(['name'=>$targetRole])->findOne();
                          if($roleObject) {
                              $roleUserList = $entityManager->getRepository('Role')->findRelated($roleObject, 'users', array('whereClause' => array('isActive' => true)));
                              foreach ($roleUserList as $user) {
                                  if ($user->id === $this->getUser()->id) continue; // skip the user, if internal, actually making the update - in case the ticket was created manually by a phone request
                                  if (in_array($user->get('emailAddress'), $distributionList)) continue; // avoid duplicating email addresses  
                                  // append the user email to the distribution list
                                  $distributionList[] = $user->get('emailAddress');
                              }                      
                          }                
                      }            
                      // add the ticket creator if not already included
                      if (!in_array($authorObject->get('emailAddress'), $distributionList)){
                          $distributionList[] = $authorObject->get('emailAddress');
                      }   
                      // initialize a mail sender service
                      $mailSender = $this->getContainer()->get('mailSender');           
                      // create an email entity and load the main properties
                      $email = $this->getEntityManager()->getEntity('Email');
                      if(isset($_SERVER['HTTPS'])){
                          $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
                      } else {
                          $protocol = 'http';
                      }        
                      $baseUrl = $protocol . "://" . $_SERVER['HTTP_HOST'].'/{{your folder where the espo application is held}}/#ServiceTicket/view/'.$entity->get('id');        
                      $subject = 'Maintenance request created";            
                      $body = 'Request details:<br/>'.$entity->get('description');            
                      $body.= '<br/><br/>Please click below to follow the ticket progress<br/><br/>'.$baseUrl.'<br/><br/>Maintenance Team';
                      // iterate the list of target users to be notified
                      foreach($distributionList as $emailAddress) {
                          // load the email object
                          $email->set(array(
                              'subject' => $subject,
                              'body' => $body,
                              'isHtml' => true,
                              'from' => '{{your from email address}}',
                              'to' => $emailAddress,
                              'isSystem' => true
                          ));
                          // send the email
                             $mailSender->send($email);
                      }        
                  } 
              }
          }

          Comment


          • #6
            As well as the custom Hook implementation, I've also added a custom "Formula" function which returns a boolean value depending on whether the Entities Parent (if it has one) isNew.

            This may actually work better for me rather than a Hook but thank you again for your input - this will be useful for other aspects of the in-house systems I am developing.

            EspoCRM is just brilliant!

            Comment

            Working...
            X