Filter Entity Reference View with dynamic argument

2019-07-29 22:51发布

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条回答
看我几分像从前
2楼-- · 2019-07-29 23:54

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();
  }
}
查看更多
登录 后发表回答