Add preview on collapsed paragraphs

Public

Warning message

We recommend you to assign at least one category to this snippet so you could easily navigate it in the future. Edit your snippet here.

Paragraphs add a preview using 'paragraphs_editor_preview' view mode when a item is collapsed

</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_field_widget_form_alter().
  3.  */
  4. function my_module_field_widget_form_alter(&$element, &$form_state, $context) {
  5. // Add an preview of the paragraphs content after collapse a paragraph.
  6. if ($context['instance']['widget']['type'] == 'paragraphs_embed') {
  7. $elements_children = element_children($element);
  8. foreach ($elements_children as $element_index) {
  9. if (is_numeric($element_index)) {
  10. if (isset($element[$element_index]['actions']['must_be_saved'])) {
  11. // Use the 'paragraphs_editor_preview' view mode.
  12. $preview = $element[$element_index]['#entity']->view('paragraphs_editor_preview');
  13. $preview_rendered = render($preview);
  14. if (!empty($preview_rendered)) {
  15. // The 'must_be_saved' index is the collapse function.
  16. $default_preview_html = isset($element[$element_index]['actions']['must_be_saved']['#markup']) ? $element[$element_index]['actions']['must_be_saved']['#markup'] : '';
  17. $new_markup .= '<p>' . $preview_rendered . '</p>' . $default_preview_html;
  18. $element[$element_index]['actions']['must_be_saved']['#markup'] = $new_markup;
  19. }
  20. }
  21. }
  22. }
  23. }
  24. }