Thursday, November 13, 2014

cake3 validation in controller

It is possible show in a form the error messages with no model associated? Obviously using the Form helper.
I see validating-data, but I need some guidance about the feasibility automatically display errors like when work with a model

//view
<?=
    $this->Form->create(),
    $this->Form->input('name', ['label' => __('Name')]),
    $this->Form->input('email', ['label' => __('Email')]),
    $this->Form->input('subject', ['label' => __('Subject')]),
    $this->Form->input('message', ['label' => __('Message'), 'type' => 'textarea', 'rows' => '3']),
    $this->Form->button(__('Submit')),
    $this->Form->end()
?>

//controller
public function contact() {
        if ($this->request->is('post')) {
            $validator = new Validator();
            $validator
                ->validatePresence('email')
                ->notEmpty('email', __('This field is required.'))
                ->add('email', 'valid', ['rule' => 'email', 'message' => __('This field requires a valid email address.')])
                ->validatePresence('name')
                ->notEmpty('name', __('This field is required.'))
                ->validatePresence('subject')
                ->notEmpty('subject', __('This field is required.'))
                ->validatePresence('message')
                ->notEmpty('message', __('This field is required.'))
            ;
            $errors = $validator->errors($this->request->data);
            if (empty($errors)) {
                $this->Flash->success(__('Your data has been sent succesfully.'));
            } else {
                $this->Flash->error(__('Unable to sent your data.'));
            }
        }
}

best regards

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: