Sterc / FormIt

A dynamic form processing Snippet for MODX Revolution
https://docs.modx.com/current/en/extras/formit
33 stars 58 forks source link

JSON output options for errors and hooks #73

Closed sepiariver closed 8 years ago

sepiariver commented 8 years ago

What It Does

Allows formatting of error responses in JSON rather than HTML. Hooks class and Validator class affected.

Why It's Needed

Often it's desirable for FormIt to handle form data posted via AJAX, and the response should be valid JSON instead of HTML. You can monkey around with conditional output modifiers and TPL properties, but in the end it's still very limiting and inflexible. With this PR, some runtime config options can be used to output these responses in JSON easily.

Example Usage

[[!FormIt? 
    &hooks=`FormItSaveForm`
    &formName=`[[!getFormName]]`
    &validate=`type:required,email:email:required`
    &successMessage=`Thank you! Your request has been submitted.`
    &validationErrorBulkFormatJson=`1`
    &validationErrorMessage=`{"success":false,"errors":[[+errors]]}`
    &hookErrorJsonOutputPlaceholder=`hook_error_json_response`
    &errTpl=`[[+error]]`
]][[!+fi.validation_error_message]][[!+hook_error_json_response]]
[[!+fi.successMessage:is=``:then=``:else=`{"success":true,"message":"[[!+fi.successMessage]]"}`]]

If the hook returned an error it would be like this:

{
  "errors": {
    "test": "bad kitty!",
    "FormItSaveForm": " "
  },
  "success": false,
  "message": "bad kitty!\n "
}

If a validator failed it would look like this:

{
  "success": false,
  "errors": {
    "type": "This field is required.",
    "email": "This field is required."
  }
}
matdave commented 8 years ago

Nice, this would be a good feature.

joeke commented 8 years ago

Hi @sepiariver Thanks for your PR, looks good! Have tested it (also with strange characters in error messages) and all seems to be going well.