top of page
Writer's pictureFaysal Jaali

How to Build a Custom Contact Form on Wix Using Velo

Building a custom contact form on your Wix website can significantly enhance user experience and streamline your business communication. With Wix Velo, you can create a form that not only collects basic information like first name, last name, and email address but also incorporates dynamic elements like conditional fields. In this blog, we’ll walk you through creating a contact form using Wix Velo and explore two different methods for storing the data: using Velo’s database capabilities and the Connect to Dataset feature.


Step 1: Accessing Wix Velo

First, log into your Wix account, access your site's dashboard, and enable Velo. This activates the Velo development environment, where you can code and customize your site.


Screenshot to activate Dev Mode on WIx


Step 2: Adding and Customizing the Contact Form

In the Wix Editor, drag and drop a form element onto your page.

  1. Adding Form Fields: The form consists of standard input fields for personal information, including 'First Name', 'Last Name', 'Email', and 'Phone Number'. These fields are essential for capturing basic contact details and should be clearly labeled and positioned for easy user navigation.

  2. Customizing Field Types and Layout: Each field has been customized to reflect the type of data it's intended to collect. The text fields for name and email ensure that users enter textual information, while the phone number field can be set to accept only numerical input for better data consistency.

  3. Incorporating Selection Options: Below the personal information fields, there is a selection titled "How did you hear about us?" with radio buttons for 'LinkedIn', 'Google', 'Wix', and 'Other'. Radio buttons are a great choice for this question as they allow for a single selection, ensuring clear and precise data about the user's discovery path.

  4. Dynamic Field Expansion for 'Other' Option: The 'Other' option includes a dynamic component that expands to reveal an additional input field when selected. This is not hidden but collapsed, meaning that it occupies space and can be made visible upon interaction.



Step 2b: Implementing Conditional Logic

screenshot of form created on Wix using custom fields

Using Velo's coding capabilities, implement the conditional logic. For instance, you can write a function that shows the additional comments field only when the specific value of a radiobox is selected:




$w('#HowDidYouHearAboutUs').onChange((event) => {
  if ($w("#HowDidYouHearAboutUs").value === "Other") {
    $w('#OtherText').expand();
  } else {
    $w('#OtherText').collapse();
  }
});


Step 3: Storing Data in a Database using Velo:

To store data in a Velo database, we can modify the form submission process. Instead of triggering the data storage on the form's 'submit' event, we'll use a button and its 'onClick' event. This gives you more control over the submission process, especially useful for implementing additional checks or actions before storing the data.


1: Add a Button to Your Form

In your Wix Editor, add a button element to your form. This button will be used to trigger the data submission process.


2: Implementing the 'onClick' Event Handler

Now, let's write the JavaScript code using Wix Velo to handle the button click event. This code will collect the data from the form, validate it, and then store it in your database.

Here's an example of how you might implement this:


// Import necessary Wix modules
import wixData from 'wix-data';

// Function to handle the button click event
$w.onReady(function () {
    $w("#submitButton").onClick(function () {
        // Collect data from the form fields
        let firstName = $w("#firstNameField").value;
        let lastName = $w("#lastNameField").value;
        let email = $w("#emailField").value;
        let PhoneNumber= $w("#PhoneNumberField").value;
        let HowDidYouHearAboutUs= $w("#HowDidYouHearAboutUs").value;
        let Other= $w("#OtherText").value;

        // Validate the data (basic example)
if (firstName && lastName && email) {
            // Create an object to store the collected data
let formData = {
                "firstName": firstName,
                "lastName": lastName,
                "email": email,
                "PhoneNumber": PhoneNumber,
                "HowDidYouHearAboutUs": HowDidYouHearAboutUs,
                "Other": Other
                // This last field is optional
            };

            // Store the data in the database
            wixData.insert("yourCollectionName", formData)
                .then(() => {
                    console.log("Data stored successfully");
                    // Additional actions upon successful storage, like     
                    //showing a thank you message
                })
                .catch((error) => {
                    console.error("Error storing data", error);
                    // Error handling actions
                });
        } else {
            // Handle the case where not all required fields are filled
        console.error("Please fill in all required fields.");
            // Actions like showing an error message to the user
        }
    });
});

3: Explanation of the Code

  1. Importing Wix Modules: The wix-data module is imported to interact with the database.

  2. Ready Function: The $w.onReady function ensures that the code runs after the page elements have finished loading.

  3. Button Click Event Handler: The onClick function is attached to the button (identified by #submitButton).

  4. Data Collection: Values are collected from each form field. For the additional comments field, it's a good practice to handle it as optional.

  5. Data Validation: Simple validation checks if the required fields are filled in.

  6. Data Object Creation: A JavaScript object (formData) is created to store the collected data in a format compatible with the database collection.

  7. Data Storage: The wixData.insert function is used to store formData in the specified database collection (yourCollectionName).

  8. Success and Error Handling: Upon successful data storage, you can implement additional actions like displaying a success message. In case of an error (e.g., data validation fails or database error), appropriate error handling or user notifications can be implemented.


Step 3b: Advanced Custom Form Examples in Wix Velo

Creating complex custom forms in Wix Velo involves leveraging advanced features like dynamic dropdowns, conditional logic, real-time validation, and integration with external APIs. These features enhance user interaction and provide a more intuitive form-filling experience. Below are examples of these advanced form types and explanations on how to implement them.


Example 1: Dynamic Dropdown Based on User Selection


Scenario:

You want a dropdown that changes its options based on a previous selection. For instance, selecting a country in one dropdown changes the options in the city dropdown.


Implementation:

  1. Setup Dropdowns: In your Wix Editor, add two dropdowns - one for country and one for city.

  2. Populate Country Dropdown: Use Velo to populate the country dropdown from a dataset or a hardcoded list.

  3. Add an onChange Event to Country Dropdown: When a country is selected, trigger an event to populate the city dropdown.

  4. Fetch and Populate City Data: Based on the selected country, fetch the corresponding cities (from a database or external API) and populate the city dropdown.

Code for Dynamic Dropdown:


// Assuming you have two dropdowns: #dropdownCountry and #dropdownCity
// Populate the country dropdown (hardcoded for example)

$w.onReady(function () {
    $w("#dropdownCountry").options = [
        { "label": "USA", "value": "usa" },
        { "label": "Canada", "value": "canada" },
        // Add more countries as needed
    ];

    // Add an event listener for when the country changes
    $w("#dropdownCountry").onChange(() => {
        let selectedCountry = $w("#dropdownCountry").value;

        // Based on the country, populate the city dropdown
if (selectedCountry === "usa") {
            $w("#dropdownCity").options = [
                { "label": "New York", "value": "newYork" },
                { "label": "Los Angeles", "value": "losAngeles" }
                // Add more cities as needed
            ];
        } else if (selectedCountry === "canada") {
            $w("#dropdownCity").options = [
                { "label": "Toronto", "value": "toronto" },
                { "label": "Vancouver", "value": "vancouver" }
                // Add more cities as needed
            ];
        }
    });
});


Example 2: Real-time Field Validation


Scenario:

Check if a username is available as the user types it in. We'll assume you have a database collection 'userCollection' with a field 'username'.


Implementation:

  1. Setup Username Field: Add a username input field (#usernameField) in the Wix Editor for user input.

  2. Implement Debounced onKeyPress Event: Attach an onKeyPress event to the username field with a debouncer to limit frequent database queries.

  3. Create Availability Check Function: Define the checkUsernameAvailability function to query the database and check if the username is already taken.

  4. Provide Real-Time Feedback: Update the UI elements in real-time to inform the user of the username's availability based on database query results.

Code for Real-time Field Validation:



import wixData from 'wix-data'; // Import wix-data module

let debounceTimer;

$w.onReady(function () {
    $w("#usernameField").onKeyPress(() => {
        clearTimeout(debounceTimer); // Clear existing timer
        debounceTimer = setTimeout(checkUsernameAvailability, 600); 
        // Set new debounce timer
       
    });
});

function checkUsernameAvailability() {
    let currentUsername = $w("#usernameField").value;

    wixData.query("userCollection")
        .eq("username", currentUsername)
        .find()
        .then((results) => {
            if (results.items.length > 0) {
                console.log("Username is taken");
            // Username is taken
             $w("#usernameStatus").text = "Username is already taken";
             $w("#usernameStatus").style.color = "red";
            } 
             else {
                console.log("Username is available"); 
             // Username is available
                $w("#usernameStatus").text = "Username is available";
                $w("#usernameStatus").style.color = "green";
            }
        })
        .catch((err) => {
            console.error("Query failed", err);
        });
}


Conclusion

In conclusion, building a custom contact form on your Wix website using Wix Velo is a strategic move that greatly enhances user engagement and simplifies communication channels. The versatility of Wix Velo allows for a range of functionalities, from basic form setups to advanced features like dynamic dropdowns, conditional fields, and real-time feedback.


This adaptability ensures that the contact form is not only functional but also intuitive and responsive to user interactions. Incorporating such sophisticated elements elevates the overall user experience, making your website more interactive and professional.

For those looking to harness the full potential of Wix Velo for creating custom solutions, CodeMasters Agency offers expert services tailored to your unique business needs. Our team is skilled in leveraging Wix Velo to build engaging, efficient, and innovative web experiences. If you're ready to transform your website into a dynamic platform that stands out, reach out to CodeMasters Agency. Let us help you take your online presence to the next level and create a digital space that truly resonates with your audience.


Comments


bottom of page