Form Question - Form Submission Origination Point

I am using Netlify Forms to handle comments for my site. However, when the notification comes in that I have a form submission there is no way to tell from which page/blog post the comment was sent from. Is there a way to have Netlify Forms specify which page the form (or in my case - the comment) was submitted from?

For example here is the email format I currently get:

Email Subject: My sites URL [Netlify] Form submission from comments-queue form**
Name:
Isaac

Email:
[name@url.com]()

Website:
[theusersreallycoolsite.com](http://mountaintopcoding.com/)

Comment:
This is a test comment to see how the system works, do not repost....

There is nothing there to specify what page the user was on when he/she sent the comment in. I need to know this so that I can post the comment manually to the correct page (my site has a well over 100 pages).

Site

This is the code for the form I am using on my Gatsby site (using TailwindCSS).

import React, { useState } from "react";

const Comments = () => {
    const [formState, setFormState] = useState({
        name: "",
        email: "", 
        website: "", 
        comment: ""
    })

    const encode = (data) => {
        return Object.keys(data)
            .map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
            .join("&");
    }

    const handleChange = e => {
        setFormState({
            ...formState, 
            [e.target.name]: e.target.value
        })
    }

    const handleSubmit = e => {
        fetch("/", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: encode({ "form-name": "comments-queue", ...formState})
          })
            .then(() => alert("Success!"))
            .catch(error => alert(error));
    
          e.preventDefault();
    }

    return (
        <div class="mt-4 border-solid border-4 border-grey-500 flex w-8/12 mx-auto">
            <form
                name="comments-queue" 
                method="POST" 
                data-netlify="true" 
                netlify-honeypot="bot-field"
                onSubmit={handleSubmit}
            >
            <input 
                type="hidden" 
                name="form-name" 
                value="comments-queue"
            />

            <input class="hidden" name="bot-field" />

            <p>Do you have something to say or meaningful to contribute? If so, please feel free to comment using the form below.</p>
            <div class="flex mx-auto">
                <p>
                    <label htmlFor="name" class="ml-4 font-semibold text-red-500">Name:</label>
                        <input
                            class="ml-2 mt-2 border-dashed border-2 border-red-500" 
                            type="text" 
                            name="name" 
                            onChange={handleChange} 
                            onSubmit={handleSubmit} 
                            value={formState.name} 
                        />
                </p>

                <p>
                    <label htmlFor="email" class="ml-4 font-semibold text-red-500">Email:</label>
                    <input 
                        class="ml-2 mt-2 border-dashed border-2 border-red-500"
                        type="email" 
                        name="email" 
                        onChange={handleChange} 
                        onSubmit={handleSubmit} 
                        value={formState.email} 
                    />
                </p>

                <p>
                    <label htmlFor="website" class="ml-4 font-semibold text-red-500">Website:</label> 
                    <input 
                        class="ml-2 mt-2 border-dashed border-2 border-red-500"
                        type="text" 
                        name="website" 
                        onChange={handleChange} 
                        onSubmit={handleSubmit} 
                        value={formState.website} 
                    />
                </p>
            </div>
            <div class="w-full">
                <p>
                    <label htmlFor="comment" class="ml-4 font-semibold text-red-500">Comment:</label> 
                        <input
                            class="ml-2 mt-2 box-border h-16 w-3/4 border-dashed border-2 border-red-500"            
                            type="text" 
                            name="comment" 
                            onChange={handleChange} 
                            onSubmit={handleSubmit} 
                            value={formState.comment} 
                        />
                </p>
            </div>

            <button type="submit" class="tracking-wide m-2 inline-block px-3 py-1 rounded-lg shadow-lg bg-red-500 text-white hover:bg-gray-300 hover:text-black">Send your comment (no spam I promise).</button>

            </form>
        </div>
    )
};

export default Comments

Thank you in advance for any guidance/suggestions.

I just add a hidden input field, and have my site generator populate it with the page url:

<input id="form-page-url" type="hidden" name="form-page-url" value="Sent from {{page_url}}">

The default netlify form notification includes the values of hidden input fields.

1 Like

As a member of the support team at Netlify, I 100% agree with the solution above from @scottkg. :100: :+1:

1 Like

Thank you @scottkg & @luke for the helpful suggestion. One last question (I hope) :laughing:

I was getting an error message page_url not defined so I added this line of code:

    const page_url = () => {
        window.location.href.toString()
    };

However, the hidden field’s name is showing in the email but not the value… What would you suggest to solve this?

So, after a bit of sleuthing, it turns out getting currentPage URL to render in Gatsby is not as straightforward as other site generators. Then I came across this article and it laid out four viable solutions for a workaround to this Gatsby issue.

After a bit of work I feel that Method #3 is the most viable. However, I keep getting stuck with this error: WebpackError: TypeError: Cannot read property 'pathname' of undefined

My hidden input field looks like this:

<input id="form-page-url" type="hidden" name="form-page-url" value={"${siteUrl}${location.pathname}"}></input>

(fyi - the "" within the value field are actually backticks)

Here is a link to my repo where I am working to solve this problem.

I feel like I am getting close because when a form is submitted it shows the siteURL which is defined in gatsby-config.js

If anyone can offer some insight to solving this I would appreciate it. I am posting this here in case anyone else in the future has similar issues with Gatsby, Netlify Forms, and retrieving current page URLs.

Hey there, @Isaac-Tait!

Thanks for following up here. I am going to loop in @jonsully to see if he has any additional insights on what you are asking here.

2 Likes

Hey @Isaac-Tait! :wave:t2:

Luckily I happen to be both a forms guy and a Gatsby guy :stuck_out_tongue:

There’s a path forward here where you could handle your own form submission rather than letting the browser handle the <form> natively, but I won’t get into that as a first-choice because it’ll be more complicated.

For the quick n’ easy route, have you tried this?

<input id="form-page-url" type="hidden" name="form-page-url" value={`${typeof window !== 'undefined' ? window.location.href : ''}`}></input>

Essentially just inlining the check for if the window object exists (and thus the page is running in a browser) and if it does, just injecting the current window location? This ought to work for you.

Hope that helps!


Jon

3 Likes

Hello @jonsully it worked! Thank you very much :laughing: I have been trying to figure that out for quite some time now.

Thank you @hillary for getting me pointed to the right person.

I really appreciate all of your help on this. :sunny: :blush:

2 Likes