1

I am using Drupal 8 and I have implemented a hook_cron to set a node field to NULL. Here is my code:

if ($lesson->field_lesson_ended_at->value < $current_time && $session_id && count($paragraphs) > 0) {
  $pids = [];
  foreach ($paragraphs as $paragraph) {
    $pids[] = $paragraph['target_id'];
  }
  $storage_handler = \Drupal::entityTypeManager()->getStorage('paragraph');
  $entities = $storage_handler->loadByProperties(['id' => $pids]);

  foreach ($entities as $entity) {
    try {
      $apiObj->forceDisconnect($session_id, $entity->get('field_session_connection_id')->value);
    } catch (Exception $e) {

    }
  }
  $storage_handler->delete($entities);
  $lesson->set("field_session_id", NULL);
  $lesson->save();
}

When cron task reaches these lines:

$lesson->set("field_session_id", NULL);
$lesson->save();

Throws the following error (capture from cron logs):

Error: Call to a member function getTranslation() on null in Drupal\Core\Entity\ContentEntityBase->hasTranslationChanges() (line 1430 of core\lib\DRupal\Core\Entity\ContentEntityBase.php)

Any ideas on how to solve this issue?

  • Could you provide a screenshot and a dpm before the exception is thrown an after? Because at first glance theres nothing wrong with your code. Also you can simplify loading the paragraphs by $storage_handler->loadMultiple($pids) and seems also that your $paragraphs variable is getted from a field, you can load paragraphs directly an avoid the storage load and the iteration by calling $paragraphs = $node->get('my_field')->referencedEntities(); this will return the full instance of paragraphs. – d70rr3s Jan 15 at 9:15
  • For more information about how paragraphs are loaded directly from the field, see \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList::referencedEntities – d70rr3s Jan 15 at 9:17
  • 1
    You shouldn't delete paragraphs manually. Remove them from the field and let the module clean up not used paragraphs, they might still be needed for older revisions. – 4k4 Jan 15 at 10:59
  • @4k4 you mean that can`t delete paragraphs programmatically? – Asatur Vardanyan Jan 15 at 12:03
  • I change line orders like this and it works as needed: $lesson->set("field_session_id", NULL); $lesson->save() $storage_handler->delete($entities); – Asatur Vardanyan Jan 15 at 12:05
0

Even if the cron job is working now after you changed the order, you might get the same error later when using the saved parent entity.

Don't delete referenced paragraph entities programmatically (now the last command after you've changed the order). The Entity Reference Revisions module is handling this automatically after all revisions referencing the paragraph are removed.

|improve this answer|||||

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.