I'm looking to set a single error message for a form, but still validate each field.
The form is a survey with 10 questions. Each of them validates the same way (->setRequired(true)
). So basically, I just to validate that each questions has an answer and display one message at the top of the form if one of them is not answered.
I've tried several solutions and gotten the same result. My error is added to the form, but also, all of the individual errors show as well.
This is my latest shot at it:
public function isValid($data)
{
$errors = 0;
parent::isValid($data);
foreach ($this->getElements() as $element) {
if ($element->hasErrors()) {
$element->clearErrorMessages();
$element->setErrors(array());
$errors++;
}
}
if (count($errors) > 0) {
$this->setErrorMessages(array('Please answer all questions before proceeding.'));
return false;
}
return true;
}
Can anyone shed some light on why this isn't working as I'd expect? There has to be a more elegant way of doing this.
EDIT:
This is what I ended up with. Probably a little different than most since my form elements are dynamically populated based on an array of questions, but the general idea should apply. Normally, you could just count the number of radio elements, but in my case, rather than looping through the elements and checking the type, it was just easier to count my array of questions.
public function isValid($data)
{
$valid_values = 0;
parent::isValid($data);
foreach ($this->getValues() as $value) {
if ($value >= 1 && $value <= 10) {
$valid_values++;
}
}
if ($valid_values <> count($this->_questions)) {
$this->setErrorMessages(array('Please answer all questions before proceeding.'));
return false;
}
return true;
}
Still not sure this is the most elegant way, but it works for my particular case.