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; ... $paragraph->save(); $sector->set('field_employee', $paragraph); // here I don't know how to append to the sector $sector->save(); }
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.