PHP Magento Tips

Save Contact Forms Data to Database and Add Default Captcha To Contact Form In Magento

Rate this posting:
{[['']]}

Magento doesn’t store contact form details by default but you can add this useful facility with a little bit of coding.

For learning purpose we add two new field in contact form.

in app/design/frontend/rwd/default/template/contacts/form.phtml add below code after telephone field:

<li>
    <label for="fax"><?php echo Mage::helper('contacts')->__('Fax') ?></label>
 <div class="input-box">
  <input name="fax" id="fax" title="<?php echo Mage::helper('core')->quoteEscape(Mage::helper('contacts')->__('Fax')) ?>" value="" class="input-text" type="tel" />
 </div>
</li>

<li>
 <label for="company_name"><?php echo Mage::helper('contacts')->__('Company Name') ?></label>
 <div class="input-box">
  <input name="company_name" id="company_name" title="<?php echo Mage::helper('core')->quoteEscape(Mage::helper('contacts')->__('Company Name')) ?>" value="" class="input-text" type="text" />
 </div>
</li>


Step1: Create File in app/etc/modules/Mycompany_Contactsave.xml and add below code:

<?xml version="1.0"?>

<config>

    <modules>

        <Mycompany_Contactsave>

            <active>true</active>

            <codePool>local</codePool>

            <depends>

                <Mage_Core />

             </depends>

        </Mycompany_Contactsave>

    </modules>

</config>

Step 2: Create config.xml and adminhtml.xml file.
Create file app/code/local/Mycompany/Contactsave/etc/config.xml and app/code/local/Mycompany/Contactsave/etc/adminhtml.xml and add below code in it.

<?xml version="1.0"?>
<config>
    <modules>
        <Mycompany_Contactsave>
            <version>1.0.0</version>
        </Mycompany_Contactsave>
    </modules>
    <global>
        <resources>
            <mycompany_contactsave_setup>
                <setup>
                    <module>Mycompany_Contactsave</module>
                    <class>Mycompany_Contactsave_Model_Resource_Setup</class>
                </setup>
            </mycompany_contactsave_setup>
        </resources>
        <blocks>
            <mycompany_contactsave>
                <class>Mycompany_Contactsave_Block</class>
            </mycompany_contactsave>
        </blocks>
        <helpers>
            <mycompany_contactsave>
                <class>Mycompany_Contactsave_Helper</class>
            </mycompany_contactsave>
        </helpers>
        <models>
            <mycompany_contactsave>
                <class>Mycompany_Contactsave_Model</class>
                <resourceModel>mycompany_contactsave_resource</resourceModel>
            </mycompany_contactsave>
            <mycompany_contactsave_resource>
                <class>Mycompany_Contactsave_Model_Resource</class>
                <entities>
                    <contactdata>
                        <table>mycompany_contactsave_contactdata</table>
                    </contactdata>
                </entities>
            </mycompany_contactsave_resource>
        </models>
        <events>
            <controller_action_predispatch_contacts_index_post>
                <observers>
                    <Mycompany_Contactsave>
                        <class>mycompany_contactsave/observer</class>
                        <method>checkContacts</method>
                    </Mycompany_Contactsave>
                </observers>
            </controller_action_predispatch_contacts_index_post>
        </events>
    </global>
    <adminhtml>
        <layout>
            <updates>
                <mycompany_contactsave>
                    <file>mycompany_contactsave.xml</file>
                </mycompany_contactsave>
            </updates>
        </layout>
    </adminhtml>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <Mycompany_Contactsave before="Mage_Adminhtml">Mycompany_Contactsave_Adminhtml</Mycompany_Contactsave>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <frontend>
  <routers>
   <contacts>
     <args>
      <modules>
      <Mycompany_Contactsave before="Mage_Contacts_IndexController">Mycompany_Contactsave</Mycompany_Contactsave>
      </modules>
     </args>
    </contacts>
   </routers>
   <layout>
            <updates>
                <mycompany_contactsave>
                    <file>mycompany_contactsave.xml</file>
                </mycompany_contactsave>
            </updates>
        </layout>
 </frontend>
 <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>
</config>

<?xml version="1.0"?>
<config>
    <acl>
        <resources>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <mycompany_contactsave translate="title" module="mycompany_contactsave">
                                        <title>Contactsave</title>
                                    </mycompany_contactsave>
                                </children>
                            </config>
                        </children>
                    </system>
                    <mycompany_contactsave translate="title" module="mycompany_contactsave">
                        <title>Manage Contact Forms</title>
                        <children>
                            <contactdata translate="title" module="mycompany_contactsave">
                                <title>Contact Data</title>
                                <sort_order>0</sort_order>
                            </contactdata>
                        </children>
                    </mycompany_contactsave>
                </children>
            </admin>
        </resources>
    </acl>
    <menu>
     <customer>
      <children>
          <mycompany_contactsave translate="title" module="mycompany_contactsave">
              <title>Manage Contact Forms</title>
              <sort_order>35</sort_order>
              <children>
                  <contactdata translate="title" module="mycompany_contactsave">
                      <title>Contact Data</title>
                      <action>adminhtml/contactsave_contactdata</action>
                      <sort_order>0</sort_order>
                  </contactdata>
              </children>
          </mycompany_contactsave>
      </children>
     </customer>
    </menu>
</config>

Step 3: Create app/code/local/Mycompany/Contactsave/sql/mycompany_contactsave_setup/install-1.0.0.php file and add below code in it.

<?php
$this->startSetup();
$table = $this->getConnection()
    ->newTable($this->getTable('mycompany_contactsave/contactdata'))
    ->addColumn(
        'entity_id',
        Varien_Db_Ddl_Table::TYPE_INTEGER,
        null,
        array(
            'identity'  => true,
            'nullable'  => false,
            'primary'   => true,
        ),
        'Contact Data ID'
    )
    ->addColumn(
        'customer_name',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(
            'nullable'  => false,
        ),
        'Customer Name'
    )
    ->addColumn(
        'customer_email',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(
            'nullable'  => false,
        ),
        'Customer Email'
    )
    ->addColumn(
        'customer_phone',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Customer Telephone'
    )
    ->addColumn(
        'customer_fax',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Customer Fax'
    )
    ->addColumn(
        'customer_company',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Customer Company Name'
    )
    ->addColumn(
        'customer_comment',
        Varien_Db_Ddl_Table::TYPE_TEXT, '64k',
        array(
            'nullable'  => false,
        ),
        'Customer Comment'
    )
    ->addColumn(
        'status',
        Varien_Db_Ddl_Table::TYPE_SMALLINT, null,
        array(),
        'Enabled'
    )
    ->addColumn(
        'updated_at',
        Varien_Db_Ddl_Table::TYPE_TIMESTAMP,
        null,
        array(),
        'Contact Data Modification Time'
    )
    ->addColumn(
        'created_at',
        Varien_Db_Ddl_Table::TYPE_TIMESTAMP,
        null,
        array(),
        'Contact Data Creation Time'
    ) 
    ->setComment('Contact Data Table');
$this->getConnection()->createTable($table);
$this->endSetup();

Step 4: Create app/code/local/Mycompany/Contactsave/Helper/Data.php file and add below code in it.

<?php
class Mycompany_Contactsave_Helper_Data extends Mage_Core_Helper_Abstract
{
    /**
     * convert array to options
     *
     * @access public
     * @param $options
     * @return array
     * @author Ultimate Module Creator
     */
    public function convertOptions($options)
    {
        $converted = array();
        foreach ($options as $option) {
            if (isset($option['value']) && !is_array($option['value']) &&
                isset($option['label']) && !is_array($option['label'])) {
                $converted[$option['value']] = $option['label'];
            }
        }
        return $converted;
    }
}

Step 5: Create Model Resource Files.

a:> Create file in app/code/local/Mycompany/Contactsave/Model/Contactdata.php and add below code:

<?php
class Mycompany_Contactsave_Model_Contactdata extends Mage_Core_Model_Abstract
{
    /**
     * Entity code.
     * Can be used as part of method name for entity processing
     */
    const ENTITY    = 'mycompany_contactsave_contactdata';
    const CACHE_TAG = 'mycompany_contactsave_contactdata';

    /**
     * Prefix of model events names
     *
     * @var string
     */
    protected $_eventPrefix = 'mycompany_contactsave_contactdata';

    /**
     * Parameter name in event
     *
     * @var string
     */
    protected $_eventObject = 'contactdata';

    /**
     * constructor
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function _construct()
    {
        parent::_construct();
        $this->_init('mycompany_contactsave/contactdata');
    }

    /**
     * before save contact data
     *
     * @access protected
     * @return Mycompany_Contactsave_Model_Contactdata
     * @author Ultimate Module Creator
     */
    protected function _beforeSave()
    {
        parent::_beforeSave();
        $now = Mage::getSingleton('core/date')->gmtDate();
        if ($this->isObjectNew()) {
            $this->setCreatedAt($now);
        }
        $this->setUpdatedAt($now);
        return $this;
    }

    /**
     * save contact data relation
     *
     * @access public
     * @return Mycompany_Contactsave_Model_Contactdata
     * @author Ultimate Module Creator
     */
    protected function _afterSave()
    {
        return parent::_afterSave();
    }

    /**
     * get default values
     *
     * @access public
     * @return array
     * @author Ultimate Module Creator
     */
    public function getDefaultValues()
    {
        $values = array();
        $values['status'] = 1;
        return $values;
    }
    
}

B:> create file app/code/local/Mycompany/Contactsave/Model/Resource/Contactdata.php and add below code in it.

<?php
class Mycompany_Contactsave_Model_Resource_Contactdata extends Mage_Core_Model_Resource_Db_Abstract
{

    /**
     * constructor
     *
     * @access public
     * @author Ultimate Module Creator
     */
    public function _construct()
    {
        $this->_init('mycompany_contactsave/contactdata', 'entity_id');
    }
}

C:> create file in app/code/local/Mycompany/Contactsave/Model/Resource/Setup.php and add below code in it.

<?php
class Mycompany_Contactsave_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup
{
}

D:> create file in app/code/local/Mycompany/Contactsave/Model/Resource/Contactdata/Collection.php and add below code in it.

<?php
class Mycompany_Contactsave_Model_Resource_Contactdata_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    protected $_joinedFields = array();

    /**
     * constructor
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    protected function _construct()
    {
        parent::_construct();
        $this->_init('mycompany_contactsave/contactdata');
    }

    /**
     * get contact datas as array
     *
     * @access protected
     * @param string $valueField
     * @param string $labelField
     * @param array $additional
     * @return array
     * @author Ultimate Module Creator
     */
    protected function _toOptionArray($valueField='entity_id', $labelField='customer_name', $additional=array())
    {
        return parent::_toOptionArray($valueField, $labelField, $additional);
    }

    /**
     * get options hash
     *
     * @access protected
     * @param string $valueField
     * @param string $labelField
     * @return array
     * @author Ultimate Module Creator
     */
    protected function _toOptionHash($valueField='entity_id', $labelField='customer_name')
    {
        return parent::_toOptionHash($valueField, $labelField);
    }

    /**
     * Get SQL for get record count.
     * Extra GROUP BY strip added.
     *
     * @access public
     * @return Varien_Db_Select
     * @author Ultimate Module Creator
     */
    public function getSelectCountSql()
    {
        $countSelect = parent::getSelectCountSql();
        $countSelect->reset(Zend_Db_Select::GROUP);
        return $countSelect;
    }
}

Step 6: Create Block Files

a:> Create file in app/code/local/Mycompany/Contactsave/Block/Adminhtml/Contactdata.php and add below code in it:

<?php
class Mycompany_Contactsave_Block_Adminhtml_Contactdata extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    /**
     * constructor
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function __construct()
    {
        $this->_controller         = 'adminhtml_contactdata';
        $this->_blockGroup         = 'mycompany_contactsave';
        parent::__construct();
        $this->_headerText         = Mage::helper('mycompany_contactsave')->__('Contact Data');
        $this->_updateButton('add', 'label', Mage::helper('mycompany_contactsave')->__('Add Contact Data'));
        $this->_removeButton('add');

    }
}

B:> Create file in app/code/local/Mycompany/Contactsave/Block/Adminhtml/Contactdata/Edit.php and add below code in it:

<?php
class Mycompany_Contactsave_Block_Adminhtml_Contactdata_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    /**
     * constructor
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function __construct()
    {
        parent::__construct();
        $this->_blockGroup = 'mycompany_contactsave';
        $this->_controller = 'adminhtml_contactdata';
        $this->_updateButton(
            'save',
            'label',
            Mage::helper('mycompany_contactsave')->__('Save Contact Data')
        );
        $this->_updateButton(
            'delete',
            'label',
            Mage::helper('mycompany_contactsave')->__('Delete Contact Data')
        );
        $this->_addButton(
            'saveandcontinue',
            array(
                'label'   => Mage::helper('mycompany_contactsave')->__('Save And Continue Edit'),
                'onclick' => 'saveAndContinueEdit()',
                'class'   => 'save',
            ),
            -100
        );
        $this->_formScripts[] = "
            function saveAndContinueEdit() {
                editForm.submit($('edit_form').action+'back/edit/');
            }
        ";
    }

    /**
     * get the edit form header
     *
     * @access public
     * @return string
     * @author Ultimate Module Creator
     */
    public function getHeaderText()
    {
        if (Mage::registry('current_contactdata') && Mage::registry('current_contactdata')->getId()) {
            return Mage::helper('mycompany_contactsave')->__(
                "Edit Contact Data '%s'",
                $this->escapeHtml(Mage::registry('current_contactdata')->getCustomerName())
            );
        } else {
            return Mage::helper('mycompany_contactsave')->__('Add Contact Data');
        }
    }
}

C:> create file in app/code/local/Mycompany/Contactsave/Block/Adminhtml/Contactdata/Grid.php and add below code in it:

<?php
class Mycompany_Contactsave_Block_Adminhtml_Contactdata_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    /**
     * constructor
     *
     * @access public
     * @author Ultimate Module Creator
     */
    public function __construct()
    {
        parent::__construct();
        $this->setId('contactdataGrid');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
    }

    /**
     * prepare collection
     *
     * @access protected
     * @return Mycompany_Contactsave_Block_Adminhtml_Contactdata_Grid
     * @author Ultimate Module Creator
     */
    protected function _prepareCollection()
    {
        $collection = Mage::getModel('mycompany_contactsave/contactdata')
            ->getCollection();
        
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    /**
     * prepare grid collection
     *
     * @access protected
     * @return Mycompany_Contactsave_Block_Adminhtml_Contactdata_Grid
     * @author Ultimate Module Creator
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            'entity_id',
            array(
                'header' => Mage::helper('mycompany_contactsave')->__('Id'),
                'index'  => 'entity_id',
                'type'   => 'number'
            )
        );
        $this->addColumn(
            'customer_name',
            array(
                'header'    => Mage::helper('mycompany_contactsave')->__('Customer Name'),
                'align'     => 'left',
                'index'     => 'customer_name',
            )
        );
        
        $this->addColumn(
            'status',
            array(
                'header'  => Mage::helper('mycompany_contactsave')->__('Status'),
                'index'   => 'status',
                'type'    => 'options',
                'options' => array(
                    '1' => Mage::helper('mycompany_contactsave')->__('Enabled'),
                    '0' => Mage::helper('mycompany_contactsave')->__('Disabled'),
                )
            )
        );
        $this->addColumn(
            'customer_email',
            array(
                'header' => Mage::helper('mycompany_contactsave')->__('Customer Email'),
                'index'  => 'customer_email',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'customer_phone',
            array(
                'header' => Mage::helper('mycompany_contactsave')->__('Customer Telephone'),
                'index'  => 'customer_phone',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'customer_fax',
            array(
                'header' => Mage::helper('mycompany_contactsave')->__('Customer Fax'),
                'index'  => 'customer_fax',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'customer_company',
            array(
                'header' => Mage::helper('mycompany_contactsave')->__('Customer Company Name'),
                'index'  => 'customer_company',
                'type'=> 'text',

            )
        );
        $this->addColumn(
          'customer_comment',
          array(
            'header' => Mage::helper('mycompany_contactsave')->__('Customer Comment'),
            'index'  => 'customer_comment',
            'type'=> 'text',
        
          )
        );
        $this->addColumn(
            'created_at',
            array(
                'header' => Mage::helper('mycompany_contactsave')->__('Created at'),
                'index'  => 'created_at',
                'width'  => '120px',
                'type'   => 'datetime',
            )
        );
        $this->addColumn(
            'updated_at',
            array(
                'header'    => Mage::helper('mycompany_contactsave')->__('Updated at'),
                'index'     => 'updated_at',
                'width'     => '120px',
                'type'      => 'datetime',
            )
        );
        $this->addColumn(
            'action',
            array(
                'header'  =>  Mage::helper('mycompany_contactsave')->__('Action'),
                'width'   => '100',
                'type'    => 'action',
                'getter'  => 'getId',
                'actions' => array(
                    array(
                        'caption' => Mage::helper('mycompany_contactsave')->__('Edit'),
                        'url'     => array('base'=> '*/*/edit'),
                        'field'   => 'id'
                    )
                ),
                'filter'    => false,
                'is_system' => true,
                'sortable'  => false,
            )
        );
        $this->addExportType('*/*/exportCsv', Mage::helper('mycompany_contactsave')->__('CSV'));
        $this->addExportType('*/*/exportExcel', Mage::helper('mycompany_contactsave')->__('Excel'));
        $this->addExportType('*/*/exportXml', Mage::helper('mycompany_contactsave')->__('XML'));
        return parent::_prepareColumns();
    }

    /**
     * prepare mass action
     *
     * @access protected
     * @return Mycompany_Contactsave_Block_Adminhtml_Contactdata_Grid
     * @author Ultimate Module Creator
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('entity_id');
        $this->getMassactionBlock()->setFormFieldName('contactdata');
        $this->getMassactionBlock()->addItem(
            'delete',
            array(
                'label'=> Mage::helper('mycompany_contactsave')->__('Delete'),
                'url'  => $this->getUrl('*/*/massDelete'),
                'confirm'  => Mage::helper('mycompany_contactsave')->__('Are you sure?')
            )
        );
        $this->getMassactionBlock()->addItem(
            'status',
            array(
                'label'      => Mage::helper('mycompany_contactsave')->__('Change status'),
                'url'        => $this->getUrl('*/*/massStatus', array('_current'=>true)),
                'additional' => array(
                    'status' => array(
                        'name'   => 'status',
                        'type'   => 'select',
                        'class'  => 'required-entry',
                        'label'  => Mage::helper('mycompany_contactsave')->__('Status'),
                        'values' => array(
                            '1' => Mage::helper('mycompany_contactsave')->__('Enabled'),
                            '0' => Mage::helper('mycompany_contactsave')->__('Disabled'),
                        )
                    )
                )
            )
        );
        return $this;
    }

    /**
     * get the row url
     *
     * @access public
     * @param Mycompany_Contactsave_Model_Contactdata
     * @return string
     * @author Ultimate Module Creator
     */
    public function getRowUrl($row)
    {
        return $this->getUrl('*/*/edit', array('id' => $row->getId()));
    }

    /**
     * get the grid url
     *
     * @access public
     * @return string
     * @author Ultimate Module Creator
     */
    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', array('_current'=>true));
    }

    /**
     * after collection load
     *
     * @access protected
     * @return Mycompany_Contactsave_Block_Adminhtml_Contactdata_Grid
     * @author Ultimate Module Creator
     */
    protected function _afterLoadCollection()
    {
        $this->getCollection()->walk('afterLoad');
        parent::_afterLoadCollection();
    }
}

D:>  Create file in app/code/local/Mycompany/Contactsave/Block/Adminhtml/Contactdata/Edit/Form.php and add below code in it:

<?php
class Mycompany_Contactsave_Block_Adminhtml_Contactdata_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    /**
     * prepare form
     *
     * @access protected
     * @return Mycompany_Contactsave_Block_Adminhtml_Contactdata_Edit_Form
     * @author Ultimate Module Creator
     */
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(
            array(
                'id'         => 'edit_form',
                'action'     => $this->getUrl(
                    '*/*/save',
                    array(
                        'id' => $this->getRequest()->getParam('id')
                    )
                ),
                'method'     => 'post',
                'enctype'    => 'multipart/form-data'
            )
        );
        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }
}

E:> Create file in app/code/local/Mycompany/Contactsave/Block/Adminhtml/Contactdata/Edit/Tabs.php and add below code in it:

<?php
class Mycompany_Contactsave_Block_Adminhtml_Contactdata_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
    /**
     * Initialize Tabs
     *
     * @access public
     * @author Ultimate Module Creator
     */
    public function __construct()
    {
        parent::__construct();
        $this->setId('contactdata_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle(Mage::helper('mycompany_contactsave')->__('Contact Data'));
    }

    /**
     * before render html
     *
     * @access protected
     * @return Mycompany_Contactsave_Block_Adminhtml_Contactdata_Edit_Tabs
     * @author Ultimate Module Creator
     */
    protected function _beforeToHtml()
    {
        $this->addTab(
            'form_contactdata',
            array(
                'label'   => Mage::helper('mycompany_contactsave')->__('Contact Data'),
                'title'   => Mage::helper('mycompany_contactsave')->__('Contact Data'),
                'content' => $this->getLayout()->createBlock(
                    'mycompany_contactsave/adminhtml_contactdata_edit_tab_form'
                )
                ->toHtml(),
            )
        );
        return parent::_beforeToHtml();
    }

    /**
     * Retrieve contact data entity
     *
     * @access public
     * @return Mycompany_Contactsave_Model_Contactdata
     * @author Ultimate Module Creator
     */
    public function getContactdata()
    {
        return Mage::registry('current_contactdata');
    }
}

F:> Create file in app/code/local/Mycompany/Contactsave/Block/Adminhtml/Contactdata/Edit/Tab/Form.php and add below code in it:

<?php
class Mycompany_Contactsave_Block_Adminhtml_Contactdata_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
    /**
     * prepare the form
     *
     * @access protected
     * @return Mycompany_Contactsave_Block_Adminhtml_Contactdata_Edit_Tab_Form
     * @author Ultimate Module Creator
     */
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $form->setHtmlIdPrefix('contactdata_');
        $form->setFieldNameSuffix('contactdata');
        $this->setForm($form);
        $fieldset = $form->addFieldset(
            'contactdata_form',
            array('legend' => Mage::helper('mycompany_contactsave')->__('Contact Data'))
        );

        $fieldset->addField(
            'customer_name',
            'text',
            array(
                'label' => Mage::helper('mycompany_contactsave')->__('Customer Name'),
                'name'  => 'customer_name',
                'required'  => true,
                'class' => 'required-entry',

           )
        );

        $fieldset->addField(
            'customer_email',
            'text',
            array(
                'label' => Mage::helper('mycompany_contactsave')->__('Customer Email'),
                'name'  => 'customer_email',
                'required'  => true,
                'class' => 'required-entry',

           )
        );

        $fieldset->addField(
            'customer_phone',
            'text',
            array(
                'label' => Mage::helper('mycompany_contactsave')->__('Customer Telephone'),
                'name'  => 'customer_phone',

           )
        );

        $fieldset->addField(
            'customer_fax',
            'text',
            array(
                'label' => Mage::helper('mycompany_contactsave')->__('Customer Fax'),
                'name'  => 'customer_fax',

           )
        );

        $fieldset->addField(
            'customer_company',
            'text',
            array(
                'label' => Mage::helper('mycompany_contactsave')->__('Customer Company Name'),
                'name'  => 'customer_company',

           )
        );

        $fieldset->addField(
            'customer_comment',
            'textarea',
            array(
                'label' => Mage::helper('mycompany_contactsave')->__('Customer Comment'),
                'name'  => 'customer_comment',
                'required'  => true,
                'class' => 'required-entry',

           )
        );
        $fieldset->addField(
            'status',
            'select',
            array(
                'label'  => Mage::helper('mycompany_contactsave')->__('Status'),
                'name'   => 'status',
                'values' => array(
                    array(
                        'value' => 1,
                        'label' => Mage::helper('mycompany_contactsave')->__('Enabled'),
                    ),
                    array(
                        'value' => 0,
                        'label' => Mage::helper('mycompany_contactsave')->__('Disabled'),
                    ),
                ),
            )
        );
        $formValues = Mage::registry('current_contactdata')->getDefaultValues();
        if (!is_array($formValues)) {
            $formValues = array();
        }
        if (Mage::getSingleton('adminhtml/session')->getContactdataData()) {
            $formValues = array_merge($formValues, Mage::getSingleton('adminhtml/session')->getContactdataData());
            Mage::getSingleton('adminhtml/session')->setContactdataData(null);
        } elseif (Mage::registry('current_contactdata')) {
            $formValues = array_merge($formValues, Mage::registry('current_contactdata')->getData());
        }
        $form->setValues($formValues);
        return parent::_prepareForm();
    }
}

Step 7: Create Controller file. Create app/code/local/Mycompany/Contactsave/Controller/Adminhtml/Contactsave.php file and add below code in it:

<?php
class Mycompany_Contactsave_Controller_Adminhtml_Contactsave extends Mage_Adminhtml_Controller_Action
{
    /**
     * upload file and get the uploaded name
     *
     * @access public
     * @param string $input
     * @param string $destinationFolder
     * @param array $data
     * @return string
     * @author Ultimate Module Creator
     */
    protected function _uploadAndGetName($input, $destinationFolder, $data)
    {
        try {
            if (isset($data[$input]['delete'])) {
                return '';
            } else {
                $uploader = new Varien_File_Uploader($input);
                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(true);
                $uploader->setAllowCreateFolders(true);
                $result = $uploader->save($destinationFolder);
                return $result['file'];
            }
        } catch (Exception $e) {
            if ($e->getCode() != Varien_File_Uploader::TMP_NAME_EMPTY) {
                throw $e;
            } else {
                if (isset($data[$input]['value'])) {
                    return $data[$input]['value'];
                }
            }
        }
        return '';
    }
}

Step 8: Create controllers. Create file in app/code/local/Mycompany/Contactsave/controllers/Adminhtml/Contactsave/ContactdataController.php and add below code in it.

<?php
class Mycompany_Contactsave_Adminhtml_Contactsave_ContactdataController extends Mycompany_Contactsave_Controller_Adminhtml_Contactsave
{
    /**
     * init the contact data
     *
     * @access protected
     * @return Mycompany_Contactsave_Model_Contactdata
     */
    protected function _initContactdata()
    {
        $contactdataId  = (int) $this->getRequest()->getParam('id');
        $contactdata    = Mage::getModel('mycompany_contactsave/contactdata');
        if ($contactdataId) {
            $contactdata->load($contactdataId);
        }
        Mage::register('current_contactdata', $contactdata);
        return $contactdata;
    }

    /**
     * default action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function indexAction()
    {
        $this->loadLayout();
        $this->_title(Mage::helper('mycompany_contactsave')->__('Manage Contact Forms'))
             ->_title(Mage::helper('mycompany_contactsave')->__('Contact Datas'));
        $this->renderLayout();
    }

    /**
     * grid action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function gridAction()
    {
        $this->loadLayout()->renderLayout();
    }

    /**
     * edit contact data - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function editAction()
    {
        $contactdataId    = $this->getRequest()->getParam('id');
        $contactdata      = $this->_initContactdata();
        if ($contactdataId && !$contactdata->getId()) {
            $this->_getSession()->addError(
                Mage::helper('mycompany_contactsave')->__('This contact data no longer exists.')
            );
            $this->_redirect('*/*/');
            return;
        }
        $data = Mage::getSingleton('adminhtml/session')->getContactdataData(true);
        if (!empty($data)) {
            $contactdata->setData($data);
        }
        Mage::register('contactdata_data', $contactdata);
        $this->loadLayout();
        $this->_title(Mage::helper('mycompany_contactsave')->__('Manage Contact Forms'))
             ->_title(Mage::helper('mycompany_contactsave')->__('Contact Datas'));
        if ($contactdata->getId()) {
            $this->_title($contactdata->getCustomerName());
        } else {
            $this->_title(Mage::helper('mycompany_contactsave')->__('Add contact data'));
        }
        if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
            $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
        }
        $this->renderLayout();
    }

    /**
     * new contact data action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function newAction()
    {
        $this->_forward('edit');
    }

    /**
     * save contact data - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function saveAction()
    {
        if ($data = $this->getRequest()->getPost('contactdata')) {
            try {
                $contactdata = $this->_initContactdata();
                $contactdata->addData($data);
                $contactdata->save();
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('mycompany_contactsave')->__('Contact Data was successfully saved')
                );
                Mage::getSingleton('adminhtml/session')->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    $this->_redirect('*/*/edit', array('id' => $contactdata->getId()));
                    return;
                }
                $this->_redirect('*/*/');
                return;
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setContactdataData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            } catch (Exception $e) {
                Mage::logException($e);
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('mycompany_contactsave')->__('There was a problem saving the contact data.')
                );
                Mage::getSingleton('adminhtml/session')->setContactdataData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(
            Mage::helper('mycompany_contactsave')->__('Unable to find contact data to save.')
        );
        $this->_redirect('*/*/');
    }

    /**
     * delete contact data - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function deleteAction()
    {
        if ( $this->getRequest()->getParam('id') > 0) {
            try {
                $contactdata = Mage::getModel('mycompany_contactsave/contactdata');
                $contactdata->setId($this->getRequest()->getParam('id'))->delete();
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('mycompany_contactsave')->__('Contact Data was successfully deleted.')
                );
                $this->_redirect('*/*/');
                return;
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('mycompany_contactsave')->__('There was an error deleting contact data.')
                );
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                Mage::logException($e);
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(
            Mage::helper('mycompany_contactsave')->__('Could not find contact data to delete.')
        );
        $this->_redirect('*/*/');
    }

    /**
     * mass delete contact data - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function massDeleteAction()
    {
        $contactdataIds = $this->getRequest()->getParam('contactdata');
        if (!is_array($contactdataIds)) {
            Mage::getSingleton('adminhtml/session')->addError(
                Mage::helper('mycompany_contactsave')->__('Please select contact datas to delete.')
            );
        } else {
            try {
                foreach ($contactdataIds as $contactdataId) {
                    $contactdata = Mage::getModel('mycompany_contactsave/contactdata');
                    $contactdata->setId($contactdataId)->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('mycompany_contactsave')->__('Total of %d contact datas were successfully deleted.', count($contactdataIds))
                );
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('mycompany_contactsave')->__('There was an error deleting contact datas.')
                );
                Mage::logException($e);
            }
        }
        $this->_redirect('*/*/index');
    }

    /**
     * mass status change - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function massStatusAction()
    {
        $contactdataIds = $this->getRequest()->getParam('contactdata');
        if (!is_array($contactdataIds)) {
            Mage::getSingleton('adminhtml/session')->addError(
                Mage::helper('mycompany_contactsave')->__('Please select contact datas.')
            );
        } else {
            try {
                foreach ($contactdataIds as $contactdataId) {
                $contactdata = Mage::getSingleton('mycompany_contactsave/contactdata')->load($contactdataId)
                            ->setStatus($this->getRequest()->getParam('status'))
                            ->setIsMassupdate(true)
                            ->save();
                }
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d contact datas were successfully updated.', count($contactdataIds))
                );
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('mycompany_contactsave')->__('There was an error updating contact datas.')
                );
                Mage::logException($e);
            }
        }
        $this->_redirect('*/*/index');
    }

    /**
     * export as csv - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function exportCsvAction()
    {
        $fileName   = 'contactdata.csv';
        $content    = $this->getLayout()->createBlock('mycompany_contactsave/adminhtml_contactdata_grid')
            ->getCsv();
        $this->_prepareDownloadResponse($fileName, $content);
    }

    /**
     * export as MsExcel - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function exportExcelAction()
    {
        $fileName   = 'contactdata.xls';
        $content    = $this->getLayout()->createBlock('mycompany_contactsave/adminhtml_contactdata_grid')
            ->getExcelFile();
        $this->_prepareDownloadResponse($fileName, $content);
    }

    /**
     * export as xml - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function exportXmlAction()
    {
        $fileName   = 'contactdata.xml';
        $content    = $this->getLayout()->createBlock('mycompany_contactsave/adminhtml_contactdata_grid')
            ->getXml();
        $this->_prepareDownloadResponse($fileName, $content);
    }

    /**
     * Check if admin has permissions to visit related pages
     *
     * @access protected
     * @return boolean
     * @author Ultimate Module Creator
     */
    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('mycompany_contactsave/contactdata');
    }
}

Step 9: Create controller file to override default contacts postAction and save data in database.

create file in app/code/local/Mycompany/Contactsave/controllers/IndexController.php file and add below code in it:

<?php
include_once("Mage/Contacts/controllers/IndexController.php");
class Mycompany_Contactsave_IndexController extends Mage_Contacts_IndexController
{
    public function postAction()
    {
        $post = $this->getRequest()->getPost();
        if ( $this->getRequest()->isPost() && $this->getRequest()->getPost('email') ) {
         
         $name          = $this->getRequest()->getPost('name');
         $email         = (string) $this->getRequest()->getPost('email');
         $telephone     = $this->getRequest()->getPost('telephone');
         $fax           = $this->getRequest()->getPost('fax');
         $company_name  = $this->getRequest()->getPost('company_name');
         $comment      = $this->getRequest()->getPost('comment');
         
            $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();
                }
                
                $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);
    
                $dt = date('d-m-Y H:i:s');
                $contact = Mage::getModel('mycompany_contactsave/contactdata');
                $contact->setData('customer_name', $name);
                $contact->setData('customer_email', $email);
                $contact->setData('customer_phone', $telephone);
                $contact->setData('customer_fax', $fax);
                $contact->setData('customer_company', $company_name);
                $contact->setData('customer_comment', $comment);
                $contact->setData('status', 1);
                $contact->setData('updated_at', $dt);
                $contact->setData('created_at', $dt);
                $contact->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('*/*/');
                $this->_redirectReferer();

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

}

Step 10: Create file in app/code/local/Mycompany/Contactsave/Model/Observer.php and add below code for captcha.

<?php
class Mycompany_Contactsave_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];
    }
}


Step 11: Create Frontend layout update file at app/design/frontend/rwd/default/layout/mycompany_contactsave.xml and add below code in it.

<?xml version="1.0"?>

<layout>

    <contacts_index_index>

        <reference name="contactForm">

            <action method="setTemplate"><template>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>

</layout>

For Captcha add below code in app/design/frontend/rwd/default/template/contacts/form.phtml at the end of comment div.

<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('core')->quoteEscape(Mage::helper('contacts')->__('Comment')) ?>" class="required-entry input-text" cols="5" rows="3"></textarea>
 </div>
 <?php echo $this->getChildHtml('form.additional.info'); ?>
</li>  

To Enable Captcha Go to System -> Configuration -> Customer Configuration -> Captcha Select Contact Page and Save

Step 12: Create admin layout file. Create file in app/design/adminhtml/default/default/layout/mycompany_contactsave.xml and add below code:

<?xml version="1.0"?>
<layout>
    <adminhtml_contactsave_contactdata_index>
        <reference name="menu">
            <action method="setActive">
                <menupath>customer/contactdata</menupath>
            </action>
        </reference>
        <reference name="content">
            <block type="mycompany_contactsave/adminhtml_contactdata" name="contactdata" />

        </reference>
    </adminhtml_contactsave_contactdata_index>
    <adminhtml_contactsave_contactdata_grid>
        <block type="core/text_list" name="root" output="toHtml">
            <block type="mycompany_contactsave/adminhtml_contactdata_grid" name="contactdata_grid"/>
        </block>
    </adminhtml_contactsave_contactdata_grid>
    <!-- Contactdata add/edit action -->
    <adminhtml_contactsave_contactdata_edit>
        <update handle="editor"/>
        <reference name="menu">
            <action method="setActive">
                <menupath>mycompany_contactsave/contactdata</menupath>
            </action>
        </reference>
        <reference name="content">
            <block type="mycompany_contactsave/adminhtml_contactdata_edit" name="contactdata_edit"></block>
        </reference>
        <reference name="left">
            <block type="mycompany_contactsave/adminhtml_contactdata_edit_tabs" name="contactdata_tabs"></block>
        </reference>
    </adminhtml_contactsave_contactdata_edit>

</layout>


If you want to display additional field in mail template then edit app/locale/en_US/template/email/contact_form.html and add your additional variable there.

Fax: {{var data.fax}}

Company Name: {{var data.company_name}}

Download Whole Module From Github: https://github.com/vijayrami/contactform_savedata_with_captcha
Tag : Magento
0 Comments On "Save Contact Forms Data to Database and Add Default Captcha To Contact Form In Magento"

Back To Top