Reputation: 856
I want to print a div with a list of errors inside it. The errors are found by iterating inside a foreach loop. I would like this entire div and list inside a variable so that I can print it in the required part.
Here's what I am doing:
errmessage = "";
//more code, if etc
else {
$errmessage .= '<div class="form-error alert alert-danger"><strong>Form submission failed!</strong><ul>';
foreach($vresult->getErrors() as $v) {
$errmessage .= '<li>'.$v.'</li>';
}
$errmessage .= '</ul></div>';
}
In another part of the file:
<form method="post">
<?php
echo $errmessage;
?>
Is this the right way to do it, I want to echo if there are error otherwise print nothing if there aren't any. This works for me but wondered if there were any other good practices.
Upvotes: 0
Views: 244
Reputation: 34
Solution looks fine one suggestion is
In else case if you do not want to display "Form submission failed!" message when no errors
if(!empty($vresult->getErrors()) {
//Build error message inside
}
Upvotes: 0
Reputation: 795
Your solution is okay to use, but I suggest using an object oriented approach like this:
<?php
class ErrorManager
{
private $errors = Array();
public function AddError($errorMessage)
{
array_push($this->errors,$errorMessage);
}
public function GetErrorMessage()
{
$finalMessage = "";
foreach ($this->errors as &$error) {
$finalMessage .= $error ."\r\n";
}
return $finalMessage;
}
}
-- Usage of the class -----
$errMngr = new ErrorManager();
$errMngr->AddError('A failure occured!');
$errMngr->AddError('another failure :(');
echo $errMngr->GetErrorMessage();
//OR Use this for HTML
echo nl2br($errMngr->GetErrorMessage());
?>
This way you can get a plain text string using a \n\r delimiter. You can output the errors in your log file and also display them as HTML with nl2br()
You can also alter the class to use a div + list like this:
public function GetErrorMessageHTMLList()
{
$finalMessage = "<div><ul>";
foreach ($this->errors as &$error) {
$finalMessage .= '<li>'.$error .'</li>';
}
return $finalMessage.'</ul></div>';
}
Upvotes: 1