1

I'm trying to update the expiry field—based on an existing field (in this case classDate)—as soon as an entry is saved.

Based on this answer, the clever recursion code in carlcs' Auto Expire plugin, I was able to get it working with this code:

public function init()
{

craft()->on('entries.saveEntry', function(Event $event) {
    $entry = $event->params['entry'];

    if ($entry->section->name == "Classes")
    {
        $entry->expiryDate = $entry->classDate;

        static $recursionLevel = 0;

        if ($recursionLevel == 0)
         {
            $recursionLevel++;
            $saved =   craft()->entries->saveEntry($entry);
         }

    }


});
}

But that seems a little dirty because saveEntry is going to get called again.

Is there a better way to handle the recursion? Bob's answer here leads me to believe you can call craft()->elements->saveElement which won't raise the saveEntry event again but I couldn't get that to work.

What am I missing? Seems too easy...

2

I'm not sure if it's any less dirty, but another way you could do it would be:

public function init()
{
    craft()->on('entries.saveEntry', function(Event $event)
    {
        $entry = $event->params['entry'];

        if ($entry->section->name == "Classes")
        {
            craft()->db->createCommand()->update(
                'entries',
                array('expiryDate' => DateTimeHelper::formatTimeForDb($entry->classDate)),
                array('id' => $entry->id)
            );
        }
    });
}
2
  • Ah yes, db->createCommand-update... never thought about hitting the db "directly" but I like the idea! Simple. It works but the expiryDate is not matching up with the classDate. Looks like the db stores in UTC? I got it to work by doing array('expiryDate' => DateTimeHelper::formatTimeForDb($entry->classDate)) not sure if there's a better way? Jul 4 '15 at 4:51
  • Nope, that's the way to do it... I'l update the answer.
    – Brad Bell
    Jul 4 '15 at 13:53

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.