I use this on all my sites. Not the sexiest thing in the world, but it works.
/mysite/code/ContactPage.php
<?php
class ContactPage extends Page
{
static $db = array (
'SuccessMessage' => 'HTMLText'
);
public function getCMSFields()
{
$f = parent::getCMSFields();
$f->addFieldToTab("Root.Content.Success Message", new HTMLEditorField('SuccessMessage','Success message (to be displayed after a user submits the form'));
return $f;
}
}
class ContactPage_Controller extends Page_Controller
{
public function ContactForm()
{
return new Form(
$this,
'ContactForm',
new FieldSet(
new TextField('Name','Your name'),
new EmailField('Email','Your email address'),
new TextField('Spam','Spam protection: <em>Is fire hot or cold?</em>'),
new TextareaField('Message','Message','10','40')
),
new FieldSet(
new FormAction('doContactSubmit','Submit')
),
new RequiredFields(
'Message','Spam'
)
);
}
public function doContactSubmit($data,$form)
{
$data = $form->getData();
if(trim(strtolower($data['Spam'])) != 'hot') {
Director::redirect($this->Link('spam'));
}
else {
$email = new Email();
$email->to = 'myemail@addressl.com';
$email->subject = 'My Website: Contact Form';
$email->from = !empty($data['Email']) ? $data['Email'] : 'webmaster@mysite.com';
$email->ss_template = "ContactPageEmail";
$email->populateTemplate($data);
$email->send();
Director::redirect($this->Link('success'));
}
}
public function Successful()
{
$p = Director::urlParams('Action');
return isset($p['Action']) && $p['Action'] == 'success';
}
public function SpamError()
{
$p = Director::urlParams('Action');
return isset($p['Action']) && $p['Action'] == 'spam';
}
}
?>
/mysite/templates/Layout/ContactPage.ss
<div id="content">
<% if Successful %>
$SuccessMessage
<% else_if SpamError %>
<p>Sorry, you did not provide a valid answer to the spam protection.</p>
$ContactForm
<% else %>
$Content
$ContactForm
<% end_if %>
</div>
/mysite/templates/email/ContactPageEmail.ss
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
</head>
<body>
<p class="body">
A user has submitted a contact form through your website. His/her info appears below.
</p>
<p class="body">
<strong>Name</strong>: $Name<br />
<strong>Email</strong>: $Email<br />
<strong>Message</strong>:
</p>
<p class="body">
$Message
</p>
</body>
</html>