0

I have a select field that holds two options. When the second option is chosen, I want to display a block.

I know that with form API I should be able to do this. I'm just not sure on where to start. Any help getting me going would be greatly appreciated.

So far I have the code below.

function MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['account']['type'] = [
      '#title' => 'I am ordering for',
      '#type' => 'select',
      '#options' => [ 'Myself' => 'Myself', 'Someone' => 'Someone else' ],
      '#weight' => -100
      ];
}
  • Is that block going to be part of the form, i.e. showing further information that need to be submitted on form-submit? – theuni Jun 13 '18 at 7:12
  • you are using drupal8 or drupal7 – sivani Jun 13 '18 at 7:20
  • Hi, @sivani I'm using Drupal 8. – Jorge Calderon Jun 14 '18 at 15:53
  • @theuni, it will be part of the form. – Jorge Calderon Jun 14 '18 at 15:53
1

Don't try to add the fields in a form alter hook. Do this in the field UI of the user entity /admin/config/people/accounts/fields. To change the visibility of fields dependending on the content of another field use

Conditional Fields

or the Form #states API directly, see How can I hide or show fields using states with hook form alter.

EDIT: The form #states api did the trick.

  • Unfortunately, I'm not displaying another field. I'm trying to show and hide a block. – Jorge Calderon Jun 14 '18 at 16:00
  • These are two ways to show and hide elements on a page with javascript. This can also be a block, this is technically the same, only different CSS to make it look like a block. – 4k4 Jun 14 '18 at 16:12
  • got it. yep, I did a bit more research on the #states form API info and I believe that's the way for me to go. – Jorge Calderon Jun 14 '18 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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