Score:0

how to alter entity reference field (taxonomies) field options in hook form alter

fr flag

Can anyone please let me how to alter entity reference field (taxonomies) field options in hook form alter,

Seems the below code doesn't work.

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_article_edit_form' || $form_id == 'node_article_add_form') {
    $channel_options = [
      '1' => 'Term1',
      '2' => 'Term2',
      '3' => 'Term3',
      '4' => 'Term4',
      '5' => 'Term5',
    ];

    $form['field_channel'] = [
      '#title' => 'Channels',
      '#description' => 'Select Channel',
      '#type' => 'select',
      '#options' => $channel_options,
    ];
  }

}

For context :

I have a field named as channels in node article which is entity reference to channel taxonomy.

I would like to limit the list of terms visible to current user to the channels to which they are assigned in their user profile.

I am trying to achieve it by altering the node edit form and replacing channels field values from the current user logged in.

ru flag
Not really an answer to your question, but there is an alternative, no-code solution for this: With views module, create a view of taxonomy terms. Filter that view as required (in your case most likely a contextual filter on the current user). As display plugin for that view select "entity reference". Then on node field settings, select "Views: Filter by an entity reference view" as "Reference method".
miststudent2011 avatar
fr flag
Thanks Hudri let me try that.
Score:0
fr flag

Thanks to @Hudri suggestion. I am able to achieve it without code using views module.

I followed the guide from How to Use Entity Reference Views in Drupal 8 - OsTraining and created a contextual filter to filter by current logged in user.

The important thing here is define Configure contextual filter When the filter value is NOT available.

View settings

View Contextual Filter Settings

Node Field Channel

miststudent2011 avatar
fr flag
Related https://stackoverflow.com/a/47544262/6687229
I sit in a Tesla and translated this thread with Ai:

mangohost

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.