Skip to content

Instantly share code, notes, and snippets.

@prashantdsala
Last active September 12, 2024 12:51
Show Gist options
  • Save prashantdsala/e54dc46206d10334a9c603c5be1fa4ef to your computer and use it in GitHub Desktop.
Save prashantdsala/e54dc46206d10334a9c603c5be1fa4ef to your computer and use it in GitHub Desktop.
Alter Paragraphs form and apply conditional form fields - Drupal 10.3.x
<?php
// https://www.drupal.org/docs/drupal-apis/form-api/conditional-form-fields#s-table-of-contents
/**
* Implements hook_field_widget_single_element_[WIDGET_TYPE]_form_alter().
*/
function custom_field_widget_single_element_paragraphs_form_alter(&$element, &$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_product_details') {
/** @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 == 'product_details') {
$dependee_field_name = 'field_new_select_list';
$selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_field_name);
// Dependent fields.
$element['subform']['field_product_category_other']['#states'] = [
'visible' => [
$selector => ['value' => 'yed'],
],
];
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment