1

I'm trying to add a custom entity operation to taxonomy terms of a specific vocabulary.

I've found documentation on using hook_entity_operation() to add the operation, and that works, but I'm not sure what to do from there.

Here's the hook implementation:

function nm_target_entity_operation(\Drupal\Core\Entity\EntityInterface $entity) {
  $operations = [];
  if ($entity->getEntityTypeId() == 'taxonomy_term' && $entity->vid->getString() == 'data-source') {
    $operations['import'] = [
      'title' => t('Re-import'),
      'url' => // what goes here?
      'weight' => 50,
    ];
  }
  return $operations;
}

If I want to have a confirmation page at /taxonomy/term/{taxonomy_term}/import, what do I put in the URL property and what kind of class should that route point at?

I took a look at Entity Clone module as that's the only contribute module we use that implements that hook, but that does complicated things with link templates that I don't understand.

1 Answer 1

1

The explanation of what the array returned by hook_entity_operation() contains is explained in the documentation for EntityListBuilderInterface::getOperations().

  • title: The localized title of the operation.
  • url: An instance of \Drupal\Core\Url for the operation URL.
  • weight: The weight of this operation.

'url' is simply the URL for the page executing that operation.

There are 5 implementations of that hook done in Drupal core, for example config_translation_entity_operation(), content_translation_entity_operation(), or field_ui_entity_operation().
The code they use to get the URL vary from one implementation to the other. The simpler way to get a URL for a page created from a module you wrote, for which you know the page route, is calling Url::fromRoute().

3
  • They all seem to use the linkTemplate thing that I'm having trouble grokking, where can I find documentation for that?
    – Lambic
    Mar 7 at 13:32
  • Introduction to Entity API in Drupal 8 / Links gives some details. If you look at the annotation used for Drupal core content entities, you will see how their entity links are defined.
    – apaderno
    Mar 7 at 18:40
  • I ended up implementing a custom route using my modules routing.yml. I'm guessing there's some way to add custom "link templates" when you can't change the annotation but I didn't have time to dig into that.
    – Lambic
    Mar 7 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.