Feeds

Author

Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough
Sep 03 2018
Sep 03

For a custom project, we use a taxonomy to tag nodes. Some terms have their own page, while others redirect to a node. The search on the site has one index which contains both nodes and terms, but the terms which are redirecting shouldn't show up when viewing a search results page. While it's possible to use hook_search_api_index_items_alter(), a nicer way to exclude them is by using a processor plugin so you can enable them in the UI per index. The relevant code is underneath. Adjust to your own likings - and maybe inject the service if you want to as well :)

namespace Drupal\project\Plugin\search_api\processor;

use </span>Drupal\search_api\IndexInterface;
use
Drupal\search_api\Processor\ProcessorPluginBase;

/**
 * Excludes entities which have a redirect.
 *
 * @SearchApiProcessor(
 *   id = "entity_redirect",
 *   label = @Translation("Entity redirect"),
 *   description = @Translation("Exclude entities which have a redirect from being indexed."),
 *   stages = {
 *     "alter_items" = 0,
 *   },
 * )
 */
class EntityRedirect extends ProcessorPluginBase {

  </span>/**
   * {@inheritdoc}
   */
 
public static function supportsIndex(IndexInterface $index) {
    foreach (
$index->getDatasources() as $datasource) {
     
$entity_type_id = $datasource->getEntityTypeId();
      if (!
$entity_type_id) {
        continue;
      }
      if (
$entity_type_id === 'node' || $entity_type_id == 'taxonomy_term') {
        return
TRUE;
      }
    }
    return
FALSE;
  }

  </span>/**
   * {@inheritdoc}
   */
 
public function alterIndexedItems(array &$items) {
   
$repository = \Drupal::service('redirect.repository');
   
$pathAliasmanager = \Drupal::service('path.alias_manager');
   
/** @var \Drupal\search_api\Item\ItemInterface $item */
   
foreach ($items as $item_id => $item) {
     
$object = $item->getOriginalObject()->getValue();
      try {
       
$path = $object->toUrl()->toString();
       
$path = $pathAliasmanager->getPathByAlias($path);
       
$path = ltrim($path, '/');
       
$redirect = $repository->findMatchingRedirect($path);
        if (!empty(
$redirect)) {
          unset(
$items[$item_id]);
        }
      }
      catch (
\Exception $ignored) {}
    }
  }

}
?>

Exclude entities which have a redirect from the search api index: https://realize.be/blog/exclude-entities-which-have-redirect-search-api-...

Aug 05 2016
Aug 05

Every Drupal developer knows the following error message (maybe some by heart): The content has been modified by another user, changes cannot be saved. In Drupal 8 the message is even a bit longer: The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved. While this inbuilt mechanism is very useful to preserve data integrity, the only way to get rid of the message is to reload the form and then redo the changes you want to make. This can be (or should I say 'is') very frustrating for users, especially when they have no idea why this is happening. In an environment where multiple users modify the same content, there are solutions like the Content locking module to get overcome this nagging problem. But what if your content changes a lot by backend calls ?

On a big project I'm currently working on, Musescore.com (D6 to D8), members can upload their scores to the website. On save, the file is send to Amazon where it will be processed so you can play and listen to the music in your browser. Depending on the length of a score, the processing might take a couple of minutes before it's available. In the meantime, you can edit the score because the user might want to update the title, body content, or add some new tags. While the edit form is open, the backend might be pinging back to our application notifying the score is now ready for playing and will update field values, thus saving the node. At this very moment, the changed time has been updated to the future, so when the user wants to save new values, Drupal will complain. This is just a simple example, in reality, the backend workers might be pinging a couple of times back on several occasions doing various operations and updating field values. And ironically, the user doesn't even have any permission to update one or more of these properties on the form itself. If you have ever uploaded a video to YouTube, you know that while your video is processing you can happily update your content and tags without any problem at all. That's what we want here too.

In Drupal 8, validating an entity is now decoupled from form validation. More information can be found on the Entity Validation API handbook and how they integrate with Symfony. Now, the validation plugin responsible for that message lives in EntityChangedConstraint and EntityChangedConstraintValidator. Since they are plugins, we can easily swap out the class and depending on our needs only add the violation when we really want to. What we also want is to preserve values of fields that might have been updated by a previous operation, in our case a backend call pinging back to tell us that the score is now ready for playing. Are you ready ? Here goes!

Step 1. Swap the class

All plugin managers in Core (any plugin manager should do that!) allow you to alter the definitions, so let's change the class to our own custom class.

/**
 * Implements hook_validation_constraint_alter().
 */
function project_validation_constraint_alter(array &$definitions) {
  if (isset(
$definitions['EntityChanged'])) {
   
$definitions['EntityChanged']['class'] = 'Drupal\project\Plugin\Validation\Constraint\CustomEntityChangedConstraint';
  }
}
?>

For the actual class itself, you can copy the original one, but without the annotation. The constraint plugin manager doesn't need to know about an additional new one (unless you want it to of course).

namespace Drupal\project\Plugin\Validation\Constraint;

use </span>Symfony\Component\Validator\Constraint;

/**
 * Custom implementation of the validation constraint for the entity changed timestamp.
 */
class CustomEntityChangedConstraint extends Constraint {
  public
$message = 'The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved. In case you still see this, then you are really unlucky this time!';
}
?>

Step 2: alter the node form

We want to be able to know that a validation of an entity is happening when an actual form is submitted. For this, we're adding a hidden field which stores a token based on the node id which we can then use later.

/**
 * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
 */
function project_form_node_form_alter(&$form, &$form_state) {
 
/** @var \Drupal\Node\NodeInterface $node */
 
$node = $form_state->getFormObject()->getEntity();
  if (!
$node->isNew() && $node->bundle() == 'your_bundle' && $node->getOwnerId() == \Drupal::currentUser()->id()) {
   
$form['web_submission'] = [
     
'#type' => 'hidden',
     
'#value' => \Drupal::csrfToken()->get($node->id()),
    ];
  }
}
?>

Step 3: Validating the entity and storing an id for later

We're getting to the tricky part. Not adding a violation is easy, but the entity that comes inside the constraint can't be changed. The reason is that ContentEntityForm rebuilts the entity when it comes in the submission phase, which means that if you would make any changes to the entity during validation, they would be lost. And it's a good idea anyway as other constraints might add violations which are necessary. To come around that, our constraint, in case the changed time is in the past, will verify if there is a valid token and call a function to store the id of the node in a static variable which can be picked up later.

namespace Drupal\project\Plugin\Validation\Constraint;

use </span>Symfony\Component\Validator\Constraint;
use
Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the EntityChanged constraint.
 */
class CustomEntityChangedConstraintValidator extends ConstraintValidator {

  </span>/**
   * {@inheritdoc}
   */
 
public function validate($entity, Constraint $constraint) {
    if (isset(
$entity)) {
     
/** @var \Drupal\Core\Entity\EntityInterface $entity */
     
if (!$entity->isNew()) {
       
$saved_entity = \Drupal::entityManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
       
// A change to any other translation must add a violation to the current
        // translation because there might be untranslatable shared fields.
       
if ($saved_entity && $saved_entity->getChangedTimeAcrossTranslations() > $entity->getChangedTimeAcrossTranslations()) {
         
$add_violation = TRUE;
          if (
$entity->getEntityTypeId() == 'node' && $entity->bundle() == 'your_bundle' &&
           
$this->isValidWebsubmission($entity->id())) {
           
$add_violation = FALSE;

            </span>// Store this id.
           
project_preserve_values_from_original_entity($entity->id(), TRUE);
          }

          </span>// Add the violation if necessary.
         
if ($add_violation) {
           
$this->context->addViolation($constraint->message);
          }
        }
      }
    }
  }

  </span>/**
   * Validate the web submission.
   *
   * @param $value
   *   The value.
   *
   * @see project_form_node_form_alter().
   *
   * @return bool
   */
 
public function isValidWebsubmission($value) {
    if (!empty(
\Drupal::request()->get('web_submission'))) {
      return
\Drupal::csrfToken()->validate(\Drupal::request()->get('web_submission'), $value);
    }

    return </span>FALSE;
  }

}

/**
 * Function which holds a static array with ids of entities which need to
 * preserve values from the original entity.
 *
 * @param $id
 *   The entity id.
 * @param bool $set
 *   Whether to store the id or not.
 *
 * @return bool
 *   TRUE if id is set in the $ids array or not.
 */
function project_preserve_values_from_original_entity($id, $set = FALSE) {
  static
$ids = [];

  if (</span>$set && !isset($ids[$id])) {
   
$ids[$id] = TRUE;
  }

  return isset(</span>$ids[$id]) ? TRUE : FALSE;
}
?>

Step 4: copy over values from the original entity

So we now passed validation, even if the submitted changed timestamp is in the past of the last saved version of this node. Now we need to copy over values that might have been changed by another process that we want to preserve. In hook_node_presave() we can call project_preserve_values_from_original_entity() to ask if this entity is eligible for this operation. If so, we can just do our thing and happily copy those values, while keeping the fields that the user has changed in tact.

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function project_node_presave(NodeInterface $node) {
  if (!
$node->isNew() && isset($node->original) && $node->bundle() == 'your_bundle' && project_preserve_values_from_original_entity($node->id())) {
   
$node->set('your_field', $node->original->get('your_field')->value);
   
// Do many more copies here.
 
}
}
?>

A happy user!

Not only the user is happy: backends can update whenever they want and customer support does not have to explain anymore where this annoying user facing message is coming from.

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web