I've created an entity reference field formatter. It works fine. However, the field formatter will only work properly on entities of type user, so if the referenced entity type is different, I don't want the formatter to appear in the list of options.

I tried adding entity_types = { user } to my annotation for the formatter, but this didn't work. I'm suspecting it cannot even be done, but I thought I'd ask here before opening up an issue in core, to suggest it for future development.

Does anyone know if this can be done, and if it can, how?


I think this will work...

There is an isApplicable() method in Drupal\Core\Field\FormatterBase. You can implement it in your FieldFormatter class like this:

public static function isApplicable(FieldDefinitionInterface $field_definition) {
  return ($field_definition->getFieldStorageDefinition()->getSetting('target_type') == 'user');
|improve this answer|||||
  • Nice! That worked like a dream. I was looking at annotation, without even considering methods on the class. Much appreciated. – Jaypan Apr 12 '17 at 1:27
  • With the same approach we can limit the field formatter to a specific field? – Adrian Cid Almaguer Apr 12 '17 at 15:40
  • If the answer is very different I can post a question, so, let my know – Adrian Cid Almaguer Apr 12 '17 at 15:41
  • 2
    Try changing: getSetting('target_type') to getName() to select based on the field machine name. If you look at the FieldDefinitionStorageInterface in the API, you'll see other available options as well. – user72086 Apr 12 '17 at 17:33
  • That's perfect, but what do I do if I only want to target "entity references that reference [my entity type]". Currently I can only target a specific field TYPE or a specific FIELD. I want to target "fields that reference a type". Sounds hard :/ – NikLP Sep 24 '18 at 15:55

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.