开发者

CakePHP validation error messages - how to pass them around?

开发者 https://www.devze.com 2023-02-01 18:17 出处:网络
Please note: I\'m not trying to do this anymore, because I found an alternative, but it may be useful in the future to know the answer.

Please note: I'm not trying to do this anymore, because I found an alternative, but it may be useful in the future to know the answer.

I have a form tha开发者_运维问答t is in a view (index.ctp) associated with the index() action on a controller. That form should post data to another action, contact(), in the same controller. This second action doesn't have a view, it's just to process the information and redirect the user according to the outcome. This action is doing the validation and redirecting the user to the referer (index in this case) in case of an error, and then the error should be displayed in index. Note that the model doesn't use a database table, but it's used only to define validation rules.

The validation is taking place correctly and reporting the expected errors. In order to retrieve the errors after the redirect, it writes the $this->ModelName->invalidFields() array to a session variable that is retrieved on the index() action after the redirection. This array is passed on to the $errors variable to the view. Now comes the problem. The errors, although being passed correctly between redirects, aren't getting attached to the respective forms. How can I accomplish this? The form has all the conventional names, so it should be automatic, but it isn't.

Here's part of the relevant code:

Index view:

echo $this->Form->create('Contact', array('url' => '/contacts/contact'));
echo (rest of form) ...
echo $this->Form->end(__('send message', true));

Contacts controller:

function index() {

    if ($this->Session->check('Contact.errors')) {
        $this->set('errors', $this->Session->read('Contact.errors'));
    }
}

function contact() {

    if (!empty($this->data)) {
        $this->Contact->set($this->data);

        if ($this->Contact->validates()) {
            (send the email)
        }
        else {
            $this->Session->write('Contact.errors', $this->Contact->invalidFields());
            $this->redirect($this->referer);
        }
    }
}


I don't think it's a good idea to write the validation errors in a session variable. I'm no CakePHP expert, but I don't think that's the way you are supposed to do it. All your forms should point to the same url you are on, so the data that the user has entered will not be lost.

Could you add some code to your question?

0

精彩评论

暂无评论...
验证码 换一张
取 消