1

suppose this form:

function test_ajax_form($form, &$form_state){   
  $form['school'] = array(
    '#type'             => 'textfield',
    '#title'            => t('School'),
    '#required'         => True,
    '#ajax' => array(
      'callback' => 'get_formations',
      'wrapper' => 'formationsWrapper',
    ),   
  );

  $form['formations'] = array(
    '#type'             => 'select',
    '#title'            => t('Formations'),
    '#required'         => True,
    '#options'           => array(),
    '#prefix'           => '<div id="formationsWrapper">',
    '#suffix'           => '</div>',
    //'#access'           => empty($form['values']['formations']['#options']) ? False : True,   );

  return $form; 
}

and the callback:

function get_formations($form, &$form_state) {   
  $formations = array(
    0 => t('No'),
    1 => t('Yes'),   
  );

  $form['formations']['#options'] = $formations;   
  return $form['formations']; 
}

Everthing works fine, my callback is called and the values populate the select. If I change the school value, then the callback is recalled and I have an error:

An illegal choice has been detected. Please contact the site administrator.

I think it's beacause I try to re-populate the options but I don't know how to fixe.

Any idea ?

1

You need to do the logic in the form function not the callback. The callback should only return the relevant part of the form. If you add options or change form structure in a callback then you get these illegal choice errors (it's a security feature to stop people from tampering with the forms).

function test_ajax_form($form, &$form_state){   
  $form['school'] = array(
    '#type'             => 'textfield',
    '#title'            => t('School'),
    '#required'         => True,
    '#ajax' => array(
      'callback' => 'get_formations',
      'wrapper' => 'formationsWrapper',
    ),   
  );

  $form['formations'] = array(
    '#type'             => 'select',
    '#title'            => t('Formations'),
    '#required'         => True,
    '#options'           => array(),
    '#prefix'           => '<div id="formationsWrapper">',
    '#suffix'           => '</div>',
    //'#access'           => empty($form['values']['formations']['#options']) ? False : True,   );

  if($form_state['triggering_element']['#name'] == 'school') {
    $formations = array(
      0 => t('No'),
      1 => t('Yes'),   
    );

    $form['formations']['#options'] = $formations;
  }

  return $form; 
}

And the callback:

function get_formations($form, &$form_state) {
  return $form['formations']; 
}
0

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.