SSbits - Home page
Site by Carbon Crayon
Submit a Post >

Newbies - The place for learning to commence!

Creating a Simple Contact Form

SSBcontactform

 Source files (2.7 KB)  Demo (admin/pass)

In this tutorial we are going to create a very simple contact form, like those commonly seen on most contact-us pages. This is a great introduction to SilverStripe forms for those new to the Subject and should also provide enough functionality for most people to use straight out of the box.

Preparation

We will be using 3 files in this tutorial, our Contact form page type, ContactPage.php and it's layout template ContactPage.ss as well as the email template ContactEmail.ss. Let's create these files and their initial code:

mysite/code/ContactPage.php

<?php
class ContactPage extends Page{
}
class ContactPage_Controller extends Page_Controller{
}

themes/yourtheme/templates/Layout/ContactPage.ss

<div class="typography">
	
	<h2>$Title</h2>
	
</div>

themes/yourtheme/templates/Email/ContactEmail.ss

<html>
	<body>
	
	</body>
</html>

Creating the Page

The first thing we need to do is setup the ContactPage model with database fields ($db) and CMS fields. For this tutorial we will keep it simple and add 2 fields, a MailTo field for the addresses to send the submitted form to and also a field for the text to show the user after submitting the form, which we'll call SubmitText. So add the following to your ContactPage class:

mysite/code/ContactPage.php

class ContactPage extends Page
{
	static $db = array(
		'Mailto' => 'Varchar(100)',
		'SubmitText' => 'Text'
	);
	
	function getCMSFields() {
		$fields = parent::getCMSFields();
	
		$fields->addFieldToTab("Root.Content.OnSubmission", new TextField('Mailto', 'Email submissions to'));	
		$fields->addFieldToTab("Root.Content.OnSubmission", new TextareaField('SubmitText', 'Text on Submission'));		
	
		return $fields;	
	}
}
.
.
.

Once done, flush your database by visiting yoursite.com/dev/build

Create the Form

Now let's actually create the fields for our contact form. Again we will keep it simple and add a Name, Email and Comments field, but you can add as many fields as you like without making the logic more complicated. To get SilverStripe to generate the form we need a function on our ContactPage_Controller class which will return the fields to the page template. We will call this function ContactForm(). A blindingly original name I know.

mysite/code/ContactPage.php

.
.
class ContactPage_Controller extends Page_Controller
{
	static $allowed_actions = array(
		'ContactForm'
	);

	function ContactForm() {
		// Create fields		  
		$fields = new FieldSet(
			new TextField('Name', 'Name*'),
			new EmailField('Email', 'Email*'),
			new TextareaField('Comments','Comments*')
		);
		 	
		// Create action
		$actions = new FieldSet(
			new FormAction('SendContactForm', 'Send')
		);
		
		// Create Validators
		$validator = new RequiredFields('Name', 'Email', 'Comments');
		
		return new Form($this, 'ContactForm', $fields, $actions, $validator);
	}
}

The first thing we do is add our Form function to the $allowed_actions array. As of v2.4, it is now required to define any actions which will be called on your page, in this case the form function is called when the form is submitted. If we don't add this we will get a 404 error.

In the ContactForm() function define the variable $fields which contains a FieldSet with our 3 fields in them.

Next we define the $action variable which creates a FormAction (i.e. the submit button) and set the first argument to SendContactForm. This is the function which will be submitting the form for us, which we will be defining in the next step of the tutorial. The second argument that the FormAction takes is the label for the submit button, in this case we are labeling it with Send but you can label yours with whatever you like.

We then set the required fields for the form, in this case all of them and store them in the $validator variable. Finally we put it all together by returning a new Form object using our variables as arguments. Now when we call $ContactForm from the template, SilverStripe will generate the form and place it in there.

Submitting the Form

Our Contact Form now appears in the template, but once submitted SilverStripe doesn't know what to do with it as we haven't defined the SendContactForm() function that we told the form to look for in the last step. Let's define that function now inside our ContactPage_Controller class: 

mysite/code/ContactPage.php

class ContactPage_Controller extends Page_Controller
{
.
.
.
	function SendContactForm($data, $form) {
  
	 	//Set data
		$From = $data['Email'];
		$To = $this->Mailto;
		$Subject = "Website Contact message";  	  
		$email = new Email($From, $To, $Subject);
		//set template
		$email->setTemplate('ContactEmail');
		//populate template
		$email->populateTemplate($data);
		//send mail
		$email->send();
	  	//return to submitted message
		Director::redirect($this->Link("?success=1"));
	}
}

Let's go through this quickly. We pass in the $data variable which provides the function with the submitted form data so that we can process it. We then assign the relevant bits of data to variables ($From, $To and $Subject) before creating a new Email() object with these variables as arguments. Next we set the template for the email which is just the name of the Template without the .ss on the end. Then we simple pass our $data array into the populateTemplate() function so that we can use the data in our template by simply calling $Name , $Comments etc. You could also pass a custom array into this function if you needed to add other data beyond that submitted in the form.

Finally we send the email and return the user to the current page + ?Success=1 which allows us to test whether the form has been submitted and if it has then display the SubmitText message instead of the form. To do this we need a function which will return true when Success is equal to 1. We can put in in the ContactPage_Controller under our SendContactForm() function It will look like this:

mysite/code/ContactPage.php

class ContactPage_Controller extends Page_Controller
{
.
.
.
	public function Success()
	{
		return isset($_REQUEST['success']) && $_REQUEST['success'] == "1";
	}
}

This function checks to see if success is set and whether it is set to 1, returning true if so. We can now use <% if Success %> in our template to add/remove content depending on whether the form has been submitted or not. This completes our php code so lets move onto the frond end templates.

The Page Template

Our actual page template is going to be pretty simple. Using our Success() function we can use a conditional to decide whether to include the form of the SubmitText like this:

themes/yourtheme/templates/Layout/ContactPage.ss

<div id="content" class="typography">

	<h1>$Title</h1>
	
	<% if Success %>
		$SubmitText
	<% else %>
		$Content
		$ContactForm
	<% end_if %>
	
</div>

The Email Template

Before we send the email in our SendContactForm() function we populate the template ContactEmail. Although the official SilverStripe documentation states that this template should go into mysite/templates/email/ I have found that it in fact only works when it's in your themes/yourtheme/templates/ folder. We need to create this template so that our email arrives with pretty HTML formatting. In the preparation we made the empty file with doc type and a <head> and <body> tags. We now need to add some CSS styling and the<body> content. This is very much down to how you want your email to look so just take this as an example, the only things which need to be the same are the names of the variables, which should match the names of the Form Fields defined in Part II, in this case $Name and $Comments.

themes/yourtheme/templates/Email/ContactEmail.ss

<html>    
    <body>
 
        <p style="font-size:1.4em;color:#666;" >The following message was submitted to your site by <a href="mailto:$Email">$Name:</a></p>
         
        <p style="font-size:1.4em;color:#222;" class="comments">$Comments</P> 
     
    </body>
</html>

And that's it! You should now have a fully functioning contact form for your visitors to send you wonderful insightful and thought provoking messages to their hearts content!

Special Thanks

Special thanks go to Ko for their contributions to this post.

Aram Balakjian avatar

Aram Balakjian

Aram is a web developer running London based agency Aab Web. He has a strong passion for developing attractive, usable sites around the SilverStripe CMS.

  • Sebastian
    24/10/2010 6:52pm (4 years ago)

    hi, I did everythink like you did and I couldn't bulid DB with /dev/build/?flush=1, I noticed that if I comment this line
    Director::redirect($this->Link('?success=1');
    everythink goes well, where is the problem, I'm new to the SS

  • Sebastian
    24/10/2010 6:55pm (4 years ago)

    ok, I found, you forgot the closing bracket in the line - that's why we shouldn't do "copy-paste" :)

  • Aram Balakjian
    24/10/2010 11:42pm (4 years ago)

    Thanks Sebastian, I have updated the code in the tutorial :)

  • Ko
    23/11/2010 10:08pm (4 years ago)

    Hi Aram!

    Thanks for your excellent tutorials!
    I just finished "Creating a Simple Contact Form"; it was my first step into the wonderful world of object oriented PHP...
    But I think there's a small error in the code for the class ContactPage_Controller:
    When I type in your code I get this error:
    " Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in /var/www/silverstripe/majako/code/ContactForm.php on line 20";
    If I change the line "$allowed_actions = array('ContactForm' ); "
    to: "static $allowed_actions = array( 'ContactForm');"
    the error is gone.

  • Aram Balakjian
    23/11/2010 11:09pm (4 years ago)

    Hi Ko, thanks for that, I have amended the code :)

  • Ko
    24/11/2010 9:12pm (4 years ago)

    Hi Aram,

    Another thing: the page template should be called: "themes/yourtheme/templates/Layout/ContactPage.ss" instead of: " themes/yourtheme/templates/Layout/ContactForm.ss "

  • Aram Balakjian
    20/12/2010 11:31am (4 years ago)

    Thanks Ko, I have amended all the file names, not sure how I got all of them wrong! lol

  • Tank863
    01/02/2011 3:00pm (4 years ago)

    Aram, your site is excellent. I am a complete beginner at SS. I just started using it and am waiting for the book to arrive. Having said that. I attempted to implement the Simple Contact Form on my site. Do I need to modify the code for my site or just plug in as is? I have the contact form up and running, but I am not receiving emails from it when I test.

  • Aram Balakjian
    01/02/2011 3:14pm (4 years ago)

    Hi Tank,

    Great to hear you are giving SS a try, it seems tough at first but will give you so much power once you get the hang of it ;)

    The code above should work strait away, have you tried the code which is supplied with the tutorial? Also are you trying it on a local enviroment or a live webserver, as local envs (e.g. WAMP, MAMP) may not support sending mails.

    Also make sure that your template ContactEmails.ss is in place, and try it in mysite/templates/ and see if it works there, I know I have had to do that in previous versions of SS.

    Let me know if you still have problems :)

    Aram

  • Tank863
    01/02/2011 11:05pm (4 years ago)

    Aram,

    Working perfectly... thank you!

    Chris

  • martinphone
    05/02/2011 6:50pm (4 years ago)

    Thanks for this - the contact form is working in itself just great, but for some reason the $ContactForm part stops my jquery effects (actually just a simple slideToggle) from working... can anyone think why?!

    I remove just "$ContactForm" and jquery's back and working. Obviously I don't have a contact form though. :)

  • Aram Balakjian
    06/02/2011 4:09pm (4 years ago)

    Hi Martin,

    I imagine it is a conflict of some sort, try adding this to your init() function (or _config):

    Validator::set_javascript_validation_handler('none');

    This will disable the prototype JS and you can then implement jQuery validation following this tutorial:

    http://www.ssbits.com/tutorials/2009/using-jquery-for-form-validation/

    Aram

  • Danny Cheeseman
    11/02/2011 2:37pm (4 years ago)

    Hi Aram,

    A quick question, I want to make an ajax version on this contact form.

    How can I output my own template instead of the generic one?

    I have tried putting a ContactForm.ss in the templates directory with no avail..

    Cheers

  • Danny Cheeseman
    11/02/2011 2:40pm (4 years ago)

    I realise I was not clear....

    I need to enclose the form elements in my own custom html..
    At the minute it is enclosed in the generic .middleColumn etc...

    I want to enclose the name and email inputs in a stepone div, then subject and comments in a steptwo div...

    Many Thanks,

  • Aram Balakjian
    11/02/2011 3:00pm (4 years ago)

    Hi Danny,

    You need to use the LiteralField like so:
    $fields->Push(LiteralField('', '<div class="stepone">));
    //Your fields
    $fields->Push(LiteralField('','</div>'));

    It's a bit hacky, but will get the job done :)

    Aram

  • Danny
    12/02/2011 8:28am (4 years ago)

    Hi Aram, Could you check that code please as it is throwing out a blank page??

  • Danny
    12/02/2011 8:29am (4 years ago)

    // Create fields
    $fields = new FieldSet(
    $fields->Push(LiteralField('', '<div class="stepone">));

    new TextField('Name', 'Name*'),
    new EmailField('Email', 'Email*'),
    new TextareaField('Comments','Comments*')

    $fields->Push(LiteralField('','</div>'));


    );

  • Danny
    12/02/2011 8:36am (4 years ago)

    This works, for anyone else who wants it..

    $fields = new FieldSet(
    new LiteralField('', '<div class="stepone">'),
    new TextField('Name', 'Name*'),
    new EmailField('Email', 'Email*'),
    new TextareaField('Comments','Comments*'),
    new LiteralField('', '</div>')
    );

  • Danny
    22/02/2011 9:27am (4 years ago)

    Hi Aram, How are you?

    I have got this contact form working on every page with a jquery multistep function.

    I now need to auto populate the Mailto and SubmitText...

    I have played for a while but cannot get it to work.

    I assume that I need to edit the

    public static $db = array(
    'Mailto' => 'Varchar(100)', //Email address to send submissions to
    'SubmitText' => 'HTMLText' //Text presented after submitting message
    );

    I have done it like:

    public static $db = array(
    'Mailto' => 'me@me.com', //Email address to send submissions to
    'SubmitText' => '<p>Thanks for your submission</p>' //Text presented after submitting message
    );

    I know the submit text part is wrong, how would I go about this..

    Thanks,

    Danny.

  • Aram Balakjian
    22/02/2011 9:33am (4 years ago)

    Hi Danny,

    you can set the defaults using the $defaults static like so:

    static $defaults = array('MailTo' => 'me@me.com');

    You cant do what you have done in $db because you need a valid fieldtype class on hte right of each item (e.g. Varchar, Int etc).

    Aram

  • Joaquin Valdez
    22/03/2011 12:38am (4 years ago)

    Is it possible to have the field labels placed to the left of the text field?

  • Joaquin Valdez
    22/03/2011 12:38am (4 years ago)

    Thank you! BTW

  • Prawnstar
    26/03/2011 6:26am (4 years ago)

    Hi, Aram,

    First, thank you very much for your (and everyone's) efforts here at SSbits. Your work has helped me immensely, thank you.

    I followed this tutorial and everything worked perfectly, until I create a second email template.

    When I create a single ContactPage.php controller and a single ContactEmail.ss email template (located in themes/mytheme/templates/Email/) everything works as you describe. However, when I created a second form, let's say OtherContactPage.php and a single OtherContactEmail.ss file located in the same themes/mytheme/templates/Email/ directory, the second form email gets sent blank. Meaning I get the email, just nothing in it(yes, i've looked at the source of the email and it is blank). To clarify, the original form/email comes through to my email inbox just fine, it's the second form/email that comes through blank.

    I've re-read your instructions a half-a-dozen times and finally noted that you say:
    "Although the official SilverStripe documentation states that this template should go into mysite/templates/email/ I have found that it in fact only works when it's in your themes/yourtheme/templates/ folder."

    So of course I tried it the SS way. That resulted in me receiving two blank emails, as you might have suspected. But...then, in the course of trial-and-error I accidentally left the templates in both locations, themes/mytheme/templates/Email and mysite/email/. Now both emails are coming through just fine!?!

    Any clue as to what the issue might be? Obviously the SilverStripe documentation you refer to is incorrect (For now, located here: http://doc.silverstripe.org/sapphire/en/topics/email).

    One thing to note is that in my files, I'm also writing the form results to the db in addition to emailing them. The values store into the db just fine in any scenario.

    Chris.b

  • Aram Balakjian
    29/03/2011 10:46am (4 years ago)

    Hi Chris, I have had strange results with template locations too, sometimes they work when in one sometimes in the other....I really haven't managed to figure out any way to make it always work....if it doesnt work in one I usually just try it in the other....

    It's also worth remembering to ?flush=1 after adding a template as sometimes it won't pick it up automatically.

    Aram

  • Mike
    15/04/2011 4:17am (4 years ago)

    Hi Aram -- great tutorial! Easy for follow and I now have the form in place on my page. I'm just a bit stumped as to how to worked out where it's going to be sent to (yes, I'm an SS Newb -- and more of a designer than a developer)! Can you five me a few pointers?

    I've read your reply to Danny (22/02/2011) but I'm not too sure where this code should be placed. Do I need to specify this in ContactPage.php?

    Thanks again
    MIKE

  • Aram Balakjian
    15/04/2011 9:40am (4 years ago)

    Hi Mike,

    THe example in this tutorial uses a custom field added to the ContactPage called 'MailTo'. This allows the user to set the address the submissions are sent to from within the CMS. This line tells the form where to send the email to:

    $To = $this->Mailto;

    You could just as easily use:

    $To = "me@mysite.com";

    If you wanted to hard code the address.

    Hope that helps :)

    Aram

  • salva
    21/04/2011 2:38pm (4 years ago)

    Hey Aram,

    i want to send the contact Mail to more then one Email adress.
    how can i modify the code, maybe comma separated email adresses in the "Mailto" field or just add bc and cc fields?

    kind regards
    salva

  • Aram Balakjian
    21/04/2011 2:48pm (4 years ago)

    Hi Salva,

    This is already possible, simple put a comma seperated list of email addresses into the 'MailTo' field and it will go to each of them :)

    Aram

  • Marc
    24/05/2011 1:24pm (4 years ago)

    Hi Aram,

    Thanks for the post. Have found this really useful for getting to know SS.

    I am now trying to push this a bit further and allow users to select from a dropdown or OptionsetField list which recipient to send their email to. I have in mind that I will add more Mailto boxes and Contact Names in admin so client can define these and then on the site the user see only the name ContactName in the dropdown.

    Problem is I am getting very stuck. Can you point me in the right direction. I have been looking on the SS Forums but I think what I have found has confused me further. :)

    Thanks in advance

    Marc

  • Aram Balakjian
    24/05/2011 1:30pm (4 years ago)

    Hi Marc,

    The best way to do this would be to create a "ContactAddress" DataObject and manage these with a DOM on the contact page. Then you can generate the dropdown from these and use the Name field for the title using $DOS->map('ID','Name');

    Then in your send function you will receive the ID of the ContactAddress DataObject so you can fetch it using DataObject::get_by_id and then pull out the address and asign it to the $to variable.

    Hope that makes sense.

    Aram

  • Marc
    24/05/2011 3:24pm (4 years ago)

    Thanks Aram.

    I think I get it. Will have a look and see if I can get my head around it all!!!

    Cheers

    Marc

  • Marc
    24/05/2011 5:02pm (4 years ago)

    Thanks again for your earlier post Aram.

    I have been able to create the editiable list of contact details as a data object and return these using the below:

    function ContactForm() {
    // Create fields
    $fields = new FieldSet(
    new DropdownField ('ContactName', 'ContactName', (DataObject::get('ContactAddress')->toDropDownMap("ID", "ContactName"))),
    new TextField('Name', 'Name*'),
    new EmailField('Email', 'Email*'),
    new TextareaField('Comments','Comments*')
    );

    I couldn't figure our the $DOS->map and what I found on ss forums didn't seem to work for me.

    I am now stuck on how to link up the current ID/Contact Name that has been selected so that the email is sent to the right address.

    Can this be done with what I have or do I need to persevere with $DOS->map?

    thanks again

    Marc

  • Aram Balakjian
    24/05/2011 5:06pm (4 years ago)

    Hi Mark, don't worry ->map() is just another form of toDropdownMap() which is now depreciated. you can literally swap 'toDropdownMap' with 'map'.

    The next stage is getting the selected DO back into your send function so that you can grab the right address. It might look something like this:

    if(is_numeric($data['ContactAddress'])
    {
    $Contact = DataObject::get_by_id('ContactAddress', $data['ContactAddress']);
    }

    $to = $Contact->EmailAddress;
    ....

    Or something along those lines :)

    Aram

  • Marc
    24/05/2011 8:28pm (4 years ago)

    Thanks again Aram.

    That does make sense but I am unable to get it working. Is there a way to debug this and/or see logs of what emails the system is attempting, or not, to send?

    Cheers

    Marc

  • Ben Tucker
    31/05/2011 1:54am (4 years ago)

    Hi Aram,

    Great tutorial. I have the contact form working fine as is, but I want to use extra variables in the email. More specifically I would like to use the Site Title, but the usual method of $SiteConfig.Title doesn't seem to work in the ContactEmail.ss.

    How do I go about passing variables to the ContactEmail.ss template?

  • Aram Balakjian
    31/05/2011 12:23pm (4 years ago)

    @marc - hmm I am sure there is but not sure what it is off the top of my head. However you can try calling $this->Customise($data)->renderWith(array("ContactEmail")); in the SendContactForm function which will render the email on the front end.

    @Ben - all you need to do is add the data to the $data array, so something like:
    $data['SiteTitle'] = $this->SiteConfig()->Title;

    Then you should be able to use $SiteTitle in the email template :)

    Aram

  • Carrie
    07/06/2011 4:52pm (3 years ago)

    Thanks for the code, got it working right away! How can I add a spam protection question like in the page under, so the question and the answer are editable in cms?
    http://silverstripe.org/general-questions/show/4728#post251692

  • Aram Balakjian
    07/06/2011 5:01pm (3 years ago)

    Hi Carrie,

    The code that UC posted in that thread should work fine, you just need to replace the question in the form with $this->Question and then when checking the answer change 'hot' for $this->answer.

    It's a good idea for a short tutorial actually, I'll try and find some time soon

  • Carrie
    08/06/2011 12:14pm (3 years ago)

    I already made a contact page with the help of your tutorial, so I thought I was wise trying to add those things in UCs post, but of course that's not so simple for the beginner... :>The error message points to the line where I added the spam field to the contact form. How should it be? I thought like this:
    new TextField('Spam','$this->Question')

    I also need to dig the right terms, because like usually there are different words used in different tutorials, like Successful/Success and SuccessMessage/ SubmitText

    The question and answer fields do appear in the cms, there's no problem with those.

  • Aram Balakjian
    08/06/2011 12:16pm (3 years ago)

    Hi Carrie,

    What is the error that your getting? Also you need to remove the '' from around $this->Question, it's not a string so you don't quote it.

    Aram

  • Carrie
    08/06/2011 12:26pm (3 years ago)

    Well, with the '' marks removed I don't get the error message anymore, but it seems I do have a problem with the cms. It doesn't save the question and the answer, when Save & published the page, those fields are cleared. And in the contact form it says just Spam above the spam question field.

  • Aram Balakjian
    08/06/2011 12:28pm (3 years ago)

    Hi Carrie, could you paste your code into pastebin and send me the link via email?

    Aram

  • Carrie
    08/06/2011 12:29pm (3 years ago)

    Also I'm still seem to be missing some part with the code, because when trying to send a message, it doesn't show the text "Sorry, you did not provide a valid answer to the spam protection." only the page doesn't exist message.

  • Carrie
    08/06/2011 12:30pm (3 years ago)

    What's the email?

  • Mike
    18/07/2011 9:27am (3 years ago)

    Hi again Aram. Just configuring this form for use on another site and I need to do a dropdown list. I was hoping you could give me a few pointers about syntax (this doesn't seem to be covered in your tutorial... TIA, MIKE

  • Aram Balakjian
    18/07/2011 9:29am (3 years ago)

    Hi Mike,

    The Syntax for a dropdown is the same as when using it in the CMS, see this post: http://www.ssbits.com/tutorials/2010/dynamically-generating-a-dropdown-list/

    Aram

  • jcwacky
    29/07/2011 12:22pm (3 years ago)

    How can it be made so that line breaks in the Enquiry field are not lost in the e-mail?

    Presumably it's not currently converting line breaks to <p> tags.

  • newb999
    07/09/2011 6:44am (3 years ago)

    Hi Aram,

    Thank you for the tutorial. I am having a wee bit of trouble with this. I have created the form, but when i send it, it does not reprint the message. I understand that the email will not work because i'm running SS on a local environment (MAMP (not pro)). Is it normal behavior for the $SubmitText on success (The correct URL returns, but no data) to not print because of me running it on a local env? Any help would be much appreciated.
    Regards

  • Aram Balakjian
    27/09/2011 9:41am (3 years ago)

    Hi Newb,

    It should work on a locan env too, just by visiting the URL with ?success=1 on the end, even without submitting the form.

    Aram

  • timwjohn
    27/09/2011 8:02pm (3 years ago)

    This is a really great article. I learned a lot. Thanks!

  • lucidOne
    18/10/2011 10:06pm (3 years ago)

    @newb999

    Try changing: Director::redirect($this->Link("?success=1"));

    To: Director::redirect(Director::baseURL(). $this->URLSegment . "/?success=1");

  • phoenixjutom
    05/12/2011 8:37am (3 years ago)

    Hi Aram,
    I am completed with Silver Stripe. And I had follow completed with this tutorial. But...I don't know how to use it? how to add contact form in silver stripe?? Please help me

  • Mike
    12/01/2012 11:34pm (3 years ago)

    Hi Aram -- I've had this form successfully installed and working on a few websites. But now it's stopped operating under Win/IE7 -- I can fill the form out and it appears to check validation but will not submit. On Mac/Firefox form will submit but no form data is sent to recipient, and no confirmation email is received by user. Any idea what's happening? Thanks, MIKE

  • Mike
    13/01/2012 8:40am (3 years ago)

    Now I'm embarassed -- always pays to populate the email template file correctly -- MY BAD!! Must be because it's Friday 13th!

    Still not sure why I can't submit form in Win/IE7 but...

  • sfimedia
    26/01/2012 12:30pm (3 years ago)

    Hi Aram

    Can you help I have set up the custom form which is working great.... I want to add the current date to the success page and contactemail template. Okay so I have added $Now.Nice to the ContactPage.ss which works fine and gives me the date. However when I add $Now.Nice to the ContactEmail.ss page it doesn't display. Any ideas do I need to Call a Control function???

  • Aram Balakjian
    26/01/2012 12:33pm (3 years ago)

    Hi sfimedia,

    You just needyo pass it into the template with the $data var.

    Try this on the line before populateTemplate($data):

    $data['Date'] = date("Y M d");

    Then just use $Date in the email template :)

    Aram

  • sfimedia
    26/01/2012 5:00pm (3 years ago)

    Great thanks! Works

    One last thing if I want to pass the ContactForm information instead of SubmitText to the ContactPage.ss how would this work. ie all the email info collected so the client can view the details after processing.

  • Adil Aliyev
    28/01/2012 10:03pm (3 years ago)

    Thanks.

    UserForms (http://www.silverstripe.org/user-forms-module/) also is useful in most cases.

  • sfimedia
    30/01/2012 9:32am (3 years ago)

    Hi Aram

    The reason I need the information to be passed is that I am creating a posting label with details that need to be printed by user. So when the email has been sent I can setup the submitted in a printable page format. Hope this is clear. I have tried a number of things to get the information to show but I think I am a little lost.

    Steve

  • Aram Balakjian
    30/01/2012 9:35am (3 years ago)

    sfimedia - You would either need to store it as a DataObject accociated to the contact page, or pass the $data back into the template when you render the page after submission:

    $templateData = array(
    'FormData' => $data
    );
    return $this->customise($templateData);

    Then you can use $FormData.Comments in the template to display the comment.

    Aram

  • DoubleONeill
    13/03/2012 9:23pm (3 years ago)

    Hi Aram,

    I've set up a contact form similarly to the way you have in this example but it's very lengthy and needs breaking up. I want to add subheadings to sections of the form and wanted to know what method you'd recommend. All I can think of is embedding some html tags in the contactpage when setting up the new form fields. For example

    new TextField('Field', '<br /><p><b>This is the subheader</b></p>'question'),

    It doesn't seem the neatest method and through my limited experience i'm sure this can bring problems later on.

    Thanks,

    DoubleONeill

  • Aram Balakjian
    14/03/2012 11:40am (3 years ago)

    Hi DoubleONeill,

    Try a HeaderField() or a LiteralField(), they should do the trick :)

    Aram

  • Liam
    26/06/2012 8:36pm (2 years ago)

    Will you be updating this to work with SS3?

  • Thomas H
    13/09/2012 1:45pm (2 years ago)

    Hi Aram,
    Thanks for a nice tutorial. I'm trying to use the SendContactForm function and everything works fine except that special characters looks VERY special. Maybe they do get double encoded or something...
    I have tried different kind of encoding on the data array, but since it is an array it doesn't work and set the charset to UTF-8 in the header:

    $Header = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/html; charset=UTF-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n";
    $email = new Email($From, $To, $Subject, $Header);

    Is this a known problem when sending data posted in a form like this? Or is it just me? :)

    This is how my characters look like: Ü å å
    If anybody here have experienced similar behaviour, and found a solution to it. It would be great if you could share some of your experience.

  • Aram Balakjian
    13/09/2012 1:56pm (2 years ago)

    Hi Thomas, that sounds very strange, not come accross that problem before.

    You could try escaping the data before passing it to the template like so:

    $data['Comments'] = htmlentities($data['Comments'];

    Let me know if that helps,

    Aram

  • jimpickens
    27/11/2012 12:10pm (2 years ago)

    Hi Aram, I have an urgent question that I hope you can answer. I am using a multi step form module on SS 2.4 and i am hoping for the inputs from the multi step form to be directed to specific tables in a database which is hosted in Cpanel (PhpMyAdmin). Is this step remotely possible? If it is, could you give a rough idea on how to achieve it?

  • Roland
    14/12/2012 7:37pm (2 years ago)

    @jcwacky: To have line breaks appear correctly in the e-mail, add the following before populating the template.

    // transform line breaks into '<br>' tags
    $line_breaks = array("\r\n", "\n", "\r");
    $data['Comments']=str_replace($line_breaks, '<br />', $data['Comments']);

  • Stefdv
    13/02/2013 8:43pm (2 years ago)

    Hi Aram,
    never had to use a special kind of contact form...now i do. Not realy a contact form, it's an upload form. I need users to upload there stories and photo's to the contentmanager. In fact that's my question..How can i create a submission admin part in the CMS. ( like the one used in the userdefinedform,i just don't need all the 'stuff' that it brings ).
    I do hope you're willing to take this great tut to a next level ;)

  • Shweta
    19/01/2014 2:58pm (10 months ago)

    Hi Aram,
    I am new to SS. I created one new page type. them got database for it. after that I made .ss file for that page type. but my page is using default content controller template.
    I am not getting what's wrong? I did flush command after every change.
    My .php file code is:
    <?php
    /**
    * Defines the HomePage page type
    */

    class HomePage extends Page {
    static $db = array(
    );
    static $has_one = array(
    );
    }

    class HomePage_Controller extends Page_Controller {

    }
    ?>
    And then I created .ss file in Layout folder
    .ss code:
    <div id="Banner">
    <img src="themes/tutorial/images/welcome.png" alt="Homepage image" />
    </div>
    <div id="Content" class="typography">
    $Content
    </div>
    and my Page.ss code is:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
    <head>
    <% base_tag %>
    $MetaTags
    <% require themedCSS(layout) %>
    <% require themedCSS(typography) %>
    <% require themedCSS(form) %>
    </head>
    <body>
    <div id="Main">
    <ul id="Menu1">
    <% control Menu(1) %>
    <li class="$LinkingMode"><a href="$Link" title="Go to the &quot;{$Title}&quot; page">$MenuTitle</a></li>
    <% end_control %>
    </ul>
    <div id="Header">
    <h1>$Title</h1>
    </div>
    <div id="ContentContainer">
    $Layout
    </div>
    <div id="Footer">
    <span>Visit <a href="http://www.silverstripe.com" title="Visit www.silverstripe.com">www.silverstripe.com</a> to download the CMS</span>
    </div>
    </div>
    $SilverStripeNavigator
    </body>
    </html>

    Please tell me whats wrong?

  • TwigHost
    18/04/2014 2:48am (7 months ago)

    Updated for v3.1.2
    > FieldSet changed to FieldList
    >Redirect changed

    ContactPage.php

    <?php
    class ContactPage extends Page
    {
    static $db = array(
    'Mailto' => 'Varchar(100)',
    'SubmitText' => 'Text'
    );

    function getCMSFields() {
    $fields = parent::getCMSFields();

    $fields->addFieldToTab("Root.Content.OnSubmission", new TextField('Mailto', 'Email submissions to'));
    $fields->addFieldToTab("Root.Content.OnSubmission", new TextareaField('SubmitText', 'Text on Submission'));

    return $fields;
    }
    }
    class ContactPage_Controller extends Page_Controller
    {
    private static $allowed_actions = array(
    'ContactForm'
    );

    public function ContactForm() {
    // Create fields
    $fields = new FieldList(
    new TextField('Name', 'Name*'),
    new EmailField('Email', 'Email*'),
    new TextareaField('Comments','Comments*')
    );

    // Create action
    $actions = new FieldList(
    new FormAction('SendContactForm', 'Send')
    );

    // Create Validators
    $validator = new RequiredFields('Name', 'Email', 'Comments');

    return new Form($this, 'ContactForm', $fields, $actions, $validator);
    }
    function SendContactForm($data, $form) {
    //Set data
    $From = $data['Email'];
    $To = $this->Mailto;
    $Subject = "Website Contact message";
    $email = new Email($From, $To, $Subject);
    //set template
    $email->setTemplate('ContactEmail');
    //populate template
    $email->populateTemplate($data);
    //send mail
    $email->send();
    //return to submitted message
    $this->redirect(Director::$this->Link("?success=1"));
    }
    public function Success()
    {
    return isset($_REQUEST['success']) && $_REQUEST['success'] == "1";
    }
    }

Post a comment ...

You cannot post comments until you have logged in. Login Here.

Advertisement

Site of the Month

Find SSbits on

Top Contributers

Rank Avatar Name
1 article image Aram Balakjian
2 article image Daniel Hensby
3 article image Marcus Dalgren
4 article image Hamish Campbell
5 article image Ty Barho
6 article image Martijn van Nieuwenhoven
7 article image Darren-Lee
8 article image Roman Schmid
9 article image Matt Clegg
10 article image dalesaurus

View full leaderboard


Advertisement