# How to make a simple contact form To make a contact form, begin by making a page type for the form to live on – we don't want to see the contact form on every page. Here we have the skeleton code for a ContactPage page type: :::php setTo('siteowner@mysite.com'); $email->setFrom($data['Email']); $email->setSubject("Contact Message from {$data["Name"]}"); $messageBody = "

Name: {$data['Name']}

Website: {$data['Website']}

Message: {$data['Message']}

"; $email->setBody($messageBody); $email->send(); return array( 'Content' => '

Thank you for your feedback.

', 'Form' => '' ); } Any function that receives a form submission takes two arguments: the data passed to the form as an indexed array, and the form itself. In order to extract the data, you can either use functions on the form object to get the fields and query their values, or just use the raw data in the array. In the example above, we used the array, as it's the easiest way to get data without requiring the form fields to perform any special transformations. This data is used to create an email, which you then send to the address you choose. The final thing we do is return a 'thank you for your feedback' message to the user. To do this we override some of the methods called in the template by returning an array. We return the HTML content we want rendered instead of the usual CMS-entered content, and we return false for Form, as we don't want the form to render. ##How to add form validation All forms have some basic validation built in – email fields will only let the user enter email addresses, number fields will only accept numbers, and so on. Sometimes you need more complicated validation, so you can define your own validation by extending the Validator class. The Sapphire framework comes with a predefined validator called 'RequiredFields', which performs the common task of making sure particular fields are filled out. Below is the code to add validation to a contact form: function Form() { $fields = new FieldSet( new TextField('Name'), new EmailField('Email'), new TextareaField('Message') ); $actions = new FieldSet( new FormAction('submit', 'Submit') ); $validator = new RequiredFields('Name', 'Message'); return new Form($this, 'Form', $fields, $actions, $validator); } We've created a RequiredFields object, passing the name of the fields we want to be required. The validator we have created is then passed as the fifth argument of the form constructor. If we now try to submit the form without filling out the required fields, JavaScript validation will kick in, and the user will be presented with a message about the missing fields. If the user has JavaScript disabled, PHP validation will kick in when the form is submitted, and the user will be redirected back to the Form with messages about their missing fields.