2
votes

I am trying to figure out how to add more than one error message to a form field. Here is the logic I am using currently inside the doFormAction method:

$errors = $validation->ValidateInput($data);
foreach($errors as $key => $value){
    if(!empty($value)){
        $errorMessages = "<ul>";
        foreach($value as $errorMessage){
            $errorMessages = $errorMessages . "<li>" . $errorMessage . "</li>"
        }
        $errorMessages = $errorMessages . "</ul>";
        $form->AddErrorMessage($key, $errorMessages, 'bad');
    }
}

The above print out will not actually print out the list for me, it will html encode the characters before they get printed out on the page. If I try to use something like this:

$form->AddErrorMessage("Field1", "First Error", 'bad');
$form->AddErrorMessage("Field1", "Second Error", 'bad');

I will only see the last error message. Is there a way with silverstripe forms to produce multiple error messages on a single field?

EDIT: Here is the function from silverstripe:

public function addErrorMessage($fieldName, $message, $messageType, $escapeHtml = true) {
    Session::add_to_array("FormInfo.{$this->FormName()}.errors",  array(
       'fieldName' => $fieldName,
       'message' => $escapeHtml ? Convert::raw2xml($message) : $message,
       'messageType' => $messageType,
    ));
}

Meaning that when I add the error message for the second time, it over writes the first one as it uses the same name.

1

1 Answers

1
votes

If I remember correctly, AddErrorMessage is supposed to add up to one error per field. Even when having multiple rules per field, I've never added more than one error message, because it might be (a) confusing for the user and (b) fixing one problem might fix others as well.

I'd rather use client-side validation (http://parsleyjs.org, https://rickharrison.github.io/validate.js/,...), which is made for rapid feedback. I will then check on the server-side again, but the vast majority of issues has then been fixed on the client-side already; thus I'm not too worried if it's a little more tedious for the rare use case.

If you still want to change it, take a look at http://api.silverstripe.org/3.1/source-class-Form.html#567-581 — you should be able to overwrite / write your own implementation covering multiple errors per field, but I'm not sure if it's worth it.