【问题标题】:Simple form without model in CakePHPCakePHP 中没有模型的简单表单
【发布时间】:2011-08-12 07:38:22
【问题描述】:

我正在尝试在产品页面中添加表单以请求附加信息。这是一个简单的表格,包含姓名、国家、电子邮件和问题字段。

我创建了这个tutorial,但我不喜欢仅仅为了小我需要制作新模型和控制器的想法。

所以我在 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));

并在products_controller.php中添加函数sendemail

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());
  }    
}

那么有什么方法可以正确验证表单,如果重定向后某些字段未填写,该字段将被设置为错误表单输入?另外如何将所有已填写的字段设置回表单?

感谢您的帮助!

【问题讨论】:

    标签: forms cakephp validation


    【解决方案1】:

    您不需要数据库表,但 CakePHPs 的验证支持天生就与模型相关联。通过创建一个虚拟模型并将您的验证规则存储在其中,您的代码将比任何替代方法都干净得多。

    要绕过使用表格,请将var $useTable = false; 添加到您的模型定义中。

    要在不保存的情况下进行验证,请调用 $this->MyModel->set($this->data);,然后调用 $this->MyModel->validates() 将执行检查并在表单中填充 $this->MyModel->validationErrors 以进行自动填充。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多