1

I want to do some server side checks to see if the entry should be saved or not.

In my plugin I have something like that

Event::on(
    Elements::class,
    Elements::EVENT_BEFORE_SAVE_ELEMENT,
    function(ElementEvent $event) {
        if ($event->element instanceof \craft\elements\Entry) {
            $entry = $event->element;
            if ( $entry->sectionId == 5 ) {
                $entry->enabled = 0;
            }
        }
    });

This works but what I want is for the entry to not be saved rather then be disabled. Something I could achive on the user model with:

$event->isValid = false;

Is there a way to withhold the entry from saving? The only other solution I can think if is to make the tests in the AFTER event and delete it if not passing the condition.

  • Just a heads up in case no solution is found: Deleting an element after it's saved would seriously screw up your database's indexes (auto-increment columns mostly), though you wouldn't really notice it since craft would be managing all things SQL-related. – Campiotti Dec 12 '19 at 14:19
2

This functionality or behavior is a bit confusing. The Elements Service has its own Events for saving Elements, specifically... but because ultimately Elements are just Yii Models, they have a discrete EVENT_BEFORE_SAVE event that uses a ModelEvent, which has the isValid property.

This is the point in the life-cycle where saving the Element can be prevented. The beforeSave method is called on the Element being saved (usually overridden in the actual Element implementation, but called + returned at the end of the subclass's method, like parent::beforeSave($isNew)), and the resulting boolean ($event->isValid) determines whether or not the saving continues.

So, in short: You can listen directly to the Entry's EVENT_BEFORE_SAVE event to prevent it from saving:

use craft\elements\Entry;
use craft\events\ModelEvent;

use yii\base\Event;

Event::on(
    Entry::class,
    Entry::EVENT_BEFORE_SAVE,
    function(ModelEvent $event) {
            $entry = $event->sender;
            if ($entry->sectionId == 5) {
                $event->isValid = false;
            }
        }
    });
| improve this answer | |

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.