3

我想以 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
    }
}

还有我正在检查重复记录的类:

记录.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 表单中使用异常。如果有人对此有解决方案,如果可以共享,我会很高兴。

PS我遵循专辑模块,所以基本上我的结构与官方模块或多或少相似

编辑: 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); 
?>
4

1 回答 1

4

鉴于您的示例,一种方法就是这样。但是,我建议您阅读内置验证器Db\RecordExists 和 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 上,请务必将名称编辑为您的标题元素的名称。

于 2012-10-22T13:53:48.047 回答