0

Is there a preferred approach modifying values?

I need to modify a value when a node loads, but must use other values from the node. The code below causes recursion errors.

function zzzmodule_entity_load(array $entities, $entity_type_id) {

  foreach ($entities as $entity) {

    if ($entity_type_id === "node" && $entity->hasField('other_field')) {


      $t = $entity->title->value;
      $o = $entity->other_field->value;

      if (empty($o)) {

        $o2 = json_encode($t);

        $entity->set('other_field', $o2);
        $entity->save();
      }

    }

  }

}
2
  • You don't check, whether your other field already has the desired value. This would prevent saving/reloading the node. Also you may check, if a computed field is more suitable for your use case. So you don't have to save your node on load at all. Mar 12, 2019 at 22:51
  • PS.: DON'T ask for a preferred approach, as this might raise oppinuated answers. Such questions are considered off-topic for Drupal Answers. Instead, describe your use case (probably also why you like to do it), highlight your steps done so far as you already did, and describe the problems you faced. Then I'm sure you receive appropriate help. Mar 12, 2019 at 23:16

1 Answer 1

0

Your code works just remove the $entity->save(); and it works i have tested it:

function zzzmodule_entity_load(array $entities, $entity_type_id) {
  foreach ($entities as $entity) {
    if ($entity_type_id === "node" && $entity->hasField('other_field')) {
      $t = $entity->title->value;
      $o = $entity->other_field->value;
      if (empty($o)) {
        $o2 = json_encode($t);
        $entity->set('other_field', $o2);
      }
    }
  }
}
1
  • That works. Was hoping to set values there without recursion but, that works. Thank you
    – s6712
    Mar 13, 2019 at 2:40

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.