Last active
September 12, 2024 12:51
-
-
Save prashantdsala/e54dc46206d10334a9c603c5be1fa4ef to your computer and use it in GitHub Desktop.
Alter Paragraphs form and apply conditional form fields - Drupal 10.3.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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