2

I want to execute PHP script in my custom module, when transition occurs. Workflow is assigned to custom entity. I'm using Drupal's core modules Workflow and Content moderation. How can I do that programmatically?

2

You can use hook_ENTITY_TYPE_update to achieve this.

/**
 * Implements hook_ENTITY_TYPE_update().
*/

function mymodule_node_update(Drupal\Core\Entity\EntityInterface $entity) {

    //Get the current Moderation state;
    if (isset($entity->moderation_state) && isset($entity->moderation_state->getValue()[0]['target_id'])) {
        $currentState = $entity->hasField('moderation_state') ? $entity->moderation_state->getValue()[0]['target_id'] : null;
    }
    //Get the original Moderation state;
    if ( isset($entity->original->moderation_state ) && isset($entity->original->moderation_state->getValue()[0]['target_id']) ) {
        $originalState = $entity->original !== NULL ? $entity->original->moderation_state->getValue()[0]['target_id'] : null;
    }

    #Get the Transition;
    $workflowTransition = rtrim($originalState.'-->'.$currentState);

    switch ($workflowTransition) {
       case 'published-->needs_review':
       case 'draft-->needs_review':
       //Do something.
      break;
       case 'draft-->needs_review':
      //Do something else;
      break;
    }
 } 
8
  • if ($workflowTransition) { this will always be true no matter what, because it's set to a string on the line above.
    – Beebee
    May 11 '18 at 15:41
  • 1
    Yes, you will need to compare states and provide your logic as needed. Look at the updated example.
    – Jay Chand
    May 11 '18 at 15:53
  • 1
    I am shocked to learn there are no event emitters for this. But after some searching around I found the request for this: drupal.org/project/drupal/issues/2873287. Hopefully we can use those in the near future :) May 11 '18 at 16:41
  • It seems like workaround, but it works. :)
    – Saulius
    May 14 '18 at 6:48
  • Where does this script live? In the Content Moderation directory?
    – johnny
    Sep 14 '18 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.