I'm working on validation with Craft. I have a custom plugin that allows public submission. However, I want to make sure I can pass errors back to the template. The key is trying to make my code as "dynamic" as possible. Meaning I do not want to specify the errors one by one.
Here is my sample controller (keep in mind I don't care what the model says is required, trying to keep the code agnostic of the model.)
public function actionSave() {
// require a post request
$this->requirePostRequest();
// assign specific fields we are listening for
$post = craft()->request->getPost('fields');
// create a new Request model
$model = MyModel::populateModel($post);
// validate the model attributes
if ($model->validate()) {
// save the record
// redirect to posted url
}
$errors = $model->getAllErrors();
craft()->urlManager->setRouteVariables(array(
'errors' => $errors
));
}
Using $model->getAllErrors()
returns an array as listed below:
array
(
0 => 'Name cannot be blank.'
1 => 'Details cannot be blank.'
2 => 'Email is not a valid email address.'
)
How would I return that array to specific fields in my template like so:
{% if errors.email is defined ? errors.email | length %}
<div data-alert class="alert">
{{ errors.email }}
</div>
{% endif %}