首页 > 解决方案 > Drupal 8:使用 hook_form_alter 将 Ajax 附加到字段引用

问题描述

我有三种类型的内容:

“Fiche Plan Action”有一个对“Promoteur”的引用字段(field_nom_du_promoteur_en_questi)。

“Fiche Action”具有对“Fiche Plan d'action”(field_plan_d_action)的引用字段。

创建的内容类型如下:Promoterur、Fiche Plan Action 和finaly Fiche Action。

我想将 Ajax 回调附加到字段 (field_plan_d_action),因此当我更改此自动完成字段时,文本类型的字段由指向“Promoteur”内容的链接自动填充。

我试图在“Fiche Action”中获取对象,然后从我得到的那个对象中获取“Promoteur”的对象,然后我通过指向该“Promoteur”的链接更新该字段。

注意:我尝试将 Ajax 附加到自动完成(参考)和选择列表。当我设置静态 ID 以获取“Promoteur”时,它可以工作,但我想从当前表单中动态获取“Fiche Plan Action”和“Promoteur”的对象(使用 form_alter())。

我在 Drupal 文档中只找到了一个使用选择列表类型的示例。对于日期(日期选择器)等其他归档类型,我不清楚。

在此处输入图像描述

function nom_promoteur_form_alter(&$form, FormStateInterface $form_state, $form_id){

  if($form_id == 'node_fiche_d_action_form' || $form_id == 'node_fiche_d_action_edit_form'){

   $form['field_plan_d_action']['widget'][0]['target_id']['#ajax'] = [
      'callback' => 'myAjaxCallback',
      'disable-refocus' => FALSE,  
      'event' => 'change', 
      'wrapper'=>'edit-field-nom-du-promoteur-0-value',
    ];

   $form['field_example_select']['widget']['#ajax'] = [
      'callback' => 'myAjaxCallback',
      'disable-refocus' => FALSE,  
      'event' => 'change', 
      'wrapper'=>'edit-field-nom-du-promoteur-0-value',
    ];

  }
}  


function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  //$values = $form_state->cleanValues()->getValues();

  /* fiche plan d'action (Object)*/
   $nodeFPA = $form['field_plan_d_action']['widget'][0]['target_id']['#default_value'];
  //$nidFPA = (int) $nodeFPA->nid->value;

  /* Get Promoteur Dynamically  (Object)*/
  //$promoteur = $nodeFPA->field_nom_du_promoteur_en_questi->entity;

  /* Promoteur with Static ID (Object)*/ 
  $promoteur = \Drupal\node\Entity\Node::load(2);
  $nid = $promoteur->id();      
  $nLabel = $promoteur->label();

  /* Url Alias */
  $url_alias = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid);

  /* Update field  */
  $form['field_nom_du_promoteur']['widget'][0]['value']['#value'] = "<a href='$url_alias'>$nLabel </a>";

  /* Just For Test */
  //$form['field_nom_du_promoteur']['widget'][0]['value']['#value'] = " Test ";

return  $form['field_nom_du_promoteur'];

}

标签: drupaldrupal-8drupal-modulesajaxformhook-form-alter

解决方案


推荐阅读