[英]Display Exception error message in Zend Form - Zend Framework 2
我想以zend形式顯示一個由異常拋出的簡單異常消息。 我檢查數據庫中是否存在重復記錄,如果退出,那么我想拋出一個錯誤,說該數據庫中已存在具有該名稱的記錄。 這個我想在add.phtml文件中完全顯示在記錄名稱textfield之后。
這就是我想要做的事情:
在我的控制器中:
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和catch如何使用純PHP的東西,但我不知道如何使用Zend Framework 2和zend表單的異常。 如果任何人有這方面的解決方案,如果它可以共享將很高興。
PS我遵循了相冊模塊,所以基本上我的結構與官方模塊大致相似
編輯 :add.phtml已添加
add.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和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元素的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.