Drupal 9: Auto Injecting Paragraph Forms On Node Edit Pages

10th January 2021 - 9 minutes read time

I tried to do something the other day that I thought would be quite simple, but turned out to be really hard to get my head around. I had a Drupal 9 site with Paragraphs installed and I wanted a user to click a button on the node edit form and inject a particular Paragraph into a Paragraph field.

I found 2 solutions to this problem that solve it in slight different ways.

Piggy Back On Existing Events

After my initial struggles over trying to get this to work I decided to use a piggy back method. This essentially listens for the user interaction and then triggers the Paragraph add event that inserts the Paragraph into the field. The user interaction I was listening for was a user selecting different elements in a select list.

To get this working I added some JavaScript to the page, attached to the select list field called "field_type".

  1. function my_module_form_node_page_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
  2. {
  3. $form['field_type']['widget']['#attached']['library'][] = 'my_module/node';
  4. }

This

  1. node:
  2. js:
  3. js/piggy-back.js: {}
  4. dependencies:
  5. - core/drupal

This loads in the JavaScript file called piggy-back.js.

This file, seen below, is used to pull together the different events attached to the different Paragraph add buttons. When the user changes the field type select list an event is triggered, which in turn then triggers one of the paragraph events.

  1. (function ($, Drupal, drupalSettings) {
  2.  
  3. 'use strict';
  4.  
  5. Drupal.behaviors.bform = {
  6. attach : function(context, settings) {
  7. // Load the existing change event.
  8. var paragraphDetailEvents = $._data($("#field-paragraph-detail-add-more")[0], "events");
  9. var paragraphHeaderEvents = $._data($("#field-paragraph-header-add-more")[0], "events");
  10.  
  11. $('#edit-field-type').change(function(event) {
  12. let changeValue = $(this).val();
  13. if (changeValue == 1) {
  14. $.each(paragraphDetailEvents.mousedown, function () {
  15. this.handler(event);
  16. });
  17. }
  18. if (changeValue == 2) {
  19. $.each(paragraphHeaderEvents.mousedown, function () {
  20. this.handler(event);
  21. });
  22. }
  23. });
  24. }
  25. };
  26.  
  27. })(jQuery, Drupal);

You can probably adapt this code to suit your needs, but this is a simple solution to the problem that actually produces the intended result.

Inject Paragraph Button Ajax Callback

Whilst the piggy back method worked, what I really wanted to do was have full control over the ajax stream and resulting response. Looking through the Paragraphs module led me to a mix of different code that seemed not to actually produce the needed result. After running through the code a few times I was able to extract the needed components into a single module.

The first thing that is needed here is a form element to control the injection of the Paragraph entity form into the page. This is handled by a submit button that is injected into the node edit form using the hook_form_node_page_form_alter() hook. The button is injected next to a field called "field_type", but I have abstracted this out so that you can move this to anywhere you need. The Paragraph field name has also need abstracted into a variable at the top so you can point this at any Paragraph field you need to. The references to the 'add more' field and class names are to integrate with the Paragraph form itself.

    1. function my_module_form_node_page_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
    2. {
    3. $paragraphFieldName = 'field_paragraph';
    4. $injectParagraphFieldName = 'field_type';
    5.  
    6. $paragraphField = NestedArray::getValue($form, [$paragraphFieldName]);
    7.  
    8. $injectParagraphField = NestedArray::getValue($form, [$injectParagraphFieldName]);
    9.  
    10. $injectParagraphField['inject_paragraph'] = [
    11. '#type' => 'submit',
    12. '#name' => 'field_type_my_module',
    13. '#value' => t('Inject Paragraph'),
    14. '#attributes' => ['class' => ['field-set-selection-submit']],
    15. '#limit_validation_errors' => [array_merge($paragraphField['#parents'], [$paragraphFieldName, 'add_more'])],
    16. '#submit' => [['\Drupal\my_module\InjectParagraph', 'addParagraphSubmit']],
    17. '#ajax' => [
    18. 'callback' => ['\Drupal\my_module\InjectParagraph', 'addParagraphAjax'],
    19. 'wrapper' => str_replace('_', '-', $paragraphFieldName) . '-add-more-wrapper',
    20. 'effect' => 'fade',
    21. 'progress' => [
    22. 'type' => 'fullscreen',
    23. ]
    24. ],
    25. ];
    26. NestedArray::setValue($form, [$injectParagraphFieldName], $injectParagraphField);
    27. }

    This button will act as the user input and wrap submit and ajax handlers around the element. In order for this submit button to work correctly it needs three things.

    1. A submit callack, which is called when the button has been submitted. In the field above this has been created as a static method and then put into a class.
    2. A limit_validation_errors. This will, as the name suggests, limit the number of validation errors that the form will produce. In this case we are telling Drupal to only validate the paragraph field for errors and to perform a 'partial submit' on the rest of the form.
    3. An Ajax callback, which is called when the button is submitted, after the submit handler. Again, this has been abstracted into a separate class.

    The class that contains the addParagraphSubmit and addParagraphAjax handlers is where the meat of the action happens. Here is the class in full and I have added lots of comments to show what is happening.

    1. <?php
    2.  
    3. namespace Drupal\my_module;
    4.  
    5. use Drupal\Component\Utility\NestedArray;
    6. use Drupal\Core\Field\FieldStorageDefinitionInterface;
    7. use Drupal\Core\Form\FormStateInterface;
    8. use Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget;
    9.  
    10. class InjectParagraph {
    11.  
    12. public static function addParagraphSubmit(array $form, FormStateInterface $form_state)
    13. {
    14. // Set the paragraph field in question.
    15. $paragraphFieldName = 'field_paragraph';
    16.  
    17. // Extract the paragraph field from the form.
    18. $element = NestedArray::getValue($form, [$paragraphFieldName, 'widget']);
    19. $field_name = $element['#field_name'];
    20. $field_parents = $element['#field_parents'];
    21.  
    22. // Get the widget state.
    23. $widget_state = static::getWidgetState($field_parents, $field_name, $form_state);
    24.  
    25. // Inject the new paragraph and increment the items count.
    26. $widget_state['selected_bundle'][] = 'detail';
    27. $widget_state['items_count']++;
    28.  
    29. // Update the widget state.
    30. static::setWidgetState($field_parents, $field_name, $form_state, $widget_state);
    31.  
    32. // Rebuild the form.
    33. $form_state->setRebuild();
    34. }
    35.  
    36. public static function addParagraphAjax(array $form, FormStateInterface $form_state)
    37. {
    38. // Set the paragraph field in question.
    39. $paragraphFieldName = 'field_paragraph';
    40.  
    41. // Extract the paragraph field from the form.
    42. $element = NestedArray::getValue($form, [$paragraphFieldName, 'widget']);
    43.  
    44. // Update the field with the needed Ajax formatting.
    45. $delta = $element['#max_delta'];
    46. $element[$delta]['#prefix'] = '<div class="ajax-new-content">' . (isset($element[$delta]['#prefix']) ? $element[$delta]['#prefix'] : '');
    47. $element[$delta]['#suffix'] = (isset($element[$delta]['#suffix']) ? $element[$delta]['#suffix'] : '') . '</div>';
    48.  
    49. // Clear the add more delta from the paragraph module.
    50. NestedArray::setValue(
    51. $element,
    52. ['add_more', 'add_more_delta', '#value'],
    53. ''
    54. );
    55.  
    56. // Return the paragraph element.
    57. return $element;
    58. }
    59.  
    60. public static function getWidgetState(array $parents, $field_name, FormStateInterface $form_state) {
    61. return NestedArray::getValue($form_state->getStorage(), array_merge(['field_storage', '#parents'], $parents, ['#fields', $field_name]));
    62. }
    63.  
    64. public static function setWidgetState(array $parents, $field_name, FormStateInterface $form_state, array $field_state) {
    65. NestedArray::setValue($form_state->getStorage(), array_merge(['field_storage', '#parents'], $parents, ['#fields', $field_name]), $field_state);
    66. }
    67. }

    If you are familiar with the Paragraph module then you will recognise some of this code as parts have been taken from the Paragraph module. I needed to copy and paste some of the code needed here as they are set to be private or protected methods within the Paragraph widget and are therefore inaccessible. I have left some of the detail out here as the code will only inject one type of Paragraph into the form. This should however, be enough information to get you going if this is what you are wanting to do. The form state is passed to both functions so you should be able to inspect it and see what has been selected and then adapt the code accordingly.

    Essentially the sequence of events is as follows.

    1. The user clicks the new 'Inject Paragraph' button on the node form.
    2. An ajax call is made to Drupal.
    3. The Drupal form processing is started.
    4. The submit handler called addParagraphSubmit is triggered. In this step we inject the placeholder for the Paragraph entity to be added to the form using a placeholder widget with the property of 'selected_bundle'. The Paragraph entity we added is called 'detail'.
    5. The internal Paragraph render functions are called, which then populate the form elements with the blank Paragraph entity forms.
    6. The ajax handler called addParagraphAjax is triggered. In this step the empty Paragraph entity form is present, just are just wrapping it in some HTML so that the form acts in the same way as the normal Paragraph form does.

    As you can see, both the submit handler and the ajax handler are needed here in order to allow the Paragraph entity form to be correctly injected. Without the submit hanlder being called the ajax handler doesn't do anything. Making sure both of these handlers is called is down to the limit_validation_errors setting in form element we injected. If this element is missing then only the ajax handler is called, which is too late in the process to allow the Paragraph entity to be added. I hadn't used this setting before and so wasn't sure what it did so I may even write an entirely separate article just on this setting as it changes how ajax callbacks work quite drastically.

    All of the code above has been put together after hours of debugging, experimentation and tweaking. I hope it is useful to you.

    Add new comment

    The content of this field is kept private and will not be shown publicly.