Filter Entity Reference View with dynamic arguments from Reference Field

人走茶凉 提交于 2019-12-11 08:52:58

问题


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

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).


回答1:


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();
  }
}


来源:https://stackoverflow.com/questions/51899076/filter-entity-reference-view-with-dynamic-arguments-from-reference-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!