Where to put the error code in a MVC model to display error to user
I have a simple setup in Yii with a Model, View and a Controller to manage a DB table. (created with Gii)
When the user presses the delete button I want to validate this request with some rules of my own and if there is an error display this to the user.
Should I put validation method in the Model,开发者_如何学Python call this validation from the controller delete method. But then I am not sure how I get a popup to appear on the webpage.
I can't speak specifically for Yii, but in general with PHP 5.3 a good practice would be to throw errors from models (mind you, human readable ones) and then catch them when you call the models in your controllers. The controllers can then pass along a list of errors to the views, which would be responsible for displaying the error(s) to the users.
<?php
class Model {
public function doImportantStuff() {
//Do stuff
if(true) {
throw new Exception('Important stuff could not be completed due to this important error.');
}
}
}
class Controller {
public function index() {
$data = array();
$crucial = new Model();
try {
$crucial->doImportantStuff();
} catch(Exception $e) {
$data['errors'][] = $e;
}
}
}
//And in the view
<?php if($data['errors']): ?>
<?php foreach($data['errors'] as $error): ?>
<p><?= $error->getMessage(); ?></p>
<?php endforeach; ?>
<?php endif; ?>
You would want to put your validation rules in your model, in the rules method, which Gii should have created for you. You can use a pre-defined validation rule or create your own, see here. You would probably want to define a "scenario" attribute for this delete function and then you can restrict your custom rule to that delete action.
The action would be defined in your controller, -- if you used Gii for CRUD creation you should have sample code to reference.
In your view, you could either use CActiveForm::error() to display an error on the page or call getErrors() to retrieve the errors to create a custom error state (with js or css, etc.).
Another option would be to define an onsubmit function with js that does an ajax call to validate the delete function prior to submit. (That ajax call would be made to a controller function and you would still want to validate in the model as well before deleting.)
精彩评论