在CakePHP中没有模型的简单形式 [英] Simple form without model in CakePHP
问题描述
我正在尝试在产品页面中添加表单以请求其他信息。
I'm trying to add form for request of additional information in product page. It's simple form with name, country, email and question fields.
我创建了这个教程,但我不喜欢只是为小形式的想法,我需要使新的模型和控制器。
I founded this tutorial , but i don't like idea that just for small form I need make new model and controller.
因此我在view.ctp中添加表单
So i add form in 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));
并在<$ c中添加函数 sendemail
$ c> products_controller.php
and add function sendemail
in 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());
}
}
因此,有什么办法如何正确验证表单并且如果某些字段在重定向后未填充,此字段将设置为错误形式输入?
So is there any way how to validate the form properly and if some field isn't fill after redirection this field will be set as error form input? Also how can I set all already filled fields back to form?
推荐答案
方案
您不需要数据库表,但CakePHP验证支持固有地绑定到模型。通过创建一个虚拟模型并在其中存储您的验证规则,您的代码将比任何替代方法更清洁。
You don't need a database table, but CakePHPs validation support is inherently tied to models. Your code is going to be a lot cleaner than any alternative by creating a dummy model and storing your validation rules in it.
要使用表格,请将 var $ useTable = false;
添加到模型定义中。
To get around using a table, add var $useTable = false;
to your model definition.
要保存而不保存,请调用 $ this-> MyModel-> set($ this-> data);
然后调用 $ this-> MyModel-> validates()
将执行检查并填充 $ this-> MyModel-> ; validationErrors
用于表单中的自动填充。
To validate without saving, call $this->MyModel->set($this->data);
and then a call to $this->MyModel->validates()
will perform the check and populate $this->MyModel->validationErrors
for automagic population in the form.
这篇关于在CakePHP中没有模型的简单形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!