2

Similar to the question here but for D8. I've managed to create the child paragraphs but failing to generate the parent paragraphs and attaching the child to them.

$questions = [];

foreach($data['questions'] as $question) {
    $answers = [];
    foreach($question['answers'] as $answer) {
        $correct = $answer['field_correct'] === 'Yes' ? 1 : 0;

        $answers[] = Paragraph::create([
            'type' => 'quiz_answers',
            'field_answer' => $answer['field_answer'],
            'field_correct' => $correct,
        ])->save();
    }

    $questions[] = Paragraph::create([
        'type' => 'quiz_question',
        'field_question' => $question['field_question'],
        'field_answers' => $answers,
    ])->save();
}


$new_submission = Node::create([
    'type' => 'quiz_submissions',
    'title' => 'Quiz Submission',
    'field_quiz' => $data['quizID'],
    'field_question_submission' => $questions,
]);
2

1 Answer 1

6

save() returns the status of the save operation, not the entity. And you probably don't need to save the paragraphs, saving the node should save new paragraphs automatically.

So you can try this version:

$questions = [];

foreach($data['questions'] as $question) {
    $answers = [];
    foreach($question['answers'] as $answer) {
        $correct = $answer['field_correct'] === 'Yes' ? 1 : 0;

        $answers[] = Paragraph::create([
            'type' => 'quiz_answers',
            'field_answer' => $answer['field_answer'],
            'field_correct' => $correct,
        ]);
    }

    $questions[] = Paragraph::create([
        'type' => 'quiz_question',
        'field_question' => $question['field_question'],
        'field_answers' => $answers,
    ]);
}


$new_submission = Node::create([
    'type' => 'quiz_submissions',
    'title' => 'Quiz Submission',
    'field_quiz' => $data['quizID'],
    'field_question_submission' => $questions,
]);
$new_submission->save();
2
  • Indeed, didn't need to save them. Works perfectly fine now. Apr 15, 2020 at 14:20
  • Very cool, that we can save paragraphs along with nodes, and no need to set $paragraph->id() as referenced value. Thanks Nov 5, 2020 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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