-
-
Save mlncn/c79f0c2d8038ba4e4ba722af2ab00e22 to your computer and use it in GitHub Desktop.
Conditional fields in Paragraphs using the Javascript States API for modern Drupal
This file contains hidden or 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
/** | |
* @file | |
* Example code from https://agaric.coop/blog/conditional-fields-paragraphs-using-javascript-states-api-modern-drupal | |
*/ | |
/** | |
* Implements hook_field_widget_single_element_WIDGET_TYPE_form_alter(). | |
* | |
* Example of conditional fields in paragraphs for modern Drupal (10, 11, . | |
*/ | |
function nicaragua_field_widget_single_element_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_sections') { | |
/** @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 == 'embedded_image_or_video') { | |
$controlling_field_name = 'field_image_or_video'; | |
$selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $controlling_field_name); | |
// Dependent fields. | |
$element['subform']['field_image']['#states'] = [ | |
'visible' => [ | |
$selector => ['value' => 'Image'], | |
], | |
]; | |
$element['subform']['field_video']['#states'] = [ | |
'visible' => [ | |
$selector => ['value' => 'Video'], | |
], | |
]; | |
} | |
} | |
} | |
/** | |
* Implements hook_form_alter(). | |
* | |
* Example of conditional fields in node forms for modern Drupal (10, 11, . | |
*/ | |
function nicaragua_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { | |
if ($form_id == 'node_article_form' || $form_id == 'node_article_edit_form') { | |
$form['field_ image']['#states'] = [ | |
'visible' => [ | |
':input[name="field_image_or_video"]' => ['value' => 'Image'], | |
], | |
]; | |
$form['field_ video']['#states'] = [ | |
'visible' => [ | |
':input[name="field_image_or_video"]' => ['value' => 'Video'], | |
], | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment