我有一个与问题模型和答案模型相关的项目模型。在项目/视图/我添加了一个表单来插入一个新问题,它工作正常。但是如果我发送带有错误的表单,它会在inside / question / add中验证。我希望在项目/视图/页面上显示这些验证错误。我怎么能这样做?
谢谢!
CODE:
function add() {
if (!empty($this->data)) {
$this->Question->create();
if ($this->Question->save($this->data)) {
$this->Session->setFlash(__('The question has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The question could not be saved. Please, try again.', true));
}
}
}
表格:
<?php echo $this->Form->create('Question', array('action' => 'add'));?>
<fieldset>
<legend><?php __('Add Question'); ?></legend>
<?php
echo $this->Form->input('text');
echo $this->Form->hidden('Project', array('value' => $project['Project']['id']));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
它们都很相似,因为它们是由Cake烘焙的。
答案 0 :(得分:1)
据我所知,您希望在视图页面上显示验证错误,而不是添加视图。
if ($this->Question->save($this->data)) {
$this->Session->setFlash(__('The question has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The question could not be saved. Please, try again.', true));
$this->Session->write('errors', $this->Question->validationErrors); //or you could use $this->Question->invalidFields()
$this->redirect(array('controller' => 'projects', 'action' => 'view', $this->data['Project']['id']));
}
现在查看echo($ this-&gt; Session-&gt; read('errors'));
答案 1 :(得分:1)
编辑:确定,为了确保正确的模型分离:因为你想在项目/视图页面上显示验证错误,你仍然需要将数据发布到projects / view / $ id(否则你将不得不处理重定向到推荐人)。您可以在Question模型中编写方法addQuestionForProject($ data),在其中移动保存代码,并在项目/视图控制器代码中调用该方法。
<?php echo $this->Form->create('Question', array('controller'=>'projects','action' => 'view',{your project id here}));?>
项目控制器
function view($id=null) { if(!$id)$this->redirect(array('action' => 'index')); if (!empty($this->data)) { if ($this->Project->Question->addQuestionForProject($this->data)) { $this->Session->setFlash(__('The question has been saved', true)); } else { $this->Session->setFlash(__('The question could not be saved. Please, try again.', true)); } } // read your project record here }
我不确定蛋糕是否可以在这种情况下自动检测到验证错误(它可能可以);但如果没有,您可以从addQuestionForProject传回错误并自行显示。
另一种方法是使用ajax调用,因此您可以直接将请求发送到问题/添加并返回错误数组(在xml,json或简单的html中),但您必须自己显示错误。 / p>
答案 2 :(得分:0)
我刚刚做了Ehtesham所说的并且它有效!
在questions_controllers.php中:
function add() {
if (!empty($this->data)) {
$this->Question->create();
if ($this->Question->save($this->data)) {
$this->Session->setFlash(__('The question has been saved', true));
$this->redirect($this->referer());
} else {
$this->Session->setFlash(__('The question could not be saved. Please, try again.', true));
$this->Session->write('question_error', $this->Question->invalidFields());
$this->redirect($this->referer());
}
}
}
projects_controller.php:
function beforeFilter () {
if ($this->Session->check('question_error')) {
$this->Project->Question->validationErrors = $this->Session->read('question_error');
$this->Session->delete('question_error');
}
}