I have an entity_reference field in a content type: field_node_ref

In the field definition, it can reference all the nodes of a given type.

The widget used for this field is a select widget

Depending the context, in the node edit form, I would like to use different views to populate the #options of the select widget.


Context A --> View A will be used

Context B --> View B will be used

The context is calculated in my business logic (I speak about it to show that multiple views can be used and then, it can't be encoded in the field definition)

In my_module_form_alter the #options are already populated and I can't update the select widget array to populate them with a custom view. I assume, I have to hook before, but I don't know how.

  • What are the different contexts based on? It might make a difference to the best approach
    – Clive
    Nov 19, 2021 at 20:07
  • @Clive: They are based on the value of a state machine field; which is another field of the edited node. Depending the state/phase/status of the edited node, I need to use view A, B or C to populate the #options of my select widget.
    – Baud
    Nov 19, 2021 at 22:40

1 Answer 1


You can create a customized selection for an entity reference field by setting an Entity Reference display of a view as the source.

To do this, create a view with an Entity Reference display. Construct that view like you normally do (select what fields to render, the basic filters, sorts, limits, etc.). Then create a custom contextual filter, grab the context, inject needed service classes, use your business logic on it, and then apply that contextual filter to the view.

In most cases, you build a filter against the ID of the entity, and your filter's job is to find out if that item should be shown or suppressed. Drupal's built in "Content ID from URL" and "Taxonomy term ID from URL" are examples of these kinds of filters. Your filter will just need to incorporate more logic than just comparing IDs.

Then on the entity reference field settings, change the Reference method to View: Filter by an entity reference view.

  • This is a nice idea. I will wait if someone doesn't comes up with a better tip before accepting this answer. I was expecting a very early hook to easily swap the used view (like we can do with an autocomplete widget)
    – Baud
    Nov 19, 2021 at 22:44

Your Answer

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

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