Koen
Koen

Reputation: 422

CakePHP 2.x: How to manually set validationErrors without a model?

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?

Upvotes: 2

Views: 1023

Answers (1)

Holt
Holt

Reputation: 37686

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
]);

Upvotes: 2

Related Questions