My form looks like this:
$form['field_1'] = array(
'#title' => t('Field 1'),
'#type' => 'radios',
'#required' => TRUE,
'#multiple' => FALSE,
'#ajax' => array(
'callback' => '_myform_ajax_field_2',
'wrapper' => 'field-2-wrapper',
'method' => 'replace',
'effect' => 'fade',
),
);
$form['field_2_wrapper'] = array(
'#prefix' => '<div id="field-2-wrapper">',
'#suffix' => '</div>',
'#weight' => 2,
);
if (isset($form_state['values']['field_1']) && $form_state['values']['field_1'] > 0) {
$form['field_2_wrapper']['field_2'] = array(
'#title' => t('Field 2'),
'#type' => 'radios',
'#required' => TRUE,
'#multiple' => FALSE,
);
}
The problem occurs when I submit the form successfully and move to the next page, and then navigate back to this form using browser back button and the field_1
radio button is remembered by the browser. This means that the radio is already selected however in this instance form_state['values']
is empty so field_2 does not display. From here the only way to get field_2
to load via AJAX is to un/re-select the desired option in field_1
.
I've tried the following solutions which failed:
Adding a JS file to
$form[#attached]['js']
to deselect any radio buttons on load, however this also gets loaded in AJAX calls. I'm not aware of a method to prevent this JS from running as a result of a traditional page load, but not on AJAX.I've tried setting a
#default_value
onfield_1
however this has no effect.
Since writing this question, I've discovered a solution which I'm really not happy with:
I am checking for and adding a unique class name to the page body to check whether I've already deselected radios. If it's already there, then don't try again. This works, it just feels a bit dirty, so I'm hoping there's a more Drupally way to solve this?
Drupal.behaviours.myClass.attach()
.