Skip to content

Instantly share code, notes, and snippets.

@carlcs
Created July 26, 2018 07:54
Show Gist options
  • Save carlcs/9713d0de4da8fca8535d1a99f806666b to your computer and use it in GitHub Desktop.
Save carlcs/9713d0de4da8fca8535d1a99f806666b to your computer and use it in GitHub Desktop.
<?php
namespace modules;
use Craft;
use craft\elements\Entry;
use craft\events\ModelEvent;
use DateTime;
use yii\base\Event;
class Module extends \yii\base\Module
{
/**
* Initializes the module.
*/
public function init()
{
// Set a @modules alias pointed to the modules/ directory
Craft::setAlias('@modules', __DIR__);
// Set the controllerNamespace based on whether this is a console or web request
if (Craft::$app->getRequest()->getIsConsoleRequest()) {
$this->controllerNamespace = 'modules\\console\\controllers';
} else {
$this->controllerNamespace = 'modules\\controllers';
}
parent::init();
// Custom initialization code goes here...
Event::on(Entry::class, Entry::EVENT_BEFORE_SAVE, [$this, 'autoExpireNewsEntries']);
}
/**
* Sets the expiration date for News entries on element save.
*
* @param ModelEvent $event
*/
public function autoExpireNewsEntries(ModelEvent $event)
{
$entry = $event->sender;
// Exit early if the entry being saved is not in the section or entry type
// that we are targeting
if (
!in_array($entry->sectionId, [4]) ||
!in_array($entry->getType()->id, [4, 5])
) {
return;
}
// Exit early if the field is not empty. Remove this if you want to override
// whatever is set in the edit entry form
if ($entry->expiryDate !== null) {
return;
}
// Calculate the new date
// $newDate = (new DateTime())->modify('+7 days 04:00');
// $newDate = (clone $entry->postDate)->modify('first day of next month 05:00');
// $newDate = $entry->myFieldHandle !== null ? $entry->myFieldHandle : $entry->postDate;
$newDate = new DateTime('2018-04-23 09:00');
// Set the new date. Element attributes like postDate and expiryDate can
// be set directly, if you want to set a custom date field here use
// $entry->setFieldValue('myFieldHandle', $newDate);
$entry->expiryDate = $newDate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment