我想以 zend 形式显示一个由异常抛出的简单异常消息。我检查数据库中是否存在重复记录,如果存在,则我想抛出一个错误,指出数据库中已存在具有该名称的记录。我想在记录名称文本字段之后的 add.phtml 文件中显示这一点。
这就是我想要做的:
在我的 Controller 中:
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
}
}
以及我正在检查重复记录的类:
记录.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 forms 的异常。如果有人对此有解决方案,如果可以共享,我们会很高兴。
附言我遵循了专辑模块,所以基本上我的结构或多或少与官方模块相似
编辑:已添加 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);
?>
最佳答案
鉴于您的示例,一种方法就是这样做。但是我建议您自己阅读内置验证器 Db\RecordExists and Db\RecordNoExists ,因为他们可能已经在做您正在尝试做的事情。
public function addAction()
{
$form = $this->getForm(); //theoretical
try {
$records->validateDuplicateRecords($recordTitle);
} catch (\Exception $e) {
$form->setMessages(array(
'recordTitle' => array($e->getMessage())
));
return new ViewModel(array(
'form' => $form
));
}
if ($form->isValid()) {
//usual stuff
}
}
使用此代码,您可以将错误消息附加到您的 title
-FormElement 上,确保将名称编辑为您的 title 元素的名称。
关于exception - 在 Zend Form 中显示异常错误消息 - Zend Framework 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012687/