Form in Magento

Hello All,

Many of you who are working in Magento might have come accross the need to make custom form for getting user data.

I am writing here an example to display form (with validation) for submitting basic info and send a mail on the email submitted.

Suppose the from need to be displayed at this url -> http://youmagentohost/formurl/

<?php

$url = Mage::getBaseUrl().'requestfrm';	
//below code for sending mail after form is submitted
//start	
if(isset($_POST) && !empty($_POST['request_flag'])):
	$params = $this->getRequest()->getParams();	 	//Fetch submited params       
	//print_r($params);        			
	// message start
	$message = '';	
	
	if(!empty($params)):
	$message = "
	<html>
	<head>
	  <title>Customer details</title>
	</head>
		<body>
		<table border='0' cellpadding='4' cellspacing='0' width='90%'>
	    <tbody>
	    <tr>
	      <td align='center' colspan='2' height='30' >Customer Details</td>	      
	    </tr>	   
	    <tr>
	      <td align='right' width='40%'><b>Name:</b></td>
	      <td width='55%'>".$params['name']."</td>
	    </tr>
	    <tr>
	      <td align='right' width='40%'><b>Email Address:</b></td>	
	      <td width='55%'>".$params['email']."</td>
	    </tr>
	    <tr>
	      <td align='right' width='40%'><b>Phone Number:</b></td>
	      <td width='55%'>".$params['phone']."</td>
	    </tr>	    
	    <tr>
	      <td align='right' width='40%'><b>Comments:</b></td>
	      <td width='55%'>".$params['comment']."</td>
	    </tr>
	    </tbody>	
		</body>
	</html>";	
	endif;	
	
	$to = Mage::getStoreConfig('contacts/email/recipient_email'); //get email address set from site admin
	
	$dt = date('d-m-Y');	
	// subject	
	$subject = "Customer details submitted on date $dt";	
	// message end
    $mail = new Zend_Mail();
    $mail->setBodyHtml($message);
    $mail->setFrom($params['email'], $params['name']);
    $mail->addTo($to, 'Site Admin');
    $mail->setSubject($subject);
    try {
      if($mail->send())
      {
      	Mage::getSingleton('core/session')->addSuccess('Mail sent successfully. We will contact you shortly');       	
      }	
    }        
    catch(Exception $ex) {
        Mage::getSingleton('core/session')->addError('Unable to send email.');        
    }  
	
endif;
//end
?>
<div align="left">
<div>
<form action="<?php echo $url ?>" id="requestForm" method="post">
	<div>
	<div>
    	<div>
      	<h3 class="txt-blue"><?php echo Mage::helper('contacts')->__('Information') ?></h3>
        </div>        
        <ul class="form-list">      	              
			<li>
        		<label class="required"><?php echo $this->__('Name') ?>&nbsp;<font color="red">*</font></label>
            	<div class="input-box">                    	
                    <input name="name" id="name" title="name" value="" class="small required-entry" type="text" />                    
            	</div>
            </li>                    
			<li>
        		<label class="required"><?php echo $this->__('Email Address') ?>&nbsp;<font color="red">*</font></label>
            	<div class="input-box">                    	
                    <input name="email" id="email" title="email" value="" class="small required-entry validate-email" type="text" />                    
            	</div>
            </li>                    
			<li>
        		<label><?php echo $this->__('Phone Number') ?></label>
            	<div class="input-box">                    	
                    <input name="phone" id="phone" title="phone" value="" type="text" />                    
            	</div>
            </li>    
            <li>
                <label for="comment"><?php echo $this->__('Comment') ?></label>
                <div class="input-box">
                    <textarea name="comment" id="comment" title="" cols="5" rows="3"></textarea>
                </div>
            </li>
        </ul>      
	</div>
	</div>
    <div style="margin:0">
        <p style="padding-right:10px;"><?php echo $this->__("<font color='red'>*</font> Required Fields") ?></p>        
        <div style="padding-right:10px;"><button type="submit" title="<?php echo $this->__('Submit') ?>" ><span><?php echo $this->__('Submit') ?></span></button></div>
    </div>
    <input type="hidden" name="request_flag" value="1"/>
</form>
<script type="text/javascript">
//<![CDATA[
    var contactForm = new VarienForm('requestForm', true);
//]]>
</script>
</div>
</div>

Updates
—————
Steps

1) Create a page frm.phtml in app\design\frontend\default\default\template\contacts, paste all the code as given in the post in this file

2) Create a page from Store Admin-end > CMS > Pages

3) Assign the value ‘requestfrm’ in URL Key

4) Browse to Pages > Content (Tab in the left column)

5) Paste the content ‘{{block type=”core/template” name=”newForm” template=”contacts/frm.phtml”}}’ (excluding the single quote) and save it

The page can be seen at http://storeurl/requestfrm

26 thoughts on “Form in Magento

  1. another point. i get no sucess message until page is reloaded.

    i made this changes and it works now:
    if($mail->send())
    {
    Mage::getSingleton(‘core/session’)->addSuccess(‘Mail sent successfully. We will contact you shortly’);
    /* qweb mod */
    Header(‘Location: ‘.$_SERVER[‘PHP_SELF’]);
    }
    }
    catch(Exception $ex) {
    Mage::getSingleton(‘core/session’)->addError(‘Unable to send email.’);
    /* qweb mod */
    Header(‘Location: ‘.$_SERVER[‘PHP_SELF’]);
    }

    Any better solution???

  2. Great Simple Script!!

    We change:
    $url = Mage::getBaseUrl().’requestfrm’;

    to:
    $url = $this->helper(‘core/url’)->getCurrentUrl();

    And now it works on different CMS Pages without any Problem. You should change it 😉

    THX!!

  3. First of all..Thanks for this great post.
    But can you please tell me how can i save form data into database..and display the same in admin panel grid.
    plz suggest me…

  4. Hi,

    Older threat but great tutorial, I have a need this form with 40+ checkboxes , so that customers can choose.. say for example 5 product samples..

    How do i include these chosen checkboxes into the form..?

    Thanks in advance!

    Best
    A

  5. Hello DWRoot.
    Thanks for sharing this topic …
    i tried to implement it but it seems the code of frm.phtml is not executed at all. In fact I got a blank page.

    Any idea? could you help me out?

    Magento version is 1.7.0.2

      1. I am having the same problem with Francesco. The page exists(not 404), but with empty content on the page, seems like the frm.phtml isn’t executed properly.

    1. You can save the information in DB if its required, and you can make a view page in any of your existing module or can make a new module and can use the above code. You can also call a view page (containing form) from a static block from admin end.

      1. Hi you wrote:You can also call a view page (containing form) from a static block from admin end….
        So you mean create in for example app/design/frontend/template/contacts/ create anotherform.phtml, insert this code into it and then call it? How? I mean you suppose the from need to be displayed at this url -> http://youmagentohost/formurl/ and first line is magento url with requestfrm. I do not undeerstand. Could it be step by step? Thank you

        1. Steps

          1) Create a page frm.phtml in app\design\frontend\default\default\template\contacts, paste all the code as given in the post in this file

          2) Create a page from Store Admin-end > CMS > Pages

          3) Assign the value ‘requestfrm’ in URL Key

          4) Browse to Pages > Content (Tab in the left column)

          5) Paste the content ‘{{block type=”core/template” name=”newForm” template=”contacts/frm.phtml”}}’ (excluding the single quote) and save it

          The page can be seen at http://storeurl/requestfrm

          Hope this is in details for you now 😉

  6. Hi, Nice job done there.
    I tried your code but I am not receiving any email though I get an success message on my screen.
    Can you tell me what might be the issue?
    I am using Magneto 1.7

    1. Are you on local environment, if yes than SMTP should be configured in your local instance. Also check in Adminend > System > Configuration > System , there is a flag for Disable Mail Communication, it should be set to No

  7. Hello DWRoot,

    First of all, thanks for sharing these information. They sure are helpful specially the “Queries in Magento” article.

    Its just that I can’t integrate it to my Magento 1.7.0.0 installation on my own.

    Thanks tho.

    1. @William – You can save the information in DB if its required, and you can make a view page in any of your existing module or can make a new module and can use the above code. You can also call a view page (containing form) from a static block from admin end.

  8. Hi,
    I found this very useful.Can you please guide me how to insert all the fields into database table?

    Thank you,
    Vittal

Leave a Reply to William Espindola Cancel reply

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

Scroll to top