Reputation: 1989
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"?
Upvotes: 0
Views: 1093
Reputation: 6464
You can show a message in the CMS default error message style on the right top corner. The simple trick is to return an error header, which the ajax call knows to handle.
public function onBeforeDelete() {
if ($this->Orders()->Count() > 0) {
header("HTTP/1.1 403 Sorry you can not delete a customer with orders");
exit;
}
parent::onBeforeDelete();
}
If you use such messages more, the best way is to put a function in a custom siteconfig extension class and call it each time to handle the situation. For example, put the following code in one of your common functions file or in a class like class SiteConfigExtension extends DataExtension.
public function popupCMSError($message='The action is not allowed', $errorCode=403)
{
header("HTTP/1.1 $errorCode $message");
exit;
}
Then, you can always call it in situations like yours or for any other purposes in the following way (if in siteconfig class for example):
singleton('SiteConfig')->popupCMSError("Sorry your custom message here");
Note: I used HTTP error 403 here for illustration only. You can use other headers as well. The same style is used in Silverstripe Framework core to display CMS errors.
Upvotes: 3
Reputation: 734
As well as overloading the validate function, you can throw a ValidationException
.
public function onBeforeDelete() {
if ($this->Orders()->Count() > 0) {
throw new ValidationException("Cannot delete a Customer with Orders");
}
parent::onBeforeDelete();
}
ValidationException
is trapped by the form processing code and should show the error as one of those pop-up message in the top-right.
Upvotes: 4
Reputation: 1113
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.
Upvotes: 1