s7a*_*ley 4 forms validation cakephp
我正在尝试在产品页面中添加表单以请求其他信息.它是名称,国家,电子邮件和问题字段的简单形式.
我创建了这个教程,但我不喜欢只需要小型表格的想法我需要制作新的模型和控制器.
所以我在view.ctp中添加表单
print $this->Form->create('', array('action' => 'sendemail'));
print $this->Form->input('name',array('label' => __('Name',true).':'));
print $this->Form->input('country',array('label' => __('Country',true).':'));
print $this->Form->input('email',array('label' => __('E-mail',true).':'));
print $this->Form->input('question',array('type' => 'textarea', 'label' => __('Your question',true).':'));
print $this->Form->end(__('Send', true));
Run Code Online (Sandbox Code Playgroud)
并添加功能sendemail
在products_controller.php
function sendemail(){
if(!empty($this->data)){
if($this->data['Product']['name'] && $this->data['Product']['country'] && $this->data['Product']['email'] && $this->data['Product']['question']){
// sending email
$this->Session->setFlash(__('Thanks, your qustion was send.', true), 'default', array('class' => 'message status'));
$this->redirect($this->referer());
} else {
// validation
$this->Session->setFlash(__('Fill all fiels', true), 'default', array('class' => 'message error'));
$this->redirect($this->referer());
}
} else {
$this->Session->setFlash(__('Error occurred', true), 'default', array('class' => 'message error'));
$this->redirect($this->referer());
}
}
Run Code Online (Sandbox Code Playgroud)
那么有没有办法如何正确验证表单,如果重定向后某些字段没有填充,这个字段将被设置为错误表单输入?另外,如何将所有已填充的字段重新设置为表单?
谢谢你的帮助!
小智 7
您不需要数据库表,但CakePHP验证支持本质上与模型相关联.通过创建虚拟模型并将验证规则存储在其中,您的代码将比任何替代方案更清晰.
要使用表格,请添加var $useTable = false;
到模型定义中.
要在不保存的情况下进行验证,请调用$this->MyModel->set($this->data);
然后调用以$this->MyModel->validates()
执行检查并填写$this->MyModel->validationErrors
表单中的自动填充.
归档时间: |
|
查看次数: |
6160 次 |
最近记录: |