After reading cakePHP: how set error validation to input field manually in controller, I was wondering how to show a validationError from a controller if we use a form without a model?
So for example, we have a view checkSomething.ctp
, with a Form that we can submit.
echo $this->Form->create(false); // If we put "SomeModel" here, it would work.
echo $this->Form->input("myField");
And say we are on /Home/CheckSomething/
.
class HomeController extends AppController{
public function CheckSomething(){
// So manually validate a field
if(strlen($this->request->data["myField"]) < 5){
// myField is not valid, so we need to show an error near that field
$this->SomeModel->invalidateField("myField", "You must enter at least 5 characters");
// How to do this?
}
}
}
We cannot use a model here... How to set a validationError for a field without a model? How to manually invalidate a field that comes from such a form?
The easiest way would be to send the error to the view directly:
$errors = [];
if (strlen($this->request->data["myField"]) < 5) {
$errors['myField'] = 'You must enter at least 5 characters';
}
$this->set('errors', $errors);
And in your view:
echo $this->Form->create(false);
echo $this->Form->input('myField', [
'error' => isset($errors['myField']) ? $errors['myField'] : false
]);