2

I can't find a way for a section (a channel in this case) to require the use to enter an expiration date.

I know I could add a new field and require that field, but that would get rid of the default functionality of entry/expire date fields.

3 Answers 3

4

You could do this with a little custom plugin. All you need to do is to listen to onBeforeSaveEntry events and check if there's an expiryDate submitted.

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

    if($entry->section['handle'] == 'news' && $entry->type['handle'] == 'news')
    {
        if ($entry->expiryDate === null)
        {
            $event->params['entry']->addError('expiryDate', Craft::t('Expiration Date cannot be blank.'));
            $event->performAction = false;
        }
    }
});
2
  • Perfect example, that worked great. Naturally, I was hoping for something native, that wouldn't be dependent on anything coded into the template, but with settings or things. I'll work on it :)
    – AJP
    Apr 24, 2015 at 11:38
  • Does anyone have a Craft 3 example of this? or a plugin?
    – Green17
    Oct 17, 2018 at 9:26
1
    Event::on(
        Elements::class,
        Elements::EVENT_BEFORE_SAVE_ELEMENT,
        function (ElementEvent $event) {
            $element = $event->element;
            //IF CAREERS SECTION
            if ($element->section->id == 6) {
                //IF FIELD IS EMPTY
                if (!$element->expiryDate) {

  $event->params['entry']->addError('expiryDate', Craft::t('Expiration Date cannot be blank.'));
  $event->performAction = false;

                }
            }
        }
    );

Just not sure on this bit:

$event->params['entry']->addError('expiryDate', Craft::t('Expiration Date cannot be blank.'));

$event->performAction = false;

1

For Craft 3, I created a module and added this:

  \yii\base\Event::on(
        \craft\elements\Entry::class,
        \craft\base\Element::EVENT_BEFORE_SAVE,
        function (\craft\events\ModelEvent $e) {

            /* @var \craft\records\Entry $entry */
            $entry = $e->sender;

            //IF CAREERS ENTRY TYPE
            if ($entry->type == 'careers') {
                //IF "Expiry date" IS EMPTY
                if (!$entry->expiryDate) {

                    $entry->addError('expiryDate', 'Expiration date cannot be blank.');
                    $e->isValid = false;

                }
            }
        }
    );

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.