Engine23
blogBannerImage
By Engine23

Magento - How to add captcha to the contact us form

Step 1: create the module instantiation xml: app/etc/modules/Engine23_Contactform.xml

<?xml version="1.0"?>
<config>
<modules>
<Engine23_Contactform>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Captcha/>
</depends>
</Engine23_Contactform>
</modules>
</config>

Step 2: Create the folder for our controller and config.xml: app/code/local/Engine23/Contactform

Step 3: Create the IndexController: app/code/local/Engine23/Contactform/controllers/IndexController.php

 <?php 
/*
 * Adding Captcha to Contacts form
 */
require_once(Mage::getModuleDir('controllers', 'Mage_Contacts') . DS . 'IndexController.php');

class Engine23_Contactform_IndexController extends Mage_Contacts_IndexController
{

    public function postAction()
    {
        $post = $this--->getRequest()->getPost(); if ($post) { $translate = Mage::getSingleton('core/translate'); /* @var $translate Mage_Core_Model_Translate */ $translate->setTranslateInline(false); try { $postObject = new Varien_Object(); $postObject->setData($post); $error = false; if (!Zend_Validate::is(trim($post['name']), 'NotEmpty')) { $error = true; } if (!Zend_Validate::is(trim($post['comment']), 'NotEmpty')) { $error = true; } if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) { $error = true; } if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) { $error = true; } $formId = 'contact_us'; $captchaModel = Mage::helper('captcha')->getCaptcha($formId); if ($captchaModel->isRequired()) { if (!$captchaModel->isCorrect($this->_getCaptchaString($this->getRequest(), $formId))) { Mage::getSingleton('customer/session')->addError($this->__('Incorrect CAPTCHA entered, please try again. If your not a robot and just want to talk, please give us a call, 402-871-5167.')); $this->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true); Mage::getSingleton('customer/session')->setCustomerFormData($this->getRequest()->getPost()); $this->getResponse()->setRedirect(Mage::getUrl('contacts')); return; } } if ($error) { throw new Exception(); } $mailTemplate = Mage::getModel('core/email_template'); /* @var $mailTemplate Mage_Core_Model_Email_Template */ $mailTemplate->setDesignConfig(array('area' => 'frontend')) ->setReplyTo($post['email']) ->sendTransactional( Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE), Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER), Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT), null, array('data' => $postObject) ); if (!$mailTemplate->getSentSuccess()) { throw new Exception(); } $translate->setTranslateInline(true); Mage::getSingleton('customer/session')->addSuccess($this->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.')); $this->_redirect('*/*/'); return; } catch (Exception $e) { $translate->setTranslateInline(true); Mage::getSingleton('customer/session')->addError($this->__('Unable to submit your request. Please, try again later')); $this->_redirect('*/*/'); return; } } else { $this->_redirect('*/*/'); } } protected function _getCaptchaString($request, $formId) { $captchaParams = $request->getPost(Mage_Captcha_Helper_Data::INPUT_NAME_FIELD_VALUE); return $captchaParams[$formId]; } } 

Step 4: Create the config.xml: app/code/local/Engine23/Contactform/etc/config.xml

<?xml version="1.0"?>
<config>
<modules>
<Engine23_Contactform>
<version>0.0.2</version>
</Engine23_Contactform>
</modules>
<default>
<captcha translate="label">
<frontend>
<areas>
<contact_us>
<label>Contact Us Form</label>
</contact_us>
</areas>
</frontend>
</captcha>
<customer>
<captcha>
<always_for>
<contact_us>1</contact_us>
</always_for>
</captcha>
</customer>
</default>
<frontend>
<routers>
<contacts>
<args>
<modules>
<engine23_contactform before="Mage_Contacts">Engine23_Contactform</engine23_contactform>
</modules>
</args>
</contacts>
</routers>
</frontend>
</config>

Step 5: Frontend over-ride for the contacts/form.phtml.  This helps us clean keep values if the form post has an incorrect captcha and also reset them after its submitted.

<?php
// Get our posted data if it was submitted and failed, this way we re-populate our form
$postData = Mage::getSingleton('customer/session')->getCustomerFormData();
?>
<div id="messages_product_view"><?php echo $this->getMessagesBlock()->getGroupedHtml() ?></div>
<div class="page-title">
<h1><?php echo $this->__('Contact Us') ?></h1>
</div>
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post">
<div class="fieldset">
<h2 class="legend"><?php echo $this->__('Contact Information') ?></h2>
<ul class="form-list">
<li class="fields">
<div class="field">
<label for="name" class="required"><em>*</em><?php echo $this->__('Name') ?></label>
<div class="input-box">
<input name="name" id="name" title="<?php echo $this->__('Name') ?>" value="<?php echo $this->htmlEscape($postData['name']) ?>" class="input-text required-entry" type="text" />
</div>
</div>
<div class="field">
<label for="email" class="required"><em>*</em><?php echo $this->__('Email') ?></label>
<div class="input-box">
<input name="email" id="email" title="<?php echo $this->__('Email') ?>" value="<?php echo $this->htmlEscape($postData['email']) ?>" class="input-text required-entry validate-email" type="text" />
</div>
</div>
</li>
<li>
<label for="telephone"><?php echo $this->__('Telephone') ?></label>
<div class="input-box">
<input name="telephone" id="telephone" title="<?php echo $this->__('Telephone') ?>" value="<?php echo $this->htmlEscape($postData['telephone']) ?>" class="input-text" type="text" />
</div>
</li>
<li class="wide">
<label for="comment" class="required"><em>*</em><?php echo $this->__('Comment') ?></label>
<div class="input-box">
<textarea name="comment" id="comment" title="<?php echo $this->__('Comment') ?>" class="required-entry input-text" cols="5" rows="3"><?php echo $this->htmlEscape($postData['comment']) ?></textarea>
</div>
</li>
<?php echo $this->getChildHtml('form.additional.info'); ?>
</ul>
</div>
<div class="buttons-set">
<p class="required"><?php echo $this->__('* Required Fields') ?></p>
<button type="submit" title="<?php echo $this->__('Submit') ?>" class="button"><span><span><?php echo $this->__('Submit') ?></span></span></button>
</div>
</form>
<script type="text/javascript">
//<![CDATA[
var contactForm = new VarienForm('contactForm', true);
//]]>
</script>
<?php
/* Clear our session data to keep it clean */
$postData = Mage::getSingleton('customer/session')->setCustomerFormData(null);
?>
app/design/frontend/PACKAGE(value from your magento admin)/THEME(value from your magento admin)/layout/contacts.xml
<?xml version="1.0"?>
<layout version="0.1.0">
<default>
<reference name="footer_links">
<action method="addLink" translate="label title" module="contacts" ifconfig="contacts/contacts/enabled"><label>Contact Us</label><url>contacts</url><title>Contact Us</title><prepare>true</prepare></action>
</reference>
</default>
<contacts_index_index translate="label">
<label>Contact Us Form</label>
<reference name="root">
<action method="setTemplate"><template>page/1column.phtml</template></action>
<action method="setHeaderTitle" translate="title" module="contacts"><title>Contact Us</title></action>
</reference>
<reference name="content">
<block type="core/template" name="contactForm" template="contacts/form.phtml">

<block type="core/text_list" name="form.additional.info">
<block type="captcha/captcha" name="captcha">
<reference name="head">
<action method="addJs"><file>mage/captcha.js</file></action>
</reference>
<action method="setFormId"><formId>contact_us</formId></action>
<action method="setImgWidth"><width>230</width></action>
<action method="setImgHeight"><width>50</width></action>
</block>
</block>

</block>
</reference>
</contacts_index_index>

</layout>

Now Update the app/design/frontend/PACKAGE(value from your magento admin)/THEME(value from your magento admin)/template/contacts/form.phtml:

<?php
// Get our posted data if it was submitted and failed, this way we re-populate our form
$postData = Mage::getSingleton('customer/session')->getCustomerFormData();
?>
<div id="messages_product_view"><?php echo $this->getMessagesBlock()->getGroupedHtml() ?></div>
<div class="page-title">
<h1><?php echo $this->__('Contact Us') ?></h1>
</div>
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post">
<div class="fieldset">
<h2 class="legend"><?php echo $this->__('Contact Information') ?></h2>
<ul class="form-list">
<li class="fields">
<div class="field">
<label for="name" class="required"><em>*</em><?php echo $this->__('Name') ?></label>
<div class="input-box">
<input name="name" id="name" title="<?php echo $this->__('Name') ?>" value="<?php echo $this->htmlEscape($postData['name']) ?>" class="input-text required-entry" type="text" />
</div>
</div>
<div class="field">
<label for="email" class="required"><em>*</em><?php echo $this->__('Email') ?></label>
<div class="input-box">
<input name="email" id="email" title="<?php echo $this->__('Email') ?>" value="<?php echo $this->htmlEscape($postData['email']) ?>" class="input-text required-entry validate-email" type="text" />
</div>
</div>
</li>
<li>
<label for="telephone"><?php echo $this->__('Telephone') ?></label>
<div class="input-box">
<input name="telephone" id="telephone" title="<?php echo $this->__('Telephone') ?>" value="<?php echo $this->htmlEscape($postData['telephone']) ?>" class="input-text" type="text" />
</div>
</li>
<li class="wide">
<label for="comment" class="required"><em>*</em><?php echo $this->__('Comment') ?></label>
<div class="input-box">
<textarea name="comment" id="comment" title="<?php echo $this->__('Comment') ?>" class="required-entry input-text" cols="5" rows="3"><?php echo $this->htmlEscape($postData['comment']) ?></textarea>
</div>
</li>
<?php echo $this->getChildHtml('form.additional.info'); ?>
</ul>
</div>
<div class="buttons-set">
<p class="required"><?php echo $this->__('* Required Fields') ?></p>
<button type="submit" title="<?php echo $this->__('Submit') ?>" class="button"><span><span><?php echo $this->__('Submit') ?></span></span></button>
</div>
</form>
<script type="text/javascript">
//<![CDATA[
var contactForm = new VarienForm('contactForm', true);
//]]>
</script>
<?php
/* Clear our session data to keep it clean */
$postData = Mage::getSingleton('customer/session')->setCustomerFormData(null);
?>

 

Step 6: Remember to also put this in your mobile theme if you have one.