3

This is actually a compound question. All in all the question is:

When using hook_form_alter to modify an existing content type's node add / edit form, where do I put the #states property, and, within the definition of the #state array, how do I determine what the value of 'name' should be in ':input[name="somename"]'?

NOTE: If you're very familiar with using #states and modifying node add / edit forms, please skip to the very last of the question where my non-working sample code is listed.

I've created a custom content type and I would like to alter certain node add / edit form elements to show up conditionally based on the values in other fields. To do this, I'd like to use the #states property (Here is a quick intro where I first learned about #states).

Most of the examples and tutorials I find are about creating custom forms. But the same approach does not seem to be working when modifying existing custom content type node add / edit forms.

For example, notice in the link above the following:

$form['kids'] = array(
    '#title' => t('How many kids do you have?'),
    '#type' => 'select',
    '#options' => array(0, 1, 2),
  );

  $form['kids_preferences'] = array(
    '#title' => t('Your kids\' preference'),
    '#type' => 'radios',
    '#options' => array('moto' => 'Motorcycles', 'cars' => 'Cars'),
     // Show this field only if the user has kids.
    '#states' => array(
      'visible' => array(
        'input[name="marriage"]' => array('checked' => TRUE),
      ),
      'disabled' => array(
        'select[name="kids"]' => array('value' => '0'),
      ),
    ),
  );

One would think then, based on the above (which is the same in all other tutorials and Drupal Docs), that you'd add ['#states'] = array(etc..) immediately after the first field element key, right?

Looking at the 'disabled' definition, you'd also conclude that you'd use the field key (kids) to reference the value in the 'name=' part of the #states array, correct?

So, after doing dpm($form) I indeed found my field names. According to dpm they were $form["myfield1"] and $form["myfield2"].

So because $form['myfield2'] depends on a value in $form['myfield1'], I tried:

$form['field_rf_which_state_territory']['#states'] = array(
            'visible' => array(
                ':input[name="myfield1"]' => array('value' => 'Yes')
            ),
        );

However, that doesn't work. Why?

After doing a lot of digging only, I started to see references to array structures like $form['myfield1']['und']['0']['#states']

I don't understand that, but I gave it a shot. Here are the actual data dumps of the two form elements from my content type node add form that I need to interact. (sorry for the long dump)

1) print_r($form["field_rf_which_state_territory"]);

Array
(
[#type] => container
[#attributes] => Array
    (
        [class] => Array
            (
                [0] => field-type-list-text
                [1] => field-name-field-rf-which-state-territory
                [2] => field-widget-options-select
            )

    )

[#weight] => 15
[#tree] => 1
[#language] => und
[und] => Array
    (
        [#entity] => stdClass Object
            (
                [uid] => 1
                [name] => admin
                [type] => snaped_resource_finder
                [language] => und
                [title] => 
                [status] => 1
                [promote] => 1
                [sticky] => 0
                [created] => 1396239314
                [revision] => 
                [comment] => 2
                [menu] => Array
                    (
                        [link_title] => 
                        [mlid] => 0
                        [plid] => 0
                        [menu_name] => main-menu
                        [weight] => 0
                        [options] => Array
                            (
                            )

                        [module] => menu
                        [expanded] => 0
                        [hidden] => 0
                        [has_children] => 0
                        [customized] => 0
                        [parent_depth_limit] => 8
                    )

            )

        [#entity_type] => node
        [#bundle] => snaped_resource_finder
        [#field_name] => field_rf_which_state_territory
        [#language] => und
        [#field_parents] => Array
            (
            )

        [#columns] => Array
            (
                [0] => value
            )

        [#title] => Which State / Territory
        [#description] => 
        [#required] => 
        [#delta] => 0
        [#type] => select
        [#default_value] => Array
            (
            )

        [#multiple] => 
        [#options] => Array
            (
                [_none] => - None -
                [AL] => Alabama
                [AK] => Alaska
                [AZ] => Arizona
                [AR] => Arkansas
                [CA] => California
                [CO] => Colorado
                [CT] => Connecticut
                [DE] => Delaware
                [DC] => District Of Columbia
                [FL] => Florida
                [GA] => Georgia
                [HI] => Hawaii
                [ID] => Idaho
                [IL] => Illinois
                [IN] => Indiana
                [IA] => Iowa
                [KS] => Kansas
                [KY] => Kentucky
                [LA] => Louisiana
                [ME] => Maine
                [MD] => Maryland
                [MA] => Massachusetts
                [MI] => Michigan
                [MN] => Minnesota
                [MS] => Mississippi
                [MO] => Missouri
                [MT] => Montana
                [NE] => Nebraska
                [NV] => Nevada
                [NH] => New Hampshire
                [NJ] => New Jersey
                [NM] => New Mexico
                [NY] => New York
                [NC] => North Carolina
                [ND] => North Dakota
                [OH] => Ohio
                [OK] => Oklahoma
                [OR] => Oregon
                [PA] => Pennsylvania
                [RI] => Rhode Island
                [SC] => South Carolina
                [SD] => South Dakota
                [TN] => Tennessee
                [TX] => Texas
                [UT] => Utah
                [VT] => Vermont
                [VA] => Virginia
                [WA] => Washington
                [WV] => West Virginia
                [WI] => Wisconsin
                [WY] => Wyoming
            )

        [#value_key] => value
        [#element_validate] => Array
            (
                [0] => options_field_widget_validate
            )

        [#properties] => Array
            (
                [strip_tags] => 1
                [optgroups] => 1
                [empty_option] => option_none
                [filter_xss] => 
            )

        [#after_build] => Array
            (
                [0] => field_form_element_after_build
            )

    )

[#access] => 1
)

2) print_r($form['field_rf_snaped_associated']);

Array
(
[#type] => container
[#attributes] => Array
    (
        [class] => Array
            (
                [0] => field-type-list-text
                [1] => field-name-field-rf-snaped-associated
                [2] => field-widget-options-buttons
            )

    )

[#weight] => 14
[#tree] => 1
[#language] => und
[und] => Array
    (
        [#entity] => stdClass Object
            (
                [uid] => 1
                [name] => admin
                [type] => snaped_resource_finder
                [language] => und
                [title] => 
                [status] => 1
                [promote] => 1
                [sticky] => 0
                [created] => 1396239314
                [revision] => 
                [comment] => 2
                [menu] => Array
                    (
                        [link_title] => 
                        [mlid] => 0
                        [plid] => 0
                        [menu_name] => main-menu
                        [weight] => 0
                        [options] => Array
                            (
                            )

                        [module] => menu
                        [expanded] => 0
                        [hidden] => 0
                        [has_children] => 0
                        [customized] => 0
                        [parent_depth_limit] => 8
                    )

            )

        [#entity_type] => node
        [#bundle] => snaped_resource_finder
        [#field_name] => field_rf_snaped_associated
        [#language] => und
        [#field_parents] => Array
            (
            )

        [#columns] => Array
            (
                [0] => value
            )

        [#title] => Is this material associated with a SNAP-Ed program?
        [#description] => 
        [#required] => 1
        [#delta] => 0
        [#type] => radios
        [#default_value] => 
        [#options] => Array
            (
                [Yes] => Yes
                [No] => No
            )

        [#value_key] => value
        [#element_validate] => Array
            (
                [0] => options_field_widget_validate
            )

        [#properties] => Array
            (
                [filter_xss] => 1
                [strip_tags] => 
                [empty_option] => 
                [optgroups] => 
            )

        [#after_build] => Array
            (
                [0] => field_form_element_after_build
            )

    )

[#access] => 1
)

The first thing I noticed is that for each of those [#type] => container That's confusing. Drupal 7 form field API doesn't has very little to say about 'container' and I'm not sure how that plays into how this all works or not.

I also noticed that [#attributes][class]2 is a field name. I tried adding that as the :input[name=] value, but that didn't work either. Additionally, I tried to inspect element of the html form and use field_rf_snaped_associated[und] that was part of the HTML. But, no go either.

And, the one and final confusing point are some tutorials show input[name...] and other show :input[name...]. But, whether I add or omit the colon, it makes no difference. Ultimately, here is the code I ended up with that I can't get to work.

function resourcefinder_form_alter(&$form, &$form_state, $form_id) {

// determine if we're on the correct form
if ($form_id == "snaped_resource_finder_node_form") {


    //dpm($form);
    //print_r($form["field_rf_which_state_territory"]);
    //print_r($form['field_rf_snaped_associated']);

    $form['field_rf_which_state_territory']['und']['0']['#states'] = array(
        'visible' => array(
            ':input[name="field_rf_snaped_associated[und]"]' => array('value' => 'Yes')
        ),
    );
}
}

So, how would I write that so field_rf_which_state_territory only shows up when 'Yes' is selected in the field_rf_snaped_associated field?

EDIT: Screenshot showing dpm output of that field enter image description here

  • 1
    I had exactly the same question, only with fields in an taxonomy term edit form. I had a select list (field_my_select) and a textfield I wanted to show (field_my_textfield). In the end I used following code in my custom module: function mymodule_form_alter(&$form,&$form_state, $form_id){ if($form_id == 'taxonomy_form_term'){ $form['field_my_textfield']['#states']= array( 'visible' => array( ':input[name="field_myselect[und]"]' => array('value' => (string)'0') ), ); } – Alina Apr 1 '14 at 7:43
2

I think you need:

$form['field_rf_which_state_territory']['und']['0']['value']['#states'] = array(
        'visible' => array(
            ':input[name="field_rf_snaped_associated[und]"]' => array('value' => 'Yes')
        ),

When looking though the $form array you need to make sure that you are adding the #states array at the same level that the #type element appears.

enter image description here

  • thank you for the screenshot. Please see my edit. I added a screenshot as well for my dpm of that field. I have several #types within the hierarchy of the array. Additionally, I don't have a 'value' field like you do. Given my dump, what would you suggest the structure be? – blue928 Apr 1 '14 at 0:46
  • Looking at your dmp output I would say you need $form['field_rf_which_state_territory']['und']['#states'] = ... – Felix Eve Apr 1 '14 at 7:59

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.