Hi,

I have a problem. I want to hide fields on user_registration form.

Im my module on hook_form_user_register_form_alter I have the following code:

<?php
    $form
['switch'] = array(
       
'#type' => 'checkbox',
       
'#title' => t('Type'),
    );

   

$form['field_name']['#states'] = array(
       
'visible' => array( // action to take
           
':input[name="switch"]' => array('checked' => TRUE)
        ) 
    );
?>

In detail I have a checkbox and depending on state the field "Name" should not be visible. So I added the #states attribute to it.
But as a result. Nothing happens. Seems only to work with my own custom form elements.

Is there a way to achieve this???
Any help is welcome.

Comments

droath’s picture

Hi lordgil -

I think you need to attach the states library and JS to that element.

Take a look at this function on drupal API "drupal_process_states" http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_pro...

Untested Example Code:

<?php
    $form
['switch'] = array(
       
'#type' => 'checkbox',
       
'#title' => t('Type'),
    );

   

$form['field_name']['#states'] = array(
       
'visible' => array( // action to take
           
':input[name="switch"]' => array('checked' => TRUE)
        )
    );
  
drupal_process_states(&$form);
?>
carstenG’s picture

nope. doesn't work. states.js is already attached.

droath’s picture

I just did a simple test and the below code works for me on the "/user/register" page.

Change "HOOK" in the function to your module name.

<?php
/**
 * Implements hook_form_FORM_ID_alter().
 */
function HOOK_form_user_register_form_alter(&$form, &$form_state, $form_id) {
 
$form['switch'] = array(
   
'#type' => 'checkbox',
   
'#title' => t('Display Username'),
   
'#weight' => -100,
  );
 
$form['account']['name']['#states'] = array(
     
// action to take
   
'visible' => array(
     
':input[name="switch"]' => array('checked' => TRUE),
    ),
  );
}
?>
JayMN’s picture

Thanks Travis (droath), that worked, and was very helpful!