【发布时间】:2012-10-12 08:05:12
【问题描述】:
我想以 zend 形式显示一个由异常引发的简单异常消息。我检查数据库中是否存在重复记录,如果退出,那么我想抛出一个错误,说明数据库中已经存在具有该名称的记录。我想在 add.phtml 文件中显示在记录名称文本字段之后。
这就是我想要做的:
在我的控制器中:
public function addAction()
{
try {
$records->validateDuplicateRecords($recordTitle);
if ($form->isValid()) {
//doing all the stuff like saving data to database
}
} catch (\Exception $e) {
echo $e->getMessage(); //Not sure with this part
}
}
以及我正在检查重复记录的班级:
records.php
public function validateDuplicateRecords($recordTitle)
{
//fetching all titles from database
//comparing with $recordTitle using foreach and if
//all these here in the loop works, I am giving the skeleton of my code
foreach($records as $record)
{
if($record == $recordTitle) {
throw new \Exception("Record with title '$recordTitle' already exists");
}
return true;
}
}
所以我基本上就是这样做的,我知道这个 try and catch 是如何与纯 php 的东西一起工作的,但我不知道如何在 Zend Framework 2 和 zend 表单中使用异常。如果有人对此有解决方案,如果可以共享,将很高兴。
附:我遵循了专辑模块,所以基本上我的结构与官方模块或多或少相似
编辑:add.phtml 已添加
添加.phtml
<?php
$title = "Add New Record Title";
$this->headTitle($title);
?>
<h2><?php echo $this->escapeHtml($title); ?></h2>
<?php
$form = $this->form;
$form->setAttribute("action", $this->url("addRecordTitle", array('controller' => "album", 'action' => "add")));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('recordTitle'));
echo $this->formInput($form->get('submit'));
echo $this->form()->closeTag($form);
?>
【问题讨论】:
-
您只是想知道如何在表单中附加错误消息,还是您的验证也有问题?
-
我只是想知道如何将错误消息附加到我的表单中,我的验证工作正常
标签: exception zend-form zend-framework2