drupal: Form API, dynamically hide or show fields based on input
Asked Answered
S

3

12

I'm building a form module. One of the early fields is a set of radio buttons. By default the first button is selected. Next I'll have a series of select boxes. One needs to be visible, the others invisible. Then as the user selects a different radio button I want different select boxes to show or hide. How can I hide the field and label by default and show it later dependent upon which radio button (or another select box option for that matter) is chosen?

Staphylorrhaphy answered 5/10, 2012 at 19:42 Comment(1)
I'm on my mobile so can't find links with ease for you. Check Form API Referenc and you will see a #ajax property to set. That's how we usually do it. But raw JavaScript or jquery is also an option.Salsbury
M
19

You can use the #states property to achieve that. The #states property can be applied to all Form API elements.

Here's the documentation link with an example.

Macguiness answered 6/10, 2012 at 1:48 Comment(3)
Thanks a lot! I was looking through the api, but there's a lot there so this was easily missed.Staphylorrhaphy
Really glad it helped :)... -Muhammad.Macguiness
Here is another documentation link from Lullabot that explains the Drupal Form API States - lullabot.com/articles/form-api-statesPoetics
B
12

simple usage example of #states: To show a select field with name 'item' only if another field with name 'type' has value 'sell'

$form['item'] = array( 
        '#title' => t('Task Item'),
        '#type' => 'select',
        '#states' => array(
            // Only show this field when the value of type is sell.
            'visible' => array(
                ':input[name="type"]' => array('value' => 'sell'),
            ),
        ),
    );
Bac answered 24/6, 2014 at 5:30 Comment(1)
Which hook would this be used in?Smithy
E
2

You could also use 'Conditional Fields' module. Here is the link: https://drupal.org/project/conditional_fields It provides a 'Manage Dependencies' tab while creating a content type where you can select which fields to be visible when a field has a particular value.

Effulgent answered 20/6, 2013 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.