I have a paragraph type that contains a text field and a text format field. I also have a content type that takes an unlimited number of paragraphs of this type.

The paragraph type is called 'questions_and_answers' and the two fields are 'field_question' and 'field_answer'. I'd like to be able to programmatically append 'questions_and_answers' paragraphs to a content type.

In the example below I'm grabbing the content from a 'double' field and importing them into the paragraph reference field. Here's my code so far.

    $nids = \Drupal::entityQuery('node')
        ->condition('type', 'faq')
    foreach ($nids as $nid) {
        $node      = \Drupal\node\Entity\NODE::load($nid);
        $questions = $node->field_questions_and_answers->getValue();
        foreach ($questions as $question) {
            $q         = $question['first'];
            $a         = $question['second'];
            $paragraph = Paragraph::create([
                    'title'          => $q,
                    'type'           => 'questions_and_answers',
                    'field_question' => $q,
                    'field_answer'   => $a,
            $node->field_qs_and_as[] = $paragraph->id();

However when I perform this action the node gets a number of question paragraphs added but they're completely empty and they can't even be deleted. What am I missing? How do you append multiple paragraphs you created to an entity reference field on a node?


When you add a paragraph you also need to pass the revision id:

  $node->field_qs_and_as[] = [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  • Yes, I assume field_qs_and_as is an entity_reference_revisions field because paragraphs doesn't support core entity_reference fields. – Berdir May 18 '17 at 19:03
  • Hi, I have added like this, I can see all paragraphs on node view but when I edit node I can edit only last paragraph. Do you know why? – tasqyn Sep 6 '19 at 4:57

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.