0

I have the content type (node), article, page, recipe.

The code below can be used to flag any type of content.

How do you target a specific type of content ?

For example I only want to flag the article and recipe content type.

<?php

/**
 * @file
 * Holds hook implementation for the Admin Task Notify module.
 */

use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\comment\Entity\Comment;

/**
 * Implements hook_node_update().
 */
function admin_task_notify_node_update(Node $node) {

    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $account = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $node, $account);

}
3

If you want your hook code to only run on specific content types, simply add a conditional

function admin_task_notify_node_update(Node $node) {

  if ($node->getType() == 'article' || $node->getType() == 'recipe') { // conditional
    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $account = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $node, $account);
  }

}

I have several types of content to add, is there a shorter way to do it ?

Using in_array()

$allowed_c_types = ['article', 'recipe', 'some_other'];
$c_type = $node->getType();

if (in_array($c_type, $allowed_c_types)) { // conditional

But don't hard code, use $flag->getBundles() to get the list as mentioned by Shawn

$allowed_c_types = $flag->getBundles();
2
  • Awesome it works. I have several types of content to add, is there a shorter way to do it ? for example if $node->getType() == 'article, recipe' – sdfff Sep 18 '20 at 9:47
  • @sdfff see updated answer. – No Sssweat Sep 18 '20 at 15:43
4

You need to configure your moderate_node flag in either the UI or in configuration management.

In the flag module, a flag entity is defined by the entity type (i.e. node) and bundles (e.g. article, page, recipe) that are allowed on it. If no bundles are specified, then all bundles are allowed.

In your example code, $flag->getBundles() method will return the bundles that are allowed (empty means all). Once set, the $flag_service->flag method will kickback exceptions if you try to flag bundles that do not apply to that flag. You'll need to adjust the code accordingly to handle those scenarios.

1
  • thank you for the explanations – sdfff Sep 18 '20 at 9:48

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.