1

My "Article" nodes have a "domain" field that links to a taxonomy term. My "Article" nodes also have a repeatable "entity reference" field "more like this" that links to other "article" nodes.

How can i restrict the list in the "more like this" field to show only the nodes that have the same "taxonomy term" that the node i am currently editing ?

Thanks a lot !

2
  • Do you need a programming (PHP) or Views-Config solution? – Rainer Feike Jun 23 '16 at 14:46
  • It doesn't matter to me. maybe a PHP version could be more configurable for future use case ... but i'm open to anything :) – Flunch Jun 23 '16 at 15:34
2

For the PHP solution you have to provide an EntityReferenceSelection Plugin. I give you an example from my "proreos" project:

namespace Drupal\proreos\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection
...

/**
 * Plugin implementation of the 'selection' entity_reference.
 *
 * @EntityReferenceSelection(
    *   id = "default:proreos",
    *   label = @Translation("proreos selection"),
    *   entity_types = {"address_entity", "anwalt_entity", "library_entity"},
    *   group = "default",
    *   weight = 1
    * )
    */
class OwnEntitiesSelection extends DefaultSelection {

  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
      $query = parent::buildEntityQuery($match, $match_operator);
      ... your code here to modify the query ...
      ... (I do $query->condition('user_id', $currentUid);) ...
      return $query;
   }} 

You may also need to override validateReferenceableNewEntities(). Look for more examples in the core modules.

3
  • Hello, seems to be exactly what i am looking for, unfortunately i can't make it work. I created a plugin "node_domain" and put src/Plugin/EntityReferenceSelection/NodeDomainSelection.php with a class NodeDomainSelection extends DefaultSelection but this file seems to never be loaded (plugin is activated, cache cleared, ...) any clue on how to delcare it properly ? – Flunch Jun 24 '16 at 9:50
  • Hm, there is nothing special about it. Have your module activated? Have the correct annotation (@EntityReferenceSelection), have the correct psr path (src/Plugin/EntityReferenceSelection). Should work. What do you mean by "I created a plugin"? Is this a module? – Rainer Feike Jun 26 '16 at 10:08
  • Check out this known bug: drupal.org/project/drupal/issues/2743773 – Rainer Feike Dec 9 '18 at 9:19

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.