To create a simple contact form for Silverstripe, simply follow the steps below:
- Create ContactPage.php under mysite/code:
<?php class ContactPage extends Page { static $db = array( 'Mailto' => 'Varchar(100)', //Email address to send submissions to 'SubmitText' => 'HTMLText' //Text presented after submitting message ); //CMS fields function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab("Root.Content.OnSubmission", new TextField('Mailto', 'Email submissions to')); $fields->addFieldToTab("Root.Content.OnSubmission", new HTMLEditorField('SubmitText', 'Text on Submission')); return $fields; } } class ContactPage_Controller extends Page_Controller { //Define our form function as allowed static $allowed_actions = array( 'ContactForm' ); //The function which generates our form 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 action $validator = new RequiredFields('Name', 'Email', 'Comments'); return new Form($this, 'ContactForm', $fields, $actions, $validator); } //The function that handles our form submission 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(Director::baseURL(). $this->URLSegment . "/?success=1"); } //The function to test whether to display the Submit Text or not public function Success() { return isset($_REQUEST['success']) && $_REQUEST['success'] == "1"; } }
- Create ContactEmail.ss into themes/yourtheme/templates/Email:
<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>
- Create ContactPage.ss into themes/yourtheme/Layout/:
<div id="content" class="typography"> <h1>$Title</h1> <% if Success %> $SubmitText <% else %> $Content $ContactForm <% end_if %> </div>
- Build database and flush using: yoursite.com/dev/build?flush=1
Looking for quality SilverStripe Web Hosting? Look no further than Arvixe Web Hosting!
Thanks for this Teet. Would this be suitable to insert into a sidebar?
Then you need to make the page for it and control the page in the sidebar.