How to alter the view behind a select widget in a regular node edit form

sa flag

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.

cn flag
What are the different contexts based on? It might make a difference to the best approach
Baud avatar
sa flag
@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.
in flag

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.

Baud avatar
sa flag
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)

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.