Using Vue.js

To use Freeform with Vue.js you'll need access to the form instance, which will provide you with the form's hash for identification. When building out the form's state manually, handling the validation in Vue.js and doing an AJAX request for saving the form, be sure to:

  • Set the request headers to use Craft's AJAX request:
    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    request.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest");
    
    1
    2
  • Set the request payload to include action, and have it point to freeform/api/form, which will handle form validation, submission saving and any other processes.
  • Add formHash to the request payload that contains the form instance's hash property. This is for identifying the target form's ID and page and other information.
  • If you're using the Freeform built-in Honeypot feature, be sure to add the correct honeypot data to the request's payload as well.
    • If you're using the Javascript Enhancement for the Freeform honeypot, you'll need to access the honeypot service and provide your form. In twig it is: craft.freeform.getHoneypot(myFormInstance), which will return a honeypot object that has the honeypot name and value.
    • If you're using the basic honeypot, just provide the honeypot name (freeform_form_handle by default) with an empty value.

Below is a simple example of a basic form rendered with Vue.js:

{# Load the form for later access #}
{% set form = craft.freeform.form('composerForm') %}

{# Load Vue.js #}
<script src="https://unpkg.com/vue"></script>

{# Add some minor styles #}
<style>
    .errors { color: red; }
    label { display: block; font-weight: bold; }
    form div { margin-bottom: 10px; }
</style>

<div id="app">
    {# Create a form and attach an onSubmit method #}
    <form v-on:submit="onSubmit">
        <div>
            <label>First Name</label>
            <input type="text" v-model="firstName" v-on:blur="() => validate('firstName')"/>
            <ul v-if="getErrors('firstName').length" class="errors">
                <li v-for="error in getErrors('firstName')">
                    ${ error }
                </li>
            </ul>
        </div>
        <div>
            <label>Last Name</label>
            <input type="text" v-model="lastName" v-on:blur="() => validate('lastName')"/>
            <ul v-if="getErrors('lastName').length" class="errors">
                <li v-for="error in getErrors('lastName')">
                    ${ error }
                </li>
            </ul>
        </div>
        <div>
            <label>Message</label>
            <textarea v-model="message" v-on:blur="() => validate('message')"></textarea>
            <ul v-if="getErrors('message').length" class="errors">
                <li v-for="error in getErrors('message')">
                    ${ error }
                </li>
            </ul>
        </div>
        <button type="submit">Submit</button>
    </form>
</div>

<script>
  new Vue({
    el: '#app',
    delimiters: ['${', '}'],
    data: {
      firstName: '',
      lastName: '',
      message: '',
      errors: [],
    },
    methods: {
      getErrors: function (property) {
        const errors = [];
        if (!this.errors.length) {
          return errors;
        }
        for (let i = 0; i < this.errors.length; i++) {
          if (this.errors[i].key === property) {
            errors.push(this.errors[i].message);
          }
        }
        return errors;
      },
      validate: function (property) {
        if (!property) {
          this.errors = [];
        } else {
          this.errors = this.errors.filter((item) => item.key !== property);
        }
        if ((!property || property === 'firstName') && !this.firstName) {
          this.errors.push({ key: 'firstName', message: 'This field is required' });
        }
        if ((!property || property === 'lastName') && !this.lastName) {
          this.errors.push({ key: 'lastName', message: 'This field is required' });
        }
        if ((!property || property === 'message') && !this.message) {
          this.errors.push({ key: 'message', message: 'This field is required' });
        }
      },
      onSubmit: function (evt) {
        this.validate();
        if (this.errors.length) {
          evt.stopPropagation();
          evt.preventDefault();
          return false;
        }
        const form = evt.target;
        const data = new FormData(form);
        const request = new XMLHttpRequest();

        // Add Honeypot field
        data.append('freeform_form_handle', '');

        // Add action which handles freeform validation
        data.append('action', 'freeform/api/form');

        // Add the form's hash, so that it gets recognized by the form service
        data.append('formHash', '{{ form.hash }}');

        // Add the CSRF token if it's enabled for the site
        data.append(
          '{{ craft.app.config.general.csrfTokenName }}',
          '{{ craft.app.request.csrfToken }}',
        );

        // Append the data
        data.append('firstName', this.firstName);
        data.append('lastName', this.lastName);
        data.append('message', this.message);

        // Create a request
        request.open('POST', window.location.href, true);
        request.setRequestHeader("Cache-Control", "no-cache");

        // Add the AJAX headers specific to Craft CMS
        request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        request.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest");

        // Attach the response handler callback
        request.onload = () => {
          if (request.status === 200) {
            const response = JSON.parse(request.response);
            const { success, finished, errors, formErrors } = response
            if (success && finished) {
              // Reset the form so that the user may enter fresh information
              form.reset();
              alert('success');
            } else if (errors || formErrors) {
              alert('error');
              console.error(errors, formErrors);
            }
          } else {
            console.error(request);
          }
        };

        // Send the request
        request.send(data);

        evt.stopPropagation();
        evt.preventDefault();
        return false;
      },
    },
  });
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
Last Updated: 11/25/2019, 3:59:54 PM