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.

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;
        }
    }
});
  • 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 '15 at 11:38
  • Does anyone have a Craft 3 example of this? or a plugin? – Green17 Oct 17 '18 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;

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.