Search code examples
silverstripemodeladmin

Raise an error to the user via Model Admin & DataObject::onBeforeDelete()


Given I'm using Model Admin to manage a Customer DataObject and I have code like this, taken from the SilverStripe docs:

public function onBeforeDelete() {
    if ($this->Orders()->Count() > 0) {
        user_error("Cannot delete a Customer with Orders", E_USER_ERROR);
        exit();
    }
    parent::onBeforeDelete();
}

When I try to delete a Customer with Orders via Model Admin all I get is a JavaScript alert that says "An error occured while fetching data from the server. Please try again later" and a notification on the top right of

Error at line 42 of /var/www/mysite/code/dataobjects/Customer.php

How do I get a nice message to come back to Model Admin saying "Cannot delete a Customer with Orders"?


Solution

  • You could try this:

    public function canDelete($member=null) {
        if ($this->Orders()->Count() > 0) {
            return false;
        }
        return parent::canDelete($member);
    

    }

    This will remove the delete button altogether, but you'd have to make it clear to your users why in another way.