Save contact form data magento controller

This tutorial explains how to save contact form data magento database. For achieving this we need to create a module and rewrite the postAction() function of the controller . Please click here to see the full module file structure and code.

Add the following code to the postAction() function of the controller. Please copy and paste the following code for full controller code.

Save contact form data magento database

require_once Mage::getModuleDir('controllers', 'Mage_Contacts').DS.'IndexController.php';
class Save_Contactform_IndexController extends Mage_Contacts_IndexController
{

    public function indexAction()
    {
        parent::indexAction();
    }

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

                if ($error) {
                    throw new Exception();
                }

                $model = Mage::getModel("contactform/contactformsave");
                $model->setData(array('created_at'=>NOW(),'name'=>$post['name'],
                    'email'=>$post['email'],'telephone'=>$post['telephone'],
                    'comment'=>$post['comment']));
                $model->save();

                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('*/*/');
        }
    }

}

Share this Tutorial