Hi I have form element as follows:

<?php
$form['name'] = array(
      '#type' => 'textfield',
      '#title' => $title,
       '#default_value' => $name,
       '#size' => 40,
    );
drupal_set_message($form['name']['#default_value' ]);
?>

I change $name and $title variable with ajax callback. Title changes correctly. drupal_set_message also returns changed default value correctly but I still can see the original value in the form.

Can anybody help?

Comments

Antwanvdm’s picture

Cant you use jQuery("id).val(); to change it in the font, you are already using Javascript right?
You said everything did change correctly within the PHP, so it should just be a output problem.

fawzi’s picture

you don't need #default_value in drupal_set_message, just ['name'] is enough.

nevets’s picture

Without seeing the whole function, its hard to tell where $name comes from.

Bagz’s picture

My guess is that the default value is not displayed on the form so you can't change it with AJAX. The default value is just the initial value that is put into $form['name']['value'] when the form is rendered. You can probably change the default value but without re-loading the form you won't see it?

mortona2k’s picture

I set a #default_value on my text field, then check for form_state and set it again, but when the ajax reloads the form, the default value is set to null, even though it is correct if I do a dpm in my callback. Any more clues?

The other Andrew Morton

melissavdh’s picture

I have been struggling with this issue too, although have just found out why this is happening...

Even if the #default_value is set correctly, and $form['element_name']['#default_value'] technically contains the right information, the value held in #default_value will only be displayed if $form_state['input']['element_name'] is EMPTY. If there is a value in $form_state['input']['element_name'], whatever it is, then $form['element_name']['#default_value'] will not be shown. By definition, the #default_value is only shown if there is no previously entered information to display!

In my situation I have a textfield, and I want to control the text inside it using a set of radio buttons with an ajax callback. When a different button is selected, the text in the textfield will change. I set this text using the $form['textfield']['#default_value'] element, but to get the default value to show I have to say unset($form_state['input']['textfield']) before the form element is defined.

geoandri’s picture

I have a similar problem with select lists . What do you mean "before the form element is defined"?
I tried, following your guide lines , inserting the unset($form_state['input']['textfield']) inside the ajax callback function but it did not worked.

peskydonut’s picture

I've been beating my head against the wall for 2 days. Unsetting the $form_state['input']['element_name'] does the trick!

sitekick’s picture

Thanks for this tip! Pulling my hair out all morning on this issue

sumaiyajaved’s picture

Thank you melissavdh I had been trying to figure this one out from the last hour .. :)

Had read it before in the documentation but forgot while implementing. I have been trying to alter a webform, and have noted that the fields that i had created in the form_alter function did not have this restriction but the fields that were created by the webform module did... I wonder why?

Regards,

Sumaiya Javed
Web Developer
www.sumaiyajaved.com
www.phpjavascript.com

tanmayk’s picture

Unsetting $form_state['input']['element_name'] will work but what if form is rebuilding after failing in validations ? I think, It will again display your '#default_value', which seems wrong. It should display entered value. Any thoughts ??

-- tanmayk

pd.raj’s picture

I had the same problem, default value does not change on ajax load but it works when I replace #default_value with #value.

romain.sahli’s picture

Hi all,

I looked at all your posts. In some special cases (i.e. when I receive specific url parameters), I want a checkbox field of a form to be no-editable with a default value. When I hit the form, the checkbox is greyed out and is checked (which is the default value I set). But the field value when the form is submitted is not the value I expect, as the checkbox is not checked.

I guess I only change the form when displayed, how can I also change the value of the checkbox ? Thank you.

Here is my code:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_form_id') {
      // set the default value to my check box
      $form['checkbox_field_name']['#default_value'][0]['value'] = 'this_will_check_the_box'; 
      // make the checkbox not-editable
      $form['#after_build'][] = '_disable_field_after_build';
  }
}

function _disable_field_after_build($form, &$form_state) {
  _form_disable_field($form['checkbox_field_name']);
  return $form;
}

function _form_disable_field(&$elements) {
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      // Recurse through all children elements.
      _form_disable_field($elements[$key]);
    }
  }
  if (!isset($elements['#attributes'])) {
    $elements['#attributes'] = array();
  }
  $elements['#attributes']['disabled'] = 'disabled';
}

romain.sahli’s picture

All right, as I mentioned, the default value is only used for display. One would have to re-populate the value when the form is submitted. Here is the code:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_form_id') {
      // set the default value to my check box
      $form['checkbox_field_name']['#default_value'][0]['value'] = 'this_will_check_the_box'; 
      // 1. Disable the fields in a custom #after_build handler.
      $form['#after_build'][] = '_disable_field_after_build';
      // 2. Re-populate the fields in a custom #submit handler.
      $form['#submit'][] = 'mymodule_form_submit';

  }
}

function _disable_field_after_build($form, &$form_state) {
  ... // same as above
}

function mymodule_form_submit($form, &$form_state) {
  if ($form['checkbox_field_name']['#attributes']['disabled'] == 'disabled') {
    // retrieve default value
    $value = $form['checkbox_field_name']['#default_value'][0]['value']; 
    // set the value
    $form_state['values']['checkbox_field_name'][0]['value'] = $value;
  }
}

happysnowmantech’s picture

I found this thread after running into a similar problem when trying to use #default_value in form elements when using AJAX callbacks. Here is some example code for doing this:


/**
 * Example of how to set default values for form fields when using AJAX callbacks.
 * 
 * In this example, the form has a select field called "Size" and a text
 * field called "Price".  When the user selects a different value for
 * "Size", the value of "Price" is updated automatically via AJAX.
 */
function my_example_form($form, &$form_state) {
  $form['size'] = array(
    '#title' => t('Size'),
    '#type' => 'select',
    '#options' => array(
        0 => '--',
        1 => 'Small',
        2 => 'Medium',
        3 => 'Large'
     ),
    // #default_value only gets used the first time the form page is loaded,
    // NOT for any subsequent AJAX calls
    '#default_value' => 0,
    '#ajax' => array(
      'callback' => 'my_example_ajax_callback',
      'wrapper' => 'price-wrapper',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
  $form['price'] = array(
    '#title' => t('Price'),
    '#type' => 'textfield',
    '#prefix' => '<div id="price-wrapper">',
    '#suffix' => '</div>',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function my_example_ajax_callback($form, &$form_state) {
  if (!empty($form_state['values']['size'])) {
    $size = $form_state['values']['size'];
    if ($size == 1) {
      // You could also do something like:
      // $form['price']['#value'] = $form['price']['#default_value']
      // if your form builder function already computed/set a #default_value
      $form['price']['#value'] = '$1.99';
    }
    if ($size == 2) {
      $form['price']['#value'] = '$2.99';
    }
    if ($size == 3) {
      $form['price']['#value'] = '$3.99';
    }
  }
  else {
    $form['price']['#value'] = '';
  }

  return $form['price'];
}

function my_example_form_submit($form, &$form_state) {
  $size = $form_state['values']['size'];
  $price = $form_state['values']['price'];
  drupal_set_message(t('You submitted: Size = %size, Price = %price', array('%size' => $size, '%price' => $price)));
}

trong.nguyen.tcec’s picture

Developer shouldon't set '#default_value' for AJAX changes. I've got this problem.
'#default_value' SHOULD BE
'#default_value' =>key($options) WHERE '#options' =>$options.

vivekweb03’s picture

Simplest solution is to use #value in ajax callback.

#default_value won't work

rajveergangwar’s picture

You saved my life

Rajveer Singh
rajveer.gang@gmail.com