0

I am looking for a way to hide/show some fields depending on what users select on another field. Users can select between four wheeler or two wheeler. If users select four wheeler from a drop-down, they see different set of fields than the ones show when two wheeler is selected. As there are many common fields I am looking to use the same content type for both cases.

What I have tried so far is using hook_form_alter() or hook_form_FORM_ID_alter() in the .theme file. Neither of them seems to work for me.

This is the code I tried. (Please do note I am using themename instead of the machine name of the theme; also the field names has been changed.)

use Drupal\Core\Form\FormStateInterface; // at top of themename.theme


function themename_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $form['field_album_type_name']['#states'] = [
    'visible' => [
      'select[name="field_album_type"]' => ['value' => 'custom']
    ]
  ];
}
4
  • So far, you stated facts, without asking any explicit question. Since you are talking of code you wrote, you should show the code you wrote so far. Did you try the #states property for form fields?
    – avpaderno
    Commented May 4, 2017 at 18:56
  • @kiamlaluno thank you for your response. I have added the code , could you take a look ?
    – June
    Commented May 5, 2017 at 3:10
  • Themename should be admin theme name or code to be added to module
    – June
    Commented May 5, 2017 at 5:29
  • Keep in mind that theme hooks are invoked just when the theme is used for the currently rendered page. It's not that the hooks are invoked for all the enabled themes, contrary to modules.
    – avpaderno
    Commented May 5, 2017 at 6:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.