Drupal 8: Attaching Ajax to field reference using hook_form_alter

1.3k views Asked by At

I have three Types of Content:

  • Promoteur (fr)
  • Fiche Plan Action ((fr)
  • Fiche Action (fr)

The "Fiche Plan Action" has a reference field to the "Promoteur" (field_nom_du_promoteur_en_questi).

The "Fiche Action" has a reference field to the "Fiche Plan d'action" (field_plan_d_action).

The creation of content types as follows: Promoteur, Fiche Plan Action and finaly Fiche Action.

I want to attach an Ajax callback to the filed (field_plan_d_action), so when I change this autocomplete field, a field of a type text was filled by a link to the "Promoteur" content automatically.

I had tried to get the object in the "Fiche Action" then from that object I get, the Object of the "Promoteur" then I update the field by a link to this "Promoteur".

Note: I tried to attach Ajax to an autocomplete (reference) and a select list. When I set a static ID to get the "Promoteur" it works, but I want to get the Object of "Fiche Plan Action" and "Promoteur "dynamically from the current form (using form_alter()).

I found just one example on the Drupal docs using select list type. for the other filed types as Date (datepicker) its not clear for me.

enter image description here

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'];

}

0

There are 0 answers