PHP Magento Tips

Adding Image Upload field in Contact Form and Send as attachment in Magento

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

Adding image upload field can be more difficult than other field for example: text, textarea, select etc.

Below is 100% tested script which working fine for Magento latest version.

Strep 1: Modify the contact form template

Modify the contact form template file: app/design/frontend/rwd/default/template/contacts/form.phtml

a> Add enctype="multipart/form-data" in <form> element as:

<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post" enctype="multipart/form-data">


b> Add file upload field below 'Telephone' field (or anywhere you want) as:

<li>

    <label for="attachment"><?php echo Mage::helper('contacts')->__('Attachment') ?></label>

    <div class="input-box">

        <input name="MAX_FILE_SIZE" type="hidden" value="2000000" />

        <input name="attachment" id="attachment" class="input-text" type="file" />

    </div>

</li>

Step 2: Create simple module to override contacts controller for processing file upload

a>: Create file at app/etc/modules/Mycompany_Customcontact.xml and add below code in it.

<?xml version="1.0"?>



<config>



    <modules>



        <Mycompany_Customcontact>



            <active>true</active>



            <codePool>local</codePool>



        </Mycompany_Customcontact>



    </modules>



</config>

b>: Create main config.xml file and add below code in it.

<?xml version="1.0" encoding="UTF-8"?>



<config>



    <modules>



        <Mycompany_Customcontact>



            <version>0.1.0</version>



        </Mycompany_Customcontact>



    </modules>



    <frontend>



        <routers>



            <contacts>



                <args>



                    <modules>



                        <Mycompany_Customcontact before="Mage_Contacts_IndexController">Mycompany_Customcontact</Mycompany_Customcontact>



                    </modules>



                </args>



            </contacts>



        </routers>



    </frontend>



</config>

c>: Create file at app/code/local/Mycompany/Customcontact/controllers/IndexController.php and add below code in it. This is the file where we override contacts indexcontroller's postaction. just copy app/code/core/Mage/Contacts/controllers/IndexController.php file's postAction and check highlighted code below:

<?php

include_once("Mage/Contacts/controllers/IndexController.php");

class Mycompany_Customcontact_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;

                }
                /**************************************************************/

                $fileName = '';

                if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {

                 try {

                  $fileName       = $_FILES['attachment']['name'];

                  $fileExt        = strtolower(substr(strrchr($fileName, ".") ,1));

                  $fileNamewoe    = rtrim($fileName, $fileExt);

                  $fileName       = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;

                  $uploader       = new Varien_File_Uploader('attachment');

                  $uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg', 'png', 'zip')); //add more file types you want to allow

                  $uploader->setAllowRenameFiles(false);

                  $uploader->setFilesDispersion(false);

                  $path = Mage::getBaseDir('media') . DS . 'contacts';

                  if(!is_dir($path)){

                   mkdir($path, 0777, true);

                  }

                  $uploader->save($path . DS, $fileName );

               

                 } catch (Exception $e) {

                  Mage::getSingleton('customer/session')->addError($e->getMessage());

                  $error = true;

                 }

                }

                /**************************************************************/

                if ($error) {

                    throw new Exception();

                }

                $mailTemplate = Mage::getModel('core/email_template');

                /* @var $mailTemplate Mage_Core_Model_Email_Template */

                /**************************************************************/

                //sending file as attachment

                $attachmentFilePath = Mage::getBaseDir('media'). DS . 'contacts' . DS . $fileName;

                if(file_exists($attachmentFilePath)){

                 $fileContents = file_get_contents($attachmentFilePath);

                 $attachment   = $mailTemplate->getMail()->createAttachment($fileContents);

                 $attachment->filename = $fileName;

                }

                /**************************************************************/

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

        }

    }

}

Try to attach file and submit the contact form, you will get that file as attachment in contact email.


Tag : Magento
0 Comments On "Adding Image Upload field in Contact Form and Send as attachment in Magento"

Back To Top