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') ->execute(); foreach ($nids as $nid) { $node = DrupalnodeEntityNODE::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, ]); $paragraph->save(); $node->field_qs_and_as[] = $paragraph->id(); } $node->save(); }
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?
Sponsored by SupremePR