0

I am using Webforms in Drupal 8, and I have a checkbox on a webform composite element which basically show/hides an address field.

public static function getCompositeElements() {
  $elements = [];

  $elements['address_same'] = [
    '#type' => 'checkbox',
    '#title' => t('They live at the same address'),
  ];

  $elements['address_postal'] = [
    '#type' => 'textfield',
    '#title' => t('Street address'),
    '#states' => [
      'visible' => [
        ':input[name="spouse[address_same]"]' => array('checked' => FALSE),
      ]
    ]
  ];
}

The issue I have is that this group of fields may have one or more values on the form, and if there is more than one then the states get all confused because they are targeting the wrong field.

This may be the same on Drupal 7, but I can not figure out how to give #states a generic selector for address_same so that it only targets the one just before it.

Most likely I will just go write some custom jQuery for this, just thought there must be a way of doing it.

1

1 Answer 1

0

See the first comment on my question, the Webform module (super-duper) maintainer @jrockowitz committed a change to the module's composite element example which explains how to do this in Drupal 8.

So this is my solution based on the question code:

use Drupal\Component\Utility\Html;
use Drupal\webform\Element\WebformCompositeBase;

class MembershipItem extends WebformCompositeBase {

  public static function getCompositeElements() {
    $elements = [];

    // Generate an unique ID that can be used by #states.
    $html_id = Html::getUniqueId('webform_membership_item');

    $elements['address_same'] = [
      '#type' => 'checkbox',
      '#title' => t('They live at the same address'),
      '#attributes' => [
        'data-webform-composite-id' => $html_id . '--address_same'
      ],
    ];

    $elements['address_postal'] = [
      '#type' => 'textfield',
      '#title' => t('Postal address'),
      '#states' => [
        'visible' => [
          '[data-webform-composite-id="' . $html_id . '--address_same"]' =>['checked' => FALSE],
        ]
      ]
    ];

    return $elements;
  }
}

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.