Search code examples
shopifycontact-formform-dataform-fields

Keep form data after errors on basic Shopify contact form


I have added a basic contact form as described in Shopify Documentation.

My code:

{% form 'contact' %}

{% if form.posted_successfully? %}
<div class="successForm feedback">
  <p>Thanks for contacting us. We'll get back to you as soon as possible.</p>
</div>
{% endif %}

{% if form.errors %}
<div class="errorForm feedback">
  <p>Sorry, we were unable to submit your inquiry because it contained {{ form.errors | size | pluralize: 'an error', 'a few errors' }}.<br/>Please correct the following and submit again:</p>
  {% for field in form.errors %}
  <p><strong>The {{ field | capitalize | replace: 'Body', 'Comments / questions' }} field {{ form.errors.messages[field] }}.</strong></p>
  {% endfor %}
</div>
{% endif %}

<div id="contactFormWrapper">
  <h3>Personal details</h3>
  <ul>
    <li>
      <label>First name:</label>
      <input type="text" id="contactFormFirstName" name="contact[first-name]" placeholder="" />
    </li>
    <li>
      <label>Last name:</label>
      <input type="text" id="contactFormLastName" name="contact[last-name]" placeholder="" />
    </li>          
    <li>
      <label>Email address:</label>
      <input type="email" id="contactFormEmail" name="contact[email]" placeholder="" />
    </li>
    <li>
      <label>Telephone number:</label>
      <input type="telephone" id="contactFormTelephone" name="contact[phone]" placeholder="" />
    </li>
    <li>
      <label>City:</label>
      <input type="text" id="contactFormCity" name="contact[city]" placeholder="" />
    </li>
    <li>
      <label>Country:</label>
      <input type="text" id="contactFormCountry" name="contact[country]" placeholder="" />
    </li>
  </ul>
  <h3>Items</h3>
  <ul>
    <li>
      <label>Items:</label>
      <input type="text" id="contactFormItems" name="contact[items]" placeholder="" />

    </li>
    <li>
      <label>Questions:</label>
      <textarea rows="10" id="contactFormComments" name="contact[body]" placeholder=""></textarea>
    </li>
  </ul>
  <div class="clearfix"></div>
  <div class="main-button-container">
    <input type="submit" id="contactFormSubmit" value="Submit Enquiry" class="btn button-style" />
  </div>
</div>

{% endform %}

However, if a user tries to submit the form but has filled it in incorrectly, the page refreshes with an error message and clears all of the data. This is not ideal from a user experience point of view, as the user has to re-enter everything.

How can I keep all of the previous data filled in after a form error? Please help.


Solution

  • You can display the submitted data using the value attribute. For example:

    <input type="text" id="contactFormEmail" name="contact[email]" value="{{form.email}}" />
    

    Or for a textarea:

    <textarea id="contactFormComments" name="contact[body]">{{form.body}}</textarea>