7

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

1

6 Answers 6

13

NameSpace : MyPackage and Module: MyModule

Module configuration

location : app/etc/modules/MyPackage_MyModule.xml

<config>
<modules>
    <MyPackage_MyModule>
        <active>true</active>
        <codePool>local</codePool>
    </MyPackage_MyModule>
</modules>

Create config file for this module

location : app/code/local/MyPackage/MyModule/etc/config.xml

<config>
<modules>
    <MyPackage_MyModule>
        <version>0.0.0.1</version>
    </MyPackage_MyModule>
</modules>
<global>
    <models>
        <mymodule>
            <class>MyPackage_MyModule_Model</class>
        </mymodule>
    </models>
    <events>
        <controller_action_predispatch_contacts_index_post>
            <observers>
                <mymodule>
                    <class>mymodule/observer</class>
                    <method>checkContacts</method>
                </mymodule>
            </observers>
        </controller_action_predispatch_contacts_index_post>
    </events>
</global>
<default>
    <captcha>
        <frontend>
            <areas>
                <contacts>
                    <label>Contacts Page</label>
                </contacts>
            </areas>
        </frontend>
    </captcha>
    <customer>
        <captcha>
            <always_for>
                <contacts>1</contacts>
            </always_for>
        </captcha>
    </customer>
</default>

Create a observer for that

location: app/code/local/MyPackage/MyModule/Model/Observer.php

class MyPackage_MyModule_Model_Observer
{
    public function checkContacts($observer){
        $formId = 'contacts';
        $captchaModel = Mage::helper('captcha')->getCaptcha($formId);
        if ($captchaModel->isRequired()) {
            $controller = $observer->getControllerAction();
            $word = $this->_getCaptchaString($controller->getRequest(), $formId);
            if (!$captchaModel->isCorrect($word)) {
                Mage::getSingleton('customer/session')->addError(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
                $controller->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);
                $url =  Mage::getUrl('contacts');
                $controller->getResponse()->setRedirect($url);
            }
        }
        return $this;
    }
    /**
     * Get Captcha String
     *
     * @param Varien_Object $request
     * @param string $formId
     * @return string
     */
    protected function _getCaptchaString($request, $formId)
    {
        $captchaParams = $request->getPost(Mage_Captcha_Helper_Data::INPUT_NAME_FIELD_VALUE);
        return $captchaParams[$formId];
    }
}

Create a local.xml to your active theme inside layout folder.

<layout version="0.1.0">
<contacts_index_index>
    <reference name="contactForm">
        <action method="setTemplate"><template>mymodule/contacts/form.phtml</template></action>
        <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>contacts</formId></action>
                <action method="setImgWidth"><width>230</width></action>
                <action method="setImgHeight"><width>50</width></action>
            </block>
        </block>
    </reference>
</contacts_index_index>

Now copy contacts/form.phtml to mymodule/contacts/form.phtml, add <?php echo $this->getChildHtml('form.additional.info'); ?> your requirement. example...

<li class="wide">
            <label for="comment" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Comment') ?></label>
            <div class="input-box">
                <textarea name="comment" id="comment" title="<?php echo Mage::helper('contacts')->__('Comment') ?>" class="required-entry input-text" cols="5" rows="3"></textarea>
            </div>
        </li>
        <?php echo $this->getChildHtml('form.additional.info'); ?>
    </ul>

Clear cache. Now Go to System -> Configuration -> Customer Configuration -> Captcha. Select Contact Page and Save.

3
  • What was the version(s) of Magento this solution is made for? ... was it for Magento 1.9.* Sep 29, 2014 at 16:38
  • Awesome - thanks. Worked for me on 1.8.1.0
    – Erfan
    Apr 30, 2015 at 9:16
  • this did not worked for me, because you need to extend mage captcha block to get html to your form.. this link helped me: atwix.com/magento/captcha-in-magento May 17, 2015 at 6:28
3

Not an answer to your question, but you should have a look on HoneySpam. It uses other spam-avoiding techniques which don't annoy customers.

1
  • I second that. I used HoneySpam and was happy with the results.
    – Marius
    Feb 23, 2015 at 9:37
1

as per i have done as below. it works for me.

layout.xml

<reference name="content">
    <block type="customer/form_register" name="multivendor_customer_form_register" template="multivendor/form/register.phtml">
        <action method="setShowAddressFields"><value>true</value></action>
        <block type="page/html_wrapper" name="multivendor.customer.form.register.fields.before" as="multivendor_form_fields_before" translate="label">
            <label>Form Fields Before</label>
        </block>


        <!-- Code Start For Display Captcha on Register page -->
        <block type="captcha/captcha" name="captcha">
                <reference name="head">
                    <action method="addJs"><file>mage/captcha.js</file></action>
                </reference>
                <action method="setFormId"><formId>vendor_form</formId></action>
                <action method="setImgWidth"><width>230</width></action>
                <action method="setImgHeight"><width>50</width></action>
        </block> 
        <!-- Code End For Display Captcha on Register page-->


    </block>
</reference>

form.phtml

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

controller.php in submit action (where your form submitted)

//Captcha Checking Start
$formId = 'vendor_form';
$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
if ($captchaModel->isRequired()) {
    $captchaModel = Mage::helper('captcha')->getCaptcha($formId);
    if ($captchaModel->isRequired()) {
        if (!$captchaModel->isCorrect($this->_getCaptchaString($this->getRequest(), $formId))) {
            Mage::getSingleton('core/session')->addError(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
            $this->_redirectReferer('');
            return;
        }
    }
}
//Captcha Checking End

Enjoy it works great.

1

Solution by Sohel Rana worked, except the first XML is missing a < /config > tag.

Other things to note is that Captcha need to be turned on in system configuration as well.

The contact form should be access via /contacts URL and not through a CMS page content with {{block}} set up. The CMS content {{block}} can't get updated with the XML layout to insert the captcha.

0

If you want to use core captcha functionality in contact us form you need to develop a module in your local directory. Here “Compny” is my namespace and “Captcha” is module name

First of all create module config file Compny_Captcha.xml in app/etc/modules/

<?xml version=”1.0″?>
<config>
<modules>
<Compny_Captcha>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Captcha/>
</depends>
</Compny_Captcha>
</modules>
</config>

create module config.xml file in app/code/local/Compny/Captcha/etc/config.xml

<?xml version=”1.0″?>

<config>
<modules>
<Compny_Captcha>
<version>1.8.0.0.0</version>
</Compny_Captcha>
</modules>
<global>
<models>
<captcha>
<rewrite>
<zend>Compny_Captcha_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>
<Compny_captcha before=”Mage_Contacts”>Compny_Captcha</Compny_captcha>
</modules>
</args>
</contacts>
</routers>
</frontend>
</config>

Here You can override core captcha model because captcha is not appear after customer login if you want to display captcha after customer login so you need to override Mage_Captcha_Model_Zend file _isUserAuth() function create Zend.php file in app/code/local/Compny/Captcha/Model/Zend.php

<?php

class Compny_Captcha_Model_Zend extends Mage_Captcha_Model_Zend
{

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

}

In this function you need to only comment function code.

Now create frontend layout you need to edit contacts.xml in app/design/frontend/default/default/layout/contacts.xml Here you need to add captcha block under

<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>

After that you need to call block in frontend form.phtml file in app/design/frontend/default/default/template/contacts/form.phtml you just put the below line before completing </ul> tag

<?php echo $this->getChildHtml(‘form.additional.info’); ?>

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

<?php
require_once(Mage::getModuleDir(‘controllers’,’Mage_Contacts’).DS.’IndexController.php’);
class Compny_Captcha_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 the captcha module is ready to test..

To apply captcha in contact us form go to your admin panel setting system->configuration->customer configuration->Captcha Enable captcha if it disable you can see “Contact us Form” in multiselect form area select it and save configuration. see your captcha on front-end.

4
  • @SINHI S, I did exactly as said but unfortunately it is not even show in configuration, I am sure I did something wrong I don't know hoe to explain, I hope I can show you how I have done it, Thank you
    – Khalil
    Apr 20, 2014 at 13:17
  • Can you verify, have you created all folders with the right name.
    – SIBHI S
    Apr 20, 2014 at 13:25
  • Then logout from admin and again login to admin, try flush cache and clear cache...
    – SIBHI S
    Apr 20, 2014 at 13:33
  • I did exactly same folder names, and I logout and log in from admin, and still I see same options: Create User, login, Forget password, Checkout as guest, and Register during Checkout and the new one not show
    – Khalil
    Apr 20, 2014 at 14:00
0

Here are the free Magento extensions for Easy Contact Form Captcha Download from here:- free Magento extensions

config of extension

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.