Magento: Override the Contacts Core Controller

So you want to add some additional functionality when the user posts stuff to your contact form.  You will need to either add an observer or override the contact form controller.  Here is how to do the latter.

1. Create a new file inside app/etc/modules to tell Magento to use your new module that you are about to create:

/app/etc/modules/Mysite_Contacts.xml

which will contain:

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

2. Create new “module” folder structure in your own namespace

Mysite->Contacts
Mysite->Contacts->controllers
Mysite->Contacts->etc

3. Inside the Mysite->Contacts->etc  folder create config.xml to specify which router we are overriding. i.e. Look at our module first.

<?xml version=”1.0″?>
<config>
<modules>
<Mysite_Contacts>
<version>1.0</version>
</Mysite_Contacts>
</modules>

<frontend>
<routers>
<contacts>
<args>
<modules>
<Mysite_Contacts before=”Mage_Contacts”>Mysite_Contacts</Mysite_Contacts>
</modules>
</args>
</contacts>
</routers>
</frontend>
</config>

4. Copy the core controller file, in this case app/code/Mage/Contacts/controllers/IndexController.php  into our module so we have

app/code/local/Mysite/Contacts/controllers/IndexController.php

5. You will now need to edit the new controller file.  Change the class name and extends parts at the top of the script.  The “extends” is the core class   “Mage_Contacts_IndexController”  and the actual classname should refer to Mysite  giving:

class Mysite_Contacts_IndexController extends Mage_Contacts_IndexController{

}

HOWEVER, if you run this now you will get an error along the lines of cannot find Mage_Contacts_IndexController!!?!  To get around this you need to add an additional line before the class definition to make sure that Magento includes the original controller file:

require_once ‘Mage/Contacts/controllers/IndexController.php’; // <— Need this to correctly path to the controller
class Mysite_Contacts_IndexController extends Mage_Contacts_IndexController
{…
}

6. In your new controller file only leave in the functionality that you want to override, in our case probably what happens in the postAction().  Remove everything else and let the original controller code deal with it.

 

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Apply your human brain cells and complete this highly complicated maths problem *