How to pass a field value from a parent node to its entity referenced children nodes when saving the parent node form Drupal 8
Here is the scenario
I have a Company &gt; Department &gt; 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?
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-&gt;bundle() == 'department') {
    $dept_company_id = $node-&gt;DEPARTMENT_COMPANY_FIELD-&gt;target_id;
    foreach ($node-&gt;DEPARTMENT_EMPLOYEE_FIELD-&gt;referencedEntities() as $employee) {
      // Only update the employee company if it's different.
      if ($employee-&gt;EMPLOYEE_COMPANY_FIELD-&gt;target_id !== $dept_company_id) {
        $employee-&gt;EMPLOYEE_COMPANY_FIELD-&gt;target_id = $dept_company_id;
        $employee-&gt;save();
      }
    }
  }
}