Magento: Add captcha to custom contact form

Khalil picture Khalil · Apr 20, 2014 · Viewed 14.4k times · Source

I created a new custom contact form in Magento website, I am trying to add captcha at the end of it.

I have added to app/code/core/Mage/Captcha/etc/config.xml

                <customcontacts>
                    <label>Custom Contact Form</label>
                </customcontacts>

And I added to app/design/frontend/base/default/layout/captcha.xml

    <customcontacts>
    <reference name="customcontacts">
        <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>customcontacts</formId></action>
                <action method="setImgWidth"><width>230</width></action>
                <action method="setImgHeight"><width>50</width></action>
            </block>
        </block>
    </reference>
</customcontacts>

And I added to my form this code:

<script type="text/javascript">
//<![CDATA[
$('form-validate-captcha').captcha.refresh($('catpcha-reload'));
//]]>

And I added this code to show the Captcha:

<div><?php echo $this->getChildHtml('captcha'); ?></div>

Then I enabled Captcha in Configuration > Customer Configuration > CAPTCHA and I choose "Custom Contact Form" then "Displaying Mode" to "Always".

But I still didn't get the Captcha at my custom form yet.

I hope I was clear

Thanks

Answer

Amit Bera picture Amit Bera · Apr 20, 2014

if ,you want to add magento own captcha to contact us form ,then follow below step.....

Donot write code in code file create an extension

Step1: Create module control file

path app/etc/modules/Amit_Captchaown.xml add below code

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

Step2:

Create module config.xml file in app/code/local/Amit/Captchaown/etc/config.xml.Rewrite model of zend and captcha controllers and here code

 <?xml version="1.0"?>
<config>
<modules>
<Amit_Captchaown>
<version>1.0.0</version>
</Amit_Captchaown>
</modules>
<global>
    <models>
    <captcha>
        <rewrite>
        <zend>Amit_Captchaown_Model_Zend</zend>
        </rewrite>
        </captcha>
    </models>
</global>
<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>
<amit_captchaown before="Mage_Contacts">Amit_Captchaown</amit_captchaown>
</modules>
</args>
</contacts>
</routers>
</frontend>
</config>

Step3:

Override Mage_Captcha_Model_Zend file _isUserAuth() function create Zend.php file in app/code/local/Amit/Captchaown/Model/Zend.php.In this function you need to only comment function code.

<?php
class Amit_Captchaown_Model_Zend extends Mage_Captcha_Model_Zend
{

protected function _isUserAuth()
{
/* return Mage::app()->getStore()->isAdmin()
? Mage::getSingleton(‘admin/session’)->isLoggedIn()
: Mage::getSingleton(‘customer/session’)->isLoggedIn();*
*/
}

}

Step4: Then add some code in contacts.xml path app/design/frontend/our package/your template/layout

add and modify code is

    <contacts_index_index translate="label">
        <label>Contact Us Form</label>
        <reference name="head">
            <action method="setTitle" translate="title" module="contacts"><title>Contact Us</title></action>
        </reference>
        <reference name="root">
            <action method="setTemplate"><template>page/2columns-right.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>

Step5:

Then add code<?php echo $this->getChildHtml('form.additional.info'); ?> to form.phtml path app/design/frontend/our package/your template/tempate/contacts.

Step6:

Now you need to override contact us controller create file in app/code/local/Amit/Captchaown/controllers/IndexController.php....

<?php
require_once(Mage::getModuleDir('controllers','Mage_Contacts').DS.'IndexController.php');
class Amit_Captchaown_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(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
$this->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);

Mage::getSingleton('customer/session')->setCustomerFormData($this->getRequest()->getPost());
$this->getResponse()->setRedirect(Mage::getUrl('*/*/'));
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(Mage::helper('contacts')->__('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(Mage::helper('contacts')->__('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];
}

}

Now just enable captcha in contact us form go to your admin panel setting sytem->configuration->customer configuration->Captcha