使用参考字段中的动态参数过滤实体参考视图 [英] Filter Entity Reference View with dynamic arguments from Reference Field
问题描述
我需要通过在我的内容类型中传递引用字段中的参数来过滤实体引用视图自动完成小部件。
我对此进行了研究,发现该PHP代码类型Contextual Filter是实现此目的的最建议方法,但是由于PHP代码已从Drupal 8 Core中删除,因此,这种常见用例的替代方法是什么? (使用PHP代码的早期建议:
hacky,但是您可以使用hook_form_alter。下面是一个将当前NID作为参数传递的示例:
/ **
*实现hook_form_alter()。
* /
函数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 ();
}
}
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).
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();
}
}
这篇关于使用参考字段中的动态参数过滤实体参考视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!