0

I'm creating some additional functionality for a module and as a part of that I'd like to use the form state API to conditionally show and hide some media field elements. I've been able to toggle the visibility of a textfield using a select field but when I attempt to do the same for a media field, it doesn't work and I'm not sure why.

Here's my code:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if (($form_id == 'node_article_form') || ($form_id == 'node_article_edit_form')) {

    // Add Conditional Fields Display.
    $form['body']['#states'] = [
      'visible' => [
        ':input[name="field_article_type"]' => ['value' => $html_tid],
      ],
    ];


    $form['field_local_video']['#states'] = [
      'visible' => [
        ':input[name="field_article_type"]' => ['value' => $video_tid],
      ],
    ];

  }
}

Among the above fields

body --> Default Body Field

field_local_video --> Media Entity Reference Field

field_article_type --> Taxonomy term field.

Similar question with different approach

3
  • Can you add the HTML generated by Drupal for the relevant form? If it's not working, something is named incorrectly, and that should be obvious by looking at the HTML. Commented Jun 12 at 8:08
  • @PatrickKenny > something is named incorrectly you are absolutely correct, my code was correct but there was typo which caused the issue. Found after multiple days of debugging. Thanks Commented Jun 12 at 9:51
  • Glad you solved it! Commented Jun 12 at 11:12

0

Browse other questions tagged or ask your own question.