|
Quick outline how to add Magento builtin captcha mechanism to Contact Us default page.
1) To add Contact Us form to Admin/Config interface you could
a) find captcha/forms element in core_config table and add “contact_form” form name to the list
b) modify config.xml in /app/code/core/Mage/Captcha/etc
in - <frontend> - <areas> add something like
<contact_form> <label>Contact Us</label> </contact_form>
and in - <always_for>
<contact_form>1</contact_form>
Also there\\\’s a miss for translation in the config file, so you should add this to the <frontend> section:
<translate> <modules> <Mage_Captcha> <files> <default>Mage_Captcha.csv</default> </files> </Mage_Captcha> </modules> </translate>
Refresh cache. Login to Admin, and make sure Contact Us form is listed in CAPTCHA configuration
2) Modify captcha layout xml file in frontend/base/default (or your theme)
add this section
<contacts_index_index> <reference name="contactForm"> <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_form</formId> </action> <action method=\\\"setImgWidth\\\"> <width>230</width> </action> <action method=\\\"setImgHeight\\\"> <width>50</width> </action> </block> </block> </reference> </contacts_index_index>
Refresh cache
3) Modify form code in /frontend/base/default/template/contacts/form.phtml to add placeholder to render captcha layout
Add this line of code right before </ul>
<?php echo $this->getChildHtml(\\\'form.additional.info\\\'); ?>
4) FInal part - how to\\\"trap\\\" the post from the Contact Us form and check the captcha
Mage uses Events and Observer to achieve this, and it works very well for the forms/events they have implemented this feature. I was not able to find events specific for Contact Us form, so, IMHO the most obvious solution is to override indexController in code/core/Mage/Contacts/controllers and in the postAction method, inside try block add the following code:
$formId = \\\'contact_form\\\'; $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; } }
and add this \\\"utility method to the controller class:
protected function _getCaptchaString($request, $formId) { $captchaParams = $request->getPost(Mage_Captcha_Helper_Data::INPUT_NAME_FIELD_VALUE); return $captchaParams[$formId]; }
5) Refresh cache, and give it a try
|