0

Backstory: I used and highly enjoyed Conditional Fields modules for D6 in the past. Currently using 7.x-3.x-dev. But had some issues recently with it and would rather just learn how to do it manually. Familiar with Devel, but had no luck successfully getting a complex hook_form_alter() to work. Always end up hitting a dead-end.

What are the fundamentals of implementing a hook_form_alter()?

I'd like to get this process laid out and in one single location. Thanks.

2

The Conditional Fields module's features can be done with using #states attribute from form api in D7.

If you want to implement it, of course you need to use hook_form_alter() to bring additionaly attributes on existing fields. There many tutorials about the usage of hook_form_alter().

Example of using of #states attribute:

  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );
  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

Example from Examples for Developers module - form_example module

  • Ahh, been trying to use the #disabled attribute all along. Thanks for the help. A wild guess, can you have more than one field in this array validate in order to display the hidden field? (since the #states attribute pulls from an array) – tdm Sep 25 '13 at 17:12
  • Have a look on the Examples for Developers module - form_example module, there is good examples about #states with nested childs – pico34 Sep 25 '13 at 18:39
  • @pico34, how can I do the same in Drupal 6? – ARUN Jun 11 '14 at 11:39
  • @ARUN, this is not implemented in D6 form API. You have to do with your own custom jquery. Or with Conditional Fields module – pico34 Jun 11 '14 at 17:44

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.