6

This is taken from the examples module(http://drupal.org/project/examples). More specifically in the 'Generate textfields' ajax section. The form attempts to demonstrate an ajax call by presenting 2 checkboxes and generating a textfield based on which checkbox was clicked.

This is the ajax callback. We have a textfield with key 'first_name'.

function ajax_example_autotextfields_callback($form, $form_state) {
  $a = $form['first_name'];
  $a['first_name']['#value'] = 'foobar';
  $a['first_name']['#disabled'] = TRUE;
 return $a;
}

The form rendered has value textfield with value 'foobar' as expected, but the textfield is not disabled? How come?

5

You can accomplish that using ajax_command_invoke.

Here is an example using your own code:

function ajax_example_autotextfields_callback($form, $form_state) {
  // $a = $form['first_name'];
  // $a['first_name']['#value'] = 'foobar';
  // $a['first_name']['#disabled'] = TRUE;
  // return $a;

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      // First we add the disable attribute into the html input tag.
      // which makes the the input field inaccessible. 
      ajax_command_invoke('#WRAPPER_SELECTOR input', 'attr', array('disabled','disabled')),
      // Then we grey it out by adding the form-disabled CSS class.
      ajax_command_invoke('#WRAPPER_SELECTOR .form-item', 'addClass', array('form-disabled')),
    ),
  );
}

You can instead grey out using CSS attributes by calling ajax_command_css

  • 1
    Awesome one !! very helpful. – Sandesh Yadav Dec 21 '12 at 8:47
3

I found another solution (if you don't want to use ajax commands).

function ajax_example_autotextfields_callback($form, $form_state) {
  $a = $form['first_name'];
  $a['first_name']['#value'] = 'foobar';
  $a['first_name']['#attributes']['disabled'] = 'disabled';
 return $a;
}
  • This seems to be way simpler than my solution. Thanks for sharing. – Francisco Luz Nov 5 '14 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.