I have a node (e.g. a business "company") with a paragraph referenced field (suppose business "sector", with multiple fields). This paragraph has in its fields a reference to another paragraph (suppose "employee" with multiple fields, one of this is a reference to a taxonomy term). In a hook_form_submit(), with $form and FormStateInterface $form_state as parameters, I need to programmatically associate multiple employees paragraph to a sector paragraph.

$node = Node::load($id);
$sector = Paragraph::load($node->get('field_sector')->target_id);

 * List of taxonomy terms loaded elsewhere.
 * I've added a custom elment to the select with "_all" employees
 * in order to associate programmatically all the employees to the $sector.
 * @var array $employees
foreach ($employees as $employee) {
    $paragraph = Paragraph::create([
        'type' => 'employee',
    $paragraph->set('field_name', $employee->get('field_name')->value);
    $paragraph->set('field_age', $employee->get('field_age')->value);

    $sector->set('field_employee', $paragraph); // here I don't know how to append to the sector

I tried to associate each $employee to the $sector but with $sector->set('field_employee', $paragraph); syntax or with $sector->appendItem($paragraph), that works for nodes, it doesn't work.

Is there a way to programmatically add one paragraph to another?

Visualizing the question, in the image below, when I save the entity with custom option "All employees" (_all) selected, I'd like to attach all the 4 paragraph employees associated to the "a selected sector" paragraph (removing _all).

Thanks in advance.


I saw the suggested answer Programmatically append multiple paragraphs to entity reference field on node but it resolve how to attach a Paragraph to a $node, not a Paragraph to a Paragraph of the $node.

I've try also this:

$employee->setParentEntity($sector, 'field_of_reference');

but still does not append the $employee to the $sector.


I've try to follow the suggested posts but I can't figure how to adapt that code inside a hook_form_submit().

Thanks anyway to all, I think its a bad construction on my code.

This is the entity form with paragraphs inside


1 Answer 1


The problems start with how you load the paragraph. You can't load it like a stand-alone entity:

$sector = Paragraph::load($node->get('field_sector')->target_id);

Instead load it via the reference field:

$sector = $node->get('field_sector')->entity;

Then you can add newly created paragraphs without saving, also nested ones, and when you are ready you can save the parent entity.

See Create nested paragraphs programmatically

  • @robdex Did this work for you?
    – NKP
    Sep 12, 2022 at 8:24

Your Answer

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

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