0

I successfully update a field from ajax. Its declaration is the following :

$form['field_unite_de_recherche']['widget']['#ajax'] = array(
  'callback' => 'ajax_equipes_from_unites_callback',
  'event' => 'change',
  'method' => 'html',
  'wrapper' => 'edit-field-equipe-membre2-wrapper',
);

This ajaxified field is declared as in the following :

$form['field_equipe_membre2'] = [
  '#type' => 'select',
  '#title' => 'Equipe(s) membre rattachée(s) à '.$title,
  '#options' => $options,
];

My question is: how to know and save the selected value in this ajaxified field by the user?

I tried to add another ajax declaration in this ajaxified field as in the following :

$form['field_equipe_membre2'] = [
  '#type' => 'select',
  '#title' => 'Equipe(s) membre rattachée(s) à '.$title,
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'ajax_save_choice_callback',
    'event' => 'change',
    'method' => 'html',
    'wrapper' => 'edit-field-equipe-membre2-wrapper',
  )
];

But the callback function is not fired. Is there a limitation of ajax function in a form?

I red a number of times that I can use the $form_sate, for instance as in the following (from Ajax call with Submit loses submitted form data)

$value = $form_state->getValue('field_equipe_membre2');
$testArray = array('field_equipe_membre2' => $value);
$form_state->setStorage($testArray);

But the callback is not fired.

Can I have some advices?

4
  • Usually these issues happen when you've added form elements in your ajax callback. They won't have ajax applied to them. You need to add form elements in the form definition.
    – Jaypan
    Commented Jun 17, 2021 at 16:25
  • May be I was not enough clear. The "field_equipe_membre2" in in the form definition, with no any options values, and these values are well filled by "ajax_equipes_from_unites_callback" function. But I did not find how to retrieve the selected value in "field_equipe_membre2" field when user click on "submit" button of th form.
    – cocq
    Commented Jun 18, 2021 at 7:09
  • First off, I don't think that setStorage() is the method that you want. You probably should be using setValue(), instead. How are you rendering this form? Also, this is for Drupal 7, right? You should mark the question with the Drupal version number.
    – Beau
    Commented Jul 16, 2021 at 16:01
  • You are right concerning "setValue" as a better functino than "setStorage" (one of my numerous tests...). This is for Drupal 9.
    – cocq
    Commented Aug 30, 2021 at 7:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.