1

So I want to edit date type filed on entry save, but I don't know how to format it. It times out on string and don't seem to accept DateTime objects either.

Event::on(
    Elements::class,
    Elements::EVENT_AFTER_SAVE_ELEMENT,
    function(ElementEvent $event) {
        if ($event->element instanceof \craft\elements\Entry) {
            $entry = $event->element;
            if($entry->sectionId == 16){
                $entry->rangeStart = date_create_from_format('d/M/Y:H:i:s', '01/01/2019:19:00:00');
                Craft::$app->elements->saveElement($entry);
            }
        }
});
1

The problem you have here is you are calling saveElement from EVENT_AFTER_SAVE_ELEMENT which is causing an infinite loop.

You need to set:

$entry->propagating = true;

Before calling the saveElement method.

Dates should be a PHP DateTime class, e.g:

$entry->rangeStart = new \DateTime('2019-04-10 19:00:00');
| improve this answer | |
  • Ahh I was so set on date that I didn't see the loop, however setting $entry->propagating = true; didn't help. I've switched to before save event instead and now it works. – Lukigi Apr 11 '19 at 10:41

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.