I have an AJAX form. I want to update the text of a textfield when a button is triggered. But this does not work. My form is below:
<?php
function my_form($form, &$form_state) {
$form['ask_first_name'] = array(
'#type' => 'textfield',
'#title' => t('Ask me my first name'),
'#default_value' => 'I LOVE chickens',
'#prefix' => '<div id="textfields">',
'#suffix' => '</div>',
);
$form['update'] = array(
'#type' => 'button',
'#value' => t('Update'),
'#ajax' => array(
'callback' => 'ajax_example_autotextfields_callback',
'wrapper' => 'textfields',
'effect' => 'fade',
),
);
// shouldn't this update the default value when the button is pressed??
if (isset($form_state['values'])) {
$form['ask_first_name']['#default_value'] = 'I HATE chickens';
}
return $form;
}
?>
When I press the 'update' button I'm expecting the field text to change, but it doesn't. If I use #value
instead of #default_value
it works, but I know I shouldn't use that because I still want the user to be able to change it again.
<?php
// using #value works - but should I use that?
$form['ask_first_name']['#value'] = 'I HATE chickens';
?>
What is the recommended Drupal way to change the field value after AJAX is triggered?
NOTE: This answer solved the problem in my case, but as mentioned in the comments there is not access to the values in $form_state['values'] after submit. However, I'm storing the data in $form_state['storage'] so I can still access the data, though I'll probably implement ctools object cache in the end.