How to set a schedule task on "preUpdate" event


#1

I’m trying to set a delete date in the scheduler for objects, inwoken by the preUpdate event. The deletion date should be relative to a date field created in the object.
I’ve set up the service according to the documentation, but don’t have anny success in setting the task.

I would be really glad, if someone could show me the right direction to solve this problem.

Here is what I have so far:


<?php
namespace AppBundle\EventListener;
  
use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Event\Model\AssetEvent;
use Pimcore\Event\Model\DocumentEvent;
use \DateTime;
use \DateInterval;

class ObjectListener {
     
    public function onPreUpdate (ElementEventInterface $e) {
       
if ($e instanceof DataObjectEvent) {
            $fair = $e->getObject();
            if ($fair instanceof\Pimcore\Model\DataObject\Fair){
                $date = $fair->getDate();
                $date = $date->modify('+1 day');

                $schedule = new \Pimcore\Model\Schedule\Task();
                $schedule->setCid($fair->getId());
                $schedule->setCtype("object");
                $schedule->setAction("delete");
                $schedule->setDate($date);
                $schedule->setActive(true);
                $schedule->save(); 

                $fair->setPublished(true);
            }
        }
    }
}

#2

Have found a solution to modify the task’s date relative to an objects date field:


           ...
            if ($fair instanceof\Pimcore\Model\DataObject\Fair){
                $date = $fair->getDate();
                $deletedate = clone $date;
                $duration = new DateInterval('P2D');
                $deletedate = $deletedate->add($duration)->getTimestamp(); 
                $taskdata = ["cid"=>$fair->getId(),"ctype"=>"object","date"=>$deletedate,"action"=>"delete","active"=>true] ;
                $task = new \Pimcore\Model\Schedule\Task($taskdata);
                $tasks[] = $task;
                $fair->setScheduledTasks($tasks);
            }
           ...