1

I am trying to use checkboxes to display inline entity form elements only when the boxes are checked. However, my code doesn't seem to be working. It will hide the element, but when I toggle the checkbox, it won't display what was hidden.

Here is my code:

function lodestar_form_user_profile_form_alter(&$form, &$form_state) {
    dpm($form);
    $form['field_your_nonprofit_connections']['und'] = array(
        '#states' => array(
            'visible' => array(
                ':input[name="field_affiliation_type[und][#options]"]' => array('value' => 'Nonprofit'),
            ),
        ),
    );
}

Here is a screenshot of the field_your_nonprofit_connections field: enter image description here

And here is one for the field_affiliation_type field: enter image description here

Based on what I have been reading in this related question (When using hook_form_alter to modify a content type's node add / edit form, where do I put the #states property?), I have now realized that my form is not even including the #states element at all.

  • How do I add the #states element into an already existing form via hook_form_alter?

  • And, how do I get the checkbox field to toggle the visibility?

2 Answers 2

1

Okay, I figured it out. Here is what I ended up with:

    function lodestar_form_user_profile_form_alter(&$form, &$form_state) {
    dpm($form);
    $form['field_your_nonprofit_connections']['und']['#states'] = array(
        'visible' => array(
            ':input[name="field_affiliation_type[und][Nonprofit]"]' => array('checked' => TRUE),
        ),
    );
}

This code got the element to toggle appropriately. Whew! I'm glad I finally solved it. Hopefully this question and answer will help someone else. It looks like the main thing I did wrong was having the incorrect ":input[name." The way I finally figured it out was by looking in the HTML itself via the element inspector. I should have tried that a long time ago.

Interestingly, the #states element never did show up in my dpm($form) output. I'm not sure why that is the case, but, apparently it doesn't need to show up there, because it is working fine without it.

0
/**
* Implements hook_form_node_form_alter().
*/
function YOURMODULE_form_node_form_alter(&$form, $form_state) {
  if($form['#form_id'] == 'page_node_form') {
  //field to hide unless it's a testimonial
  $form['field_function']['#states'] = array(
    'visible' => array(
      ':input[name="field_testimonial[und][0]"]' => array('checked' => 
    TRUE),
    );
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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