Skip to content

Instantly share code, notes, and snippets.

@goldenflower
Created August 13, 2019 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldenflower/0a82fc4e6392e19f0fb428a47e09ffff to your computer and use it in GitHub Desktop.
Save goldenflower/0a82fc4e6392e19f0fb428a47e09ffff to your computer and use it in GitHub Desktop.
field-paragraph-condation
/**
* Implements hook_field_widget_WIDGET_TYPE_form_alter().
*/
function my_common_field_widget_entity_reference_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_paragarph') {
/** @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 == 'test_form') {
$dependee_field_name = 'field_select_type';
$selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_field_name);
// Dependent fields.
$element['subform']['field_upload']['#states'] = [
'visible' => [
$selector => ['value' => 'upload'],
],
];
$element['subform']['field_youtube']['#states'] = [
'visible' => [
$selector => ['value' => 'youtube'],
],
];
}
}
}
@goldenflower
Copy link
Author

Always remember
Good point above. To be specific, considering the hook name hook_field_widget_WIDGET_TYPE_form_alter:

If you're using the "Paragraphs Classic" widget: WIDGET_TYPE = entity_reference_paragraphs
If you're using the "Paragraphs Experimental" widget: WIDGET_TYPE = paragraphs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment