Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Conditional fields in Paragraphs using the Javascript States API for Drupal 8
/**
* @file
* Example code from http://agaric.com/blogs/conditional-fields-paragraphs-using-javascript-states-api-drupal-8.
*/
/**
* Implements hook_field_widget_WIDGET_TYPE_form_alter().
*
* Example of conditional fields in paragraphs for Drupal 8.
*/
function nicaragua_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_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') {
$dependee_field_name = 'field_image_or_video';
$selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_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 Drupal 8.
*/
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