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?
1 Answer
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;
}
}
-
if ($workflowTransition) {
this will always be true no matter what, because it's set to a string on the line above.– BeebeeMay 11, 2018 at 15:41 -
1Yes, you will need to compare states and provide your logic as needed. Look at the updated example. May 11, 2018 at 15:53
-
1I 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, 2018 at 16:41
-
-