I have a form that includes a set of radio inputs, and other fields that will or will not be relevant, depending on which radio option is selected. I'm using #states for client-side UX sugar.
However there are certain conditions, picked up in the validate function that need to change the value the user entered for the radio, and re-present the form with a different option selected. I'm having problems with this, as the form comes back but the option is not changed. e.g. Submitting this should with 'a' selected should change it to 'b' and re-present.
What happens is that the value is set to b, the form rebuilds, but the browser still shows 'a' selected.
<?php
function x_a_form($form, &$form_state) {
return [
'switcher' => [
'#type' => 'radios',
'#options' => [
'a' => 'Aye',
'b' => 'Bee', ],
'#default_value' => empty($form_state['values']['switcher'])
? 'a'
: $form_state['values']['switcher'],
],
'submit' => ['#type' => 'submit', '#value' => 'Go' ],
];
}
function x_a_form_validate($form, &$form_state) {
// silly example of a condition...
if ($form_state['values']['switcher'] == 'a') {
// Change the value.
// Nb. form_set_value() is a very long winded way to do just this:
$form_state['values']['switcher'] = 'b';
// We will not be saying anything is invalid, but we don't want
// the form to submit.
$form_state['rebuild'] = TRUE;
return;
}
// other validation...
}