jsitter's picture

I'm trying to get a password_confirm field to hide when a checkbox isn't selected. The example in the Form API Documentation works great for regular text fields but doesn't work when attached to a password_confirm field. I'm not sure if this is a bug or if I'm not using it properly.

 

$form['sasnewsletter_set_password'] = array(

  '#type' => 'checkbox',

  '#title' => t('Set Password'),

  '#default_value' => FALSE,

);


$form['sasnewsletter_smtp_server_password'] = array(

    '#type' => 'password_confirm',

    '#title' => t('SMTP Server Password'),

    '#size' => 25,

    '#states' => array(

     // Hide the password field when sasnewsletter_set_password checkbox is disabled.

    'invisible' => array(

      ':input[name="sasnewsletter_set_password"]' => array('checked' => FALSE),

    ),
  ),
);

Accepted answer

Hello  👋

This seems to be an issue with D7 and D8/9 too. See https://www.drupal.org/project/drupal/issues/1427838

...someone in that thread mentioned that wrapping the password in a '#type' => 'container' and then adding #states to the container has worked for them (but I suspect that you may need custom form validation then).

Can you please give that a go, and let us know if it worked for you too?

Thanks

Comments

klonos's picture

Hello  👋

This seems to be an issue with D7 and D8/9 too. See https://www.drupal.org/project/drupal/issues/1427838

...someone in that thread mentioned that wrapping the password in a '#type' => 'container' and then adding #states to the container has worked for them (but I suspect that you may need custom form validation then).

Can you please give that a go, and let us know if it worked for you too?

Thanks

Hey klonos

Wrapping it in a container worked.

The working code is:

$form['sasnewsletter_set_password'] = array(

  '#type' => 'checkbox',

  '#title' => t('Set Password'),

  '#default_value' => FALSE,

);


$form['password_wrapper'] = array(

  '#type' => 'container',

  '#states' => array(

    // Hide the password field when sasnewsletter_set_password checkbox is disabled.

    'invisible' => array(

      ':input[name="sasnewsletter_set_password"]' => array('checked' => FALSE),

    ),

  ),

);


$form['password_wrapper']['sasnewsletter_smtp_server_password'] = array(

  '#type' => 'password_confirm',

  '#title' => t('SMTP Server Password'),

  '#size' => 25,

);
klonos's picture

Yay! 🎉 ...glad the workaround has worked in your case as well  and thanks for taking the time to confirm.

I've marked https://www.drupal.org/project/drupal/issues/1427838 as needing backport to D7, so once this is fixed for D8/9, we'll crossport the proper solution to Backdrop. One way or another, this will eventually be no issue.

Cheers