How to Get Last Content Moderation State in Drupal 8+

0
2530
How to Get Last Content Moderation State in Drupal 8+
How to Get Last Content Moderation State in Drupal 8+

If you’re using Drupal 8 or above for your website’s content moderation, you may need to retrieve the last moderation state of a piece of content programmatically. Whether you want to display the last state in a view or perform some other custom functionality based on the last moderation state, Drupal provides some simple code snippets and techniques to achieve this. In this blog post, we’ll explore how to get the last content moderation state in Drupal 8+.

Content moderation in Drupal allows you to create custom workflows for content creation and publication. It provides a way to manage the lifecycle of content from creation to publication, including different moderation states such as draft, published, and archived. Each moderation state is represented by a moderation state entity, which stores information about the state, the entity being moderated, the user who moderated the content, and the timestamp of the moderation event.

To get the last content moderation state in Drupal, you can try below code:

function getLastContentModerationState($nodeId)
{
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nodeId);
    if (!$node) return null;

    $revisionIds = \Drupal::entityTypeManager()->getStorage('node')->revisionIds($node);
    if (count($revisionIds) > 0) {
        $lastRevisionId = end($revisionIds);
        $lastRevisionNode = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($lastRevisionId);
        return $lastRevisionNode->get('moderation_state')->getString();
    }

    return null;
}

In short, we need to find node last revision first then we can access the moderation state.

Once the Content Moderation module is enabled, you can get moderation state by calling $node->get('moderation_state').

One more thing in the above code, the function Node::revisionIds($node return a list of revision IDs sorted in ascending order, we don’t have to sort, the last one will be the last revision ID of the node.

That’s it!