I wanted to display a simple exception message in zend form which is thrown by an exception. I check whether there is a duplicate record existing in the database and if exits then I want to throw an error saying the the record with that name already exists in the database. This I wanted to show in the add.phtml file exactly after the record name textfield.
This is how I am trying to do:
In my 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
}
}
And the class where I am checking for duplicate records:
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;
}
}
So that is basically how im doing, I know how this try and catch works with pure php stuff, but I don't know how I can use the exceptions with Zend Framework 2 and zend forms. In case if anybody has a solution for this would be glad if it can be shared.
P.S. I followed the Album Module so basically my structure resembles more or less same from the official Module
EDIT: add.phtml has been addded
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);
?>