2

I need to filter a node by moderation state. I am using the Drupal 8 content moderation module.

I basically want to get NIDs of all nodes in draft state. Something similar to this.

$nids = \Drupal::entityQuery('node')
      ->condition('moderation_state', 'draft')
      ->execute();
2

You try the code :

$query = \Drupal::database()->select('content_moderation_state_field_data', 'ms');
    $query->join('node_field_revision', 'nf', 'nf.nid=ms.content_entity_id AND nf.vid=ms.content_entity_revision_id AND nf.langcode=ms.langcode');
    $query->fields('ms');
    $query->condition('ms.moderation_state','draft');
    $results = $query->execute()->fetchAllAssoc('content_entity_id');

Because entityQuery not filter content moderation

1
1

Posting a link to the d.o issue queue where as of this week a potential patch to core to allow EntityQuery to recognize Workflow moderation state that @Santiago cited above: https://www.drupal.org/project/drupal/issues/3025164#comment-13221005 Without this patch or a similar core hack, EntityQuery can not query Drupal 8 Workflow moderation state.

1

An additional workaround to this is you can add a tag to the entity query and then alter it in a separate hook_query_TAG_alter hook. It's an extra step but it gets the job done and gives you direct access to the SQL query for you to modify. So you can generate the entity query like you normally would, and any extra SQL that it does not support you can modify as needed.

Entity query:

/** @var \Drupal\node\NodeStorage $storage */
$storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $storage->getQuery()
  ->addTag('archive_press_releases')
  ->currentRevision()
  ->condition('type', ['post_page', 'story_page'], 'IN')
  ->condition('field_date', $formatted, '<=')
  ->sort('field_date');
$result = $query->execute();

hook_query_TAG_alter example:

/**
 * Implements hook_query_TAG_alter().
 */
function bax_archiving_query_archive_press_releases_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->addJoin('LEFT', 'content_moderation_state_field_data', 'md', 'md.content_entity_revision_id = base_table.vid');
  $query->condition('md.moderation_state', 'archived', '<>');
}

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.