Ajax in a form produces an error suppose this form:

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

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

  return $form; 
}


and the callback:

function get_formations($form, &amp;$form_state) {   
  $formations = array(
    0 =&gt; t('No'),
    1 =&gt; 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 ?
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, &amp;$form_state){   
  $form['school'] = array(
    '#type'             =&gt; 'textfield',
    '#title'            =&gt; t('School'),
    '#required'         =&gt; True,
    '#ajax' =&gt; array(
      'callback' =&gt; 'get_formations',
      'wrapper' =&gt; 'formationsWrapper',
    ),   
  );

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

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

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

  return $form; 
}


And the callback:

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