Monday, July 04, 2016

How to add Custom Fields to Contact Form in Magento

Magento comes with a nice Contact Us form which helps customers to keep in touch with store owners. But in this article we'll see how we can easily add more fields to this Magento Contact form.

Let's check out the various settings in the Admin Panel first.

Below is the Store Email Address section. Any one of them can be used with the Contact Forms Email sender. We'll use "Customer Support" as our sender.



Next, let's take a look at Contact Form settings.



Here, we have the Target email address where the Contact Email will be sent to. Email template can also be selected here.

So, now we need to make changes to 3 more files... 

1. app/design/frontend/default/YOUR_THEME/template/contacts/form.phtml
2. app/code/core/Mage/Contacts/controllers/IndexController.php
3. app/locale/en_US/template/email/contact_form.html

The first file is the contact form template where we would include our new fields.
The IndexController.php is the controller where we can add server side validation to the field.
The third file is the Email Template.

Let's start with the Contact Form template. We are going to add a "Subject" field to our form. So, we just create an <input> element with a name "subject". If we want to make it a required entry, let's add "required-entry" to its class. This will add JavaScript validation to it. Check out the HTML below.

<li>
  <div class="input-box">
    <input name="subject" id="subject" title="Subject" value="" class="input-text required-entry" type="text" placeholder="Subject" />
  </div>
</li>

Now, as it is a required field, we need to add a server side validation as well. Here the controller IndexController.php comes in help. We can add our validation within postAction() method as shown below. Here we have checked if the value is an empty one.

if (!Zend_Validate::is(trim($post['subject']) , 'NotEmpty')) 
{
    $error = true;
}

If Server side validation fails, an error message "Unable to submit your request. Please, try again later" is shown.

Now, let's modify the Email template to include the new field "Subject". Open the email template file app/locale/en_US/template/email/contact_form.html. 



See how we have included the field "subject" in our email template by writing ::

Subject: {{var data.subject}}

Another thing, the first line of this template says "<!--@subject Our CUSTOM Contact Form@-->". This will be the Contact Email Subject line. Here I have modified it to "Our CUSTOM Contact Form".

Final result is, one email with subject line "Our CUSTOM Contact Form" is sent from "Customer Support" profile to "storeowner@store.com" as entered in "System > Configuration > Contacts" shown above.

This way we can add any number of fields to the Contact Form, add validations to it, and include them in the final email.