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();
      }

    }

  }

}
  • 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. – Mario Steinitz Mar 12 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. – Mario Steinitz Mar 12 at 23:16
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);
      }
    }
  }
}
  • That works. Was hoping to set values there without recursion but, that works. Thank you – s6712 Mar 13 at 2:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.