0

I have a select list on custom module form, on it's select giving ajax call and populating the second select list. But when I select the value from the first list, it is passing old value (previously selected) to the callback function (It should send currently select value). Following is my code.

  function get_subject($form, &$form_state) {
    $form['students'] = array(
      '#type' => 'select',
      '#options' => $student_array,
      '#title' => t('Students'),
      '#id' => 'students',
      '#value' => ($students != '') ? $students : '',
      '#required' => TRUE, 
      '#ajax' => array(
        'callback' => '_subject_loader',
        'wrapper' => 'subject_div',
      ),
    );
    $form['subject'] = array(
      '#type' => 'select',
      '#options' => $subject_list,
      '#title' => t('subject'),
      '#id' => 'subject',
      '#prefix' => '<div id="subject_div">',
      '#suffix' => '</div>',
      '#value' => ($subject != '') ? $subject: '',
      '#required' => TRUE 
    );
    $form['submit'] = array(
      '#type'=>'submit',
      '#value'=>'Submit',
    );
    return $form;
  }

  function _subject_loader($form, $form_state) {
    return $form['subject'];
  }
1
  • The '#value' key provides a fixed value for an element. You should use '#default_value' for input fields. So that may be your problem. Aug 21 '18 at 8:34
1

Use Form state input rather than using values in ajax call back like below:

if (isset($form_state['input']['students'])) {
    $student = $form_state['input']['students'];
  }
0
0

If you return the $form['subject'] you will be returning an array most likely, as the $form is a render array. You need to access the lists inside $form_state which hold the values of the submited form.

function _subject_loader($form, $form_state) {
  $user_input_values = $form_state->getUserInput();
  return $user_input_values['student'];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.