xpertbot / craft-wheelform

Craft CMS 4 Form with Database integration
MIT License
66 stars 32 forks source link

Error handling via JS #276

Closed wallythewebdev closed 1 year ago

wallythewebdev commented 2 years ago

Hi (again).

Just wanted to touch base on the ideal (or default intended) way to handle errors in JS to prevent form submission while required fields have not fulfilled their requirements.

PHP method default - Very cool Macro picks up on any Macros, but requires on page reload (which I am avoiding for a seemless UX):

{% macro errorList(errors) %}
    {% if errors %}
        <ul class="errors">
            {% for error in errors %}
                <li>{{ error }}</li>
            {% endfor %}
        </ul>
    {% endif %}
{% endmacro %}
{% from _self import errorList %}

In JS as per the docs, using Ajax to submit the form:

    axios({
      method: 'post',
      url: url,
      responseType: 'json',
      headers: {'X-Requested-With': 'XMLHttpRequest'},
      data: formData,
    })
    .then(function (response) {
      console.log(response);
      < FORM VALIDATION PASSED HERE? >
    })
    .catch(function (error) {
      console.log(error);
    });

Does wheel form have a built in JS function that checks for the validation of form fields? I have wrote a custom one, but I was just wanting to checkin if there is an official way to handle form validation?

xpertbot commented 2 years ago

Hello, The errors macro is not part of the plugin is just default Twig Templating system behavior. However, there are two ways to solve this:

  1. Since you are already using Ajax to submit, you can get the errors from the backend after the submission and display them on the page. The response returns a "success" boolean that you can check against.
  2. Add the validation to the form and validate the values before the submission. This will prevent the server from handling the submissions and use fewer resources.
stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.