3
votes

I need to filter an "Entity Reference View" autocomplete widget by passing arguments from a "Reference Field" in my content type.

Autocomplete by URL

I researched on this and found that PHP Code type Contextual Filter is the most suggested way to achieving this but as PHP Code has now been removed from Drupal 8 Core, what are the alternatives to this common use case? (an earlier suggestion to use PHP Code: Drupal 7: how to filter view content (with entity reference field) based on current page content)

While editing the reference field, it seems that only hard-coded values be mentioned in "View arguments" field and there is no dynamical way of achieving this (e.g. from URL/query string etc).

View Arguments field

1
What do you mean by "entity reference view" ... please give more detail of your setup - GiorgosK
I'm working on Drupal 8. I setup a view of "Entity Reference" type and then mentioned it in my "Entity Reference" field (autocomplete widget) in a Content Type. You can notice it in 2nd picture above "View used to select the entities". My question is about "View arguments" field (in the same picture) where I'm trying to pass dynamic parameters (for example if "Country ISO Code=USA" then autocomplete widget only shows USA office locations and not all offices around the world). Please let me know if I was able to clarify. Thanks for your support - Farrukh

1 Answers

0
votes

It's hacky, but you can use a hook_form_alter. Here's an example passing the current NID as an argument:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) 
{

  if ($form_id == 'node_NODETYPE_edit_form') {
    $node = $form_state->getFormObject()->getEntity();
    $form['field_MY_REF_FIELD']['widget'][0]['target_id']['#selection_settings']['view']['arguments'][0] = $node->id();
  }
}