开发者

CakePHP form validation before sending post to the requested controller function

My validation is working as it stands, but I want to display the validation error prior to the search controller. I understand this might not be possible within the CakePHP framework.

I have a model plan.php. And in the plans_controller.php, I have a function called search().

My form calls search() as expected (because there is no search model):

echo $this->Form->create('Plan', array('action' => 'search'));

As it stands, when I submit my search, the errors are displayed and the url changes to .../search, so no results are displayed ("There are 0 results for that search criteria", but the correct validation errors are displayed below required form fields.

I do not want the .../search url to be displayed. I want the form to "halt" and just display the validation errors w开发者_Python百科/out changing the url to the search function.

I am calling the search form within an element because the search form displays on several different pages.

To sum this up: The search form should validate w/out changing the url path to the controller action name of the search. Of course, the validation is done IN the search() and plan.php model, so I just don't know how to work around this and wondering if its even possible.


You can use the validates() method of the model to check whether it validates and then redirect back.

Assuming your model is called Plan, this would be your controller

$errors = array();
if (!$this->Plan->validates($this->data)) {
   //errors occured
   $errors = $this->Plan->invalidFields();
   $this->Session->save('Plan.errors', $errors);
   $this->redirect('/plans');
}

And in your view.

if ($this->Session->check('Plan.errors')) {
   $errors = $this->Session->read('Plan.errors');
   $this->Session->delete('Plan.errors'); //don't want it again

}

In both cases, make sure Session helper/component is actually assigned to your view and controller


OK. Cracked out a working solution w/ implode, but now my errors are only displayed in the default layout and no longer under the form fields where that belong.. So now I need to know how to get the errors back below the form fields..

Working code:

...else {
          $errors = $this->Plan->invalidFields();
          $error_messages = implode(' ',$errors);
          $this->Session->setFlash($error_messages);
          $this->redirect('/');
        }...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜