2

I would like to programatically populate a paragraph field with a default value for one of my content types.

I came up with the following solution:

use \Drupal\Node\NodeInterface;
use \Drupal\paragraphs\Entity\Paragraph;

function my_site_node_create(NodeInterface $node) {
    switch ($node->getType()){
        case 'my_content_type':
            $paragraph = Paragraph::create([
                'type' => 'references',  // paragraph type machine name
                'field_references_title' => [  // paragraph's field machine name
                    'value' => 'Some examples of what we have done' // body field value
                ],
            ]);
            $paragraph->save();

            $node->set('field_paragraphs_content', [
                [
                    'target_id' => $paragraph->id(),
                    'target_revision_id' => $paragraph->getRevisionId(),
                ],
            ]);
            break;
    }

}

This code seems to work but im worried I might be creating useless Paragraph-entities when the user doesn't save this node (because of the '$paragraph->save()').

How can I avoid this?

2

You should be able to rely on the auto-creating of new paragraphs, instead of assinging the ID, do not save the paragraph and assign it with 'entity' => $paragraph.

This should then actually save the paragraph when the node is saved.

0

Inspired in https://www.drupal.org/project/paragraphs_tools I created the next hook which worked for me. Basically instead for a $node->set it calls the appendItem from the paragraph field.

/**
 * Implements hook_entity_prepare_form().
 *
 * @param EntityInterface $entity
 * @param string $operation
 * @param FormStateInterface $form_state
 */
function example_module_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {
  $bundles = ['blockherotertiary', 'blockblogpost'];
  $entity_manager = \Drupal::entityManager();
  $langcode = $form_state->get('langcode');

  $field = $entity->get('field_blocks');
  $target_type = $field->getSetting('target_type');

  foreach ($bundles as $bundle_name) {
    // Create paragraph and display.
    $entity_type = $entity_manager->getDefinition($target_type);
    $bundle_key = $entity_type->getKey('bundle');

    /** @var FieldableEntityInterface $paragraphs_entity */
    $paragraphs_entity = $entity_manager->getStorage($target_type)->create(array(
      $bundle_key => $bundle_name,
      'langcode' => $langcode,
    ));

    // Field values.
    $field->appendItem($paragraphs_entity);
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.