This is an example of how to hide dependent - conditional fields in Paragraphs using the Javascript States API (https://www.drupal.org/docs/drupal-apis/form-api/conditional-form-fields) for Drupal 9.
For this example here I have a custom paragraph type: call_to_action and I want to show the field that you can select a different bg color (field_bg_color) only for 2 out of 4 of the values of the field_display_format field. So when a user select for the "Display Format" field "Circle Image Left" or "Circle image Right" then the "Bg Color" field becomes visible and lets you select a different bg color for the paragraph.
<?php
/**
* @file
* Primary module hooks for SHH Paragraphs module.
*/
/**
* Implements hook_field_widget_WIDGET_TYPE_form_alter().
*
* Example of conditional fields in paragraphs for Drupal 8.
*/
function pixelthis_paragraphs_field_widget_paragraphs_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
/** @var \Drupal\field\Entity\FieldConfig $field_definition */
$field_definition = $context['items']->getFieldDefinition();
$paragraph_entity_reference_field_name = $field_definition->getName();
if ($paragraph_entity_reference_field_name == 'field_paragraphs') {
/** @see \Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget::formElement() */
$widget_state = \Drupal\Core\Field\WidgetBase::getWidgetState($element['#field_parents'], $paragraph_entity_reference_field_name, $form_state);
/** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
$paragraph_instance = $widget_state['paragraphs'][$element['#delta']]['entity'];
$paragraph_type = $paragraph_instance->bundle();
// Determine which paragraph type is being embedded.
if ($paragraph_type == 'call_to_action') {
$dependee_field_name = 'field_display_format';
$selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_field_name);
// Dependent fields.
if (!isset($element['subform']['field_bg_color']['#states'])) return;
// Dependent fields.
$element['subform']['field_bg_color']['#states'] = [
'visible' => [
[
$selector => ['value' => 'circle_image_left'],
],
'or',
[
$selector => ['value' => 'circle_image_right'],
],
],
];
}
}
}
This is a modified version of the code found here: https://gist.github.com/dinarcon/ea67da074fca0c19c25b85e244262219