1

I got a bit of help with this from Discord. Here is what I have:

Event::on(Entry::class, Element::EVENT_AFTER_SAVE, function (ModelEvent $e) {
  $entry = $e->sender;

  if ($entry->sectionId !== 7) {
    return;
  }

  if ($entry->typeId !== 9) {
    return;
  }

  $parent = $entry->getParent();

  if (!$parent) {
    return;
  }

  $parent->dateUpdated = $entry->dateUpdated;
  Craft::$app->getElements()->saveElement($parent);
});

The trouble is that the if conditions aren't working; with the above code, the parent entry is not updated. As soon as I remove those two if statements, the code works and the parent is updated. However, I don't want to run this on all sections/structures.

Does anyone know what might be going wrong? I've checked the section/type IDs many times :)

Thanks in advance!

1

This is because you are using !== to compare your sectionId and typeId.

In PHP using this will compare the value as well as the type.

Here, since you are comparing an int with a string, although the value is a match, the type isn't, your first conditional is failing and nothing happens.

Try using != instead:

Event::on(Entry::class, Element::EVENT_AFTER_SAVE, function (ModelEvent $e) {
  $entry = $e->sender;

  if ($entry->sectionId != 7) {
    return;
  }

  if ($entry->typeId != 9) {
    return;
  }

  $parent = $entry->getParent();

  if (!$parent) {
    return;
  }

  $parent->dateUpdated = $entry->dateUpdated;
  Craft::$app->getElements()->saveElement($parent);
});

1
  • Oh boy...that was easy. Thank you!!
    – mupoftpr
    Aug 24 at 22:24
0

I'd start by var_dumping or logging the value of sectionId and TypeId, since its not saving parent, it hits one of the if statements and returns before doing anything.

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.