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.
EDIT 1
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');
$employee->save();
but still does not append the $employee
to the $sector
.
EDIT 2
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.