How to pass a field value from a parent node to its entity referenced children nodes when saving the parent node form
Question
Drupal 8
Here is the scenario
I have a Company > Department > Employee… in that hierarchy.
Companies are already created previously.
On the Department node add form, there is an entity reference field to reference a Company. On that same Department node form, there is another Entity Reference field that leverages Inline Entity Form to add + reference Employee nodes on the fly. These Employee nodes also have a Company entity reference field.
The goal is to pass the Company field value from the Department node to the referenced Employee nodes when the Department form is saved.
I figure this may be accomplished with the Business rules module, and/or a hook form alter. Tried both without any traction. Any tips?
Solution
One option is to use hook_ENTITY_TYPE_update() and hook_ENTITY_TYPE_insert().
// Top of .module
use Drupal\node\NodeInterface;
function MYMODULE_node_update(NodeInterface $node) {
_MYMODULE_set_department_employee_company($node);
}
function MYMODULE_node_insert(NodeInterface $node) {
_MYMODULE_set_department_employee_company($node);
}
function _MYMODULE_set_department_employee_company(NodeInterface $node) {
if ($node->bundle() == 'department') {
$dept_company_id = $node->DEPARTMENT_COMPANY_FIELD->target_id;
foreach ($node->DEPARTMENT_EMPLOYEE_FIELD->referencedEntities() as $employee) {
// Only update the employee company if it's different.
if ($employee->EMPLOYEE_COMPANY_FIELD->target_id !== $dept_company_id) {
$employee->EMPLOYEE_COMPANY_FIELD->target_id = $dept_company_id;
$employee->save();
}
}
}
}