TransWikia.com

How do I create a conditional form field?

Drupal Answers Asked by Sean on December 15, 2020

I have this dropdown menu of options in the user registration page of my site (image shown below), and i want when the user selects the employer, some text fields appear, like name of company, and when they select job seeker, the text field that appears asks for things like uploading CV.

conditional dropdown

I have conditional fields module installed but it does not cater for user registration form (image shown below) .

Is there a way to add the user registration form to be one of the options that conditional fields module offers? I have followed each of those links and none of them is helpful.:(

conditional fields

Lastly, in the account type drop down image shown above, I want to filter out the administrator, anonymous user and authenticated user options such that the user only creates either an employer account or job seeker account. Any ideas how i can do that?

2 Answers

If you happy doing some custom coding then you can use hook_form_alter() to alter the form and then use states to conditionally hide and show fields. You can also remove the other options from the account type select whilst your there.

For example your code may look something like this:

/**
 * Implements hook_form_FORM_ID_alter() for user_register_form.
 */
function YOUR_MODULE_form_user_register_form_alter(&$form, DrupalCoreFormFormStateInterface $form_state, $form_id) {

  // Install devel and uncomment this line to understand the struture of the $form array
  //dpm($form);

  $form['your_field']['#states'] = [
    'visible' => [
      ':input[name="somefield[value]"]' => ['checked' => TRUE],
    ]
  ];

  unset($form['account_type']['#options']['administrator']);
  unset($form['account_type']['#options']['anonymous user']);

}

This code just gives you an idea of the kind of thing required - you will need to modify what is above to fit your exact use case.

This is certainly more complex than using the conditional fields module but is also far more flexible.

Answered by Felix Eve on December 15, 2020

You can do this using taxonomy terms. A warning though ... taxonomy worked terribly due to the amount of conditional items. For my situation, user selected a state, then the town it took about a minute for each selection.

Does this help? http://www.webbykat.com/2013/04/conditional-fields-and-term-reference-tree-two-small-bugs-their-resolution

I'm assuming you have this Drupal 7 module? https://www.drupal.org/project/conditional_fields

Answered by edukates on December 15, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP