# Helping you adapt your iPhorm Ajax contact form

### Thanks for purchasing the iPhorm Ajax contact form!

Need more help? Email us at support@freerangewebdesign.com. Visit www.freerangewebdesign.com and www.sabre-webdesign.com to see our great web services and for latest updates on our Theme Forest templates.

NOTE: Click section headings to show help content.

# Installation

## How to install

To install the contact form into your web page, there are 6 things you must do:

- 1. Copy the HTML code for the contact form into your web page
- 2. Copy the CSS stylesheet link(s) into your web page
- 3. Copy the JavaScript links into your web page
- 4. Configure the contact form to send enquiries to your email address
- 5. Choose a character encoding
- 6. Upload the `contact-form` folder to your web server via FTP

Each step is explained in more detail below.

### 1. Copy the HTML code for the contact form into your web page

Open the `index.php` file and locate the HTML code for the contact form on lines 17 - 94 (it is commented in the file). Select all of this code then copy and paste it into the body of your web page.

### 2. Copy the link to the CSS stylesheet into your web page

There are two stylesheets used by the contact form, which are in the folder contact-form/css:

- 1. A CSS reset / general stylesheet (pagestyles.css)
- 2. A layout specific stylesheet, one of:
  - inline.css
  - block.css
  - standard.css
  - twocol.css

If you have already styled your web page, you probably do not need pagestyles.css so you do not need to copy the link to it. However if you want your web page to look like the live preview of the contact form, feel free to copy the link to this stylesheet from line 7 of index.php and paste it into the <head> section of your web page.

    <link rel="stylesheet" type="text/css" href="contact-form/css/pagestyles.css" />

You will need to choose a layout from the 4 we have designed for you (inline.css, block.css, standard.css, twocol.css). You can find an example of each layout in the live preview on CodeCanyon. Once you have chosen a layout, copy the code from line 8 of index.php and enter the name of the stylesheet layout you would like at the end of the `href` attribute for example, to choose the standard.css layout, copy the code below and paste it into the <head> section of your web page.

    <link rel="stylesheet" type="text/css" href="contact-form/css/standard.css" />

### 3. Copy the JavaScript links into your PHP page

The form requires the 4 JavaScript files shown below, to include them in your web page, copy lines 10 - 13 inclusive from index.php and paste them into your PHP page. Note: if your web page already uses the jQuery library you can skip copying the first line.

    <script type="text/javascript" src="contact-form/js/jquery-1.5.min.js"></script>
    <script type="text/javascript" src="contact-form/js/plugins.js"></script>
    <script type="text/javascript" src="contact-form/js/iphorm.js"></script>
    <script type="text/javascript" src="contact-form/js/scripts.js"></script>

### 4. Configure the contact form to send enquiries to your email address

To configure the contact form, open `contact-form/config.php` and on line 19 you will find the current email address that will be receiving the enquiries. Change that to your email address as shown below.

    $recipients = array(
        'spam@freerangewebdesign.com'
    );

becomes

    $recipients = array(
        'your@emailaddress.com'
    );

While you are in `contact-form/config.php` you can also change the success message if you wish, which is displayed when the form is successfully submitted. The code for that is on line 6.

### 5. Choosing a character encoding

You should also make sure the form is using the same character encoding as your website. By default the iPhorm works with UTF-8 encoding and will expect form data sent from your web page to be in this encoding.

#### Using UTF-8 encoding (recommended)

To set your web page to use UTF-8 encoding, insert the following meta tag just after the opening `<head>` tag of the web page your form is on:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

#### Using another encoding such as ISO-8859-1

If your web page uses another charset and you want the iPhorm to use the same charset, you must add the line of PHP code below to `config.php` (for example to use the ISO-8859-1 charset):

    $form->setCharset('ISO-8859-1');

For a list of all valid character encodings, see the charset section of this page.

### 6. Upload the `contact-form` folder to your web server via FTP

You should now upload the `contact-form` folder so that it resides in the same place as your PHP/HTML file containing the form. The `contact-form` folder and your PHP/HTML file should be in the same folder on your web server. If this setup is not possible, just change the `action=""` attribute of the `<form>` tag to point to the `contact-form/process.php` file.

Now visit your PHP/HTML page via your web browser, the form should appear and the contact form should work correctly. See the troubleshooting section below if you are having problems.

# Customising your form

## Adding a form element

To add a form element, there are two steps.

- 1. Add the HTML for the form element in your web page
- 2. Add the form element to the `config.php` file to make the PHP script aware of the new form element

Both steps are explained in more detail below.

### 1. Add the HTML for the form element in your web page

The easiest way to add another form element is to copy the existing HTML code from another element, including all surrounding wrappers. Each element included with the form has comments surrounding it and the file `contact-form/examples/example-all-elements.php` has example code for most form elements you will ever need to use. So to copy the entire element, you would select the all the HTML code between the comments. For example, lets say we wanted to add a new required field called "Fax". We would copy the HTML for the "Name" field by copying lines 27 - 34 of index.php and pasting the code in between the form elements that you would like your new element to be between. You would then change all occurences of "name" in your copied code with "fax" (except the actual name attribute key i.e. it should be `name="fax"` not `fax="fax"` on the input), to give us:

    <!-- Begin Fax element -->
    <div class="element-wrapper fax-element-wrapper clearfix">
        <label for="fax">Fax <span class="red">*</span></label>
        <div class="input-wrapper fax-input-wrapper">
            <input class="fax-element" id="fax" type="text" name="fax" />
        </div>
    </div>
    <!-- End Fax element -->

### 2. Add the form element to the `config.php` file to make the PHP script aware of the new form element

To make the PHP script aware of the new field, you will need to edit the `contact-form/config.php` file. You will need to create a new iPhorm_Element object for your new field, if you don't know how to do that just copy the existing code for the name element as on lines 41 - 44 then change everything that says "name" to "fax", giving us.

    $fax = new iPhorm_Element('fax');
    $fax->addFilter('trim');
    $fax->addValidator('required');
    $form->addElement($fax);

IMPORTANT: The part in red above must match the `name=""` attribute of the form element in the HTML. This tells the PHP script what element you are referring to. If we had given the input field the attribute `name="fax_number"` in the HTML, then the part in red above would also have to be fax_number. So that the form works perfectly, we recommend setting the name attribute in the HTML with all lower case with underscores where there should be spaces, e.g. if adding a field called "National insurance number" set the name attribute to be "national_insurance_number" in the HTML for the form element.

The filter you are adding to the element in the code above will trim whitespace from the start and end of the value submitted by the form user. The validator you are adding in the code above will make the field required. If you do not want those filters or validators for the element just delete the line that adds them. For more help on Filters and Validators see the Advanced form customisation section below.

You can also pass in a second argument when creating an element which sets the label for the element - what will be displayed above the field in the email. For example, if in the HTML your field was called "fax", by default the label would be "Fax" but you could change the label to be just "Fax number" with this code:

    $fax = new iPhorm_Element('fax', 'Fax number');

## Adding a multiple form element

There are a couple of elements that can have multiple values, for example, a group of checkboxes or a multiple select element. When adding these elements, you need to add a pair of square brackets to the name attribute of the element `[]`. To add a multiple form element, there are two steps.

- 1. Add the HTML for the form element in your web page
- 2. Add the form element to the config.php file to make the PHP script aware of the new form element

Both steps are explained in more detail below.

### 1. Add the HTML for the form element in your web page

The easiest way to add another form element is to copy the existing HTML code for the element, including all surrounding wrappers. There is an example of most HTML form elements and the code you should use in the file `contact-form/examples/example-all-elements.php`. Each element included with the form has comments surrounding it. So to copy the entire element you would select the all the HTML code between the comments. For example, lets say we wanted to add a multi checkbox field. We would copy the HTML for the "Multi checkbox" element by copying lines 68 - 79 of contact-form/examples/example-all-elements.php and pasting the code in between the form elements that you would like your new element to be between. You would then change all occurences of "multi_checkbox" in your copied code with the name you want to give your new element, below I have given it the name "number_of_kids" so I've updated all surrounding wrappers aswell to reflect this and so you can style the element individually.

    <!-- Number of kids element -->
    <div class="element-wrapper number_of_kids-element-wrapper clearfix">
        <label>Number of kids <span class="red">*</span></label>
        <div class="input-wrapper number_of_kids-input-wrapper clearfix">
            <input id="number_of_kids-One" name="number_of_kids[]"
                value="One" type="checkbox" />
                <label for="number_of_kids-One">One</label><br />
            <input id="number_of_kids-Two" name="number_of_kids[]"
                value="Two" type="checkbox" />
                <label for="number_of_kids-Two">Two</label><br />
            <input id="number_of_kids-Three" name="number_of_kids[]"
                value="Three" type="checkbox" />
                <label for="number_of_kids-Three">Three</label><br />
            <input id="number_of_kids-Four" name="number_of_kids[]"
                value="Four" type="checkbox" />
                <label for="number_of_kids-Four">Four</label><br />
            <input id="number_of_kids-Five" name="number_of_kids[]"
                value="Five" type="checkbox" />
                <label for="number_of_kids-Five">Five</label><br />
        </div>
    </div>
    <!-- End Number of kids element -->

### 2. Add the form element to the config.php file to make the PHP script aware of the new form element

To make the PHP script aware of the new field, you will need to edit the file `contact-form/config.php`. You will need to create a new iPhorm_Element object for your new field, if you don't know how to do that just copy the existing code for the one of the existing elements then change the name to suit your new element. The difference with multiple elements is the you need to add `[]` to the end of the name in config.php also. Continuing the above example would give us:

    $numberOfKids = new iPhorm_Element('number_of_kids[]');
    $form->addElement($numberOfKids);

IMPORTANT: The part in red above must match the `name=""` attribute of the form element in the HTML. This tells the PHP script what element you are referring to.

## Removing a form element

To remove a form element, there are two steps.

- 1. Remove the HTML for the form element in your web page
- 2. Remove the form element from the config.php file to make the PHP script aware that the form element is no longer there

Both steps are explained in more detail below.

### 1. Remove the HTML for the form element in your web page

Each form element and it's associated wrappers are commented individually in index.php. Find the form element you want to remove by looking at the class names of the elements, each element has their own class names that should help you identify them. Once you've found it, delete the HTML code between the comments surrounding the element. A common request is to remove the phone element. To do that, delete lines 43 - 50 of index.php then proceed to step 2.

### 2. Remove the form element from the config.php file to make the PHP script aware that the form element is no longer there

In `contact-form/config.php`, locate the code that creates the form element you want to remove. If you wanted to delete the phone element (lines 63 - 65 of config.php), the code you are looking for would be:

    $phone = new iPhorm_Element('phone');
    $phone->addFilter('trim');
    $form->addElement($phone);

Remove (or just comment out) these lines.

## Making a field required

A required field simply has a validator called 'required' added to it. You can use the method `addValidator()` on your element to add the required validator. In `config.php` if the element already has the code for addValidators() next to it, then just add 'required' as the next element in the array. Otherwise you will need to enter code on a new line to add the validator, for example if you wanted to make the phone field required add your new line of code to line 65:

    $phone = new iPhorm_Element('phone');
    $phone->addFilter('trim');
    $phone->addValidator('required');
    $form->addElement($phone);

It might also be a good idea to add an asterisk to the element label on your web page to let users know that the element is now required.

## Making a field not required

To make a field not required you need to remove the 'required' validator. Open `config.php` and find the PHP code for the element you want to change. There should be code that looks like the following:

    $element->addValidator('required'); // Single validator
    or
    $element->addValidators(array('required', 'email')); // Multiple validators

If the element has the single validator line of code, simply delete or comment out the line adding the required validator. If the element has the multiple validators line, remove the 'required' string and the comma after it. The multiple validators line would now look like this:

    $element->addValidators(array('email')); // Multiple validators (required removed)

It might also be a good idea to remove the asterisk from the field label on your web page to let users know that the field is no longer required.

## Changing layout

To change layout all you need to do is change the name of the stylesheet you are linking to. We have included 4 layouts with the form.

- standard.css - Standard layout, each label and field on it's own line
- block.css - Block layout, each label to the left and field on the right
- inline.css - Inline layout, smaller fields are placed side by side
- twocol.css - Two column layout, similar to block but without the borders

You can look at each layout on the live preview of the form on CodeCanyon. Once you have decided on a layout, change the link to the CSS stylesheet file in the <head> section of your web page to the filename of the layout you have chosen. To choose the two column layout see example below.

    <link rel="stylesheet" type="text/css" href="contact-form/css/twocol.css" />

### Non-JavaScript layout

We have minimally styled a page that non JavaScript users will see errors and success messages on using neutral colours. If you want to change the style of this page edit the file `contact-form/nojs.php`. To see what the page looks like, disable JavaScript in your browser and submit the form.

## Changing the tooltips

The form tooltips are created using the qTip jQuery plugin. See the sections below on changing the tooltips.

### Changing the text of a tooltip

The tooltips become active when the form element has the class iphorm-tooltip and it uses the content of the `title=""` attribute of the form element. If you want to change the text of a tooltip, locate the form element in the HTML and change the `title=""` attribute to the text you want to display.

### Adding or removing a tooltip

The tooltips become active when the form element has the class iphorm-tooltip and it uses the content of the `title=""` attribute of the form element. If you want to show a tooltip on an element that doesn't have one already, add the class iphorm-tooltip to the form element and add a `title=""` attribute containing the text you want to display in the tooltip.

To remove a tooltip from an element that already has one, remove the class iphorm-tooltip from the form element and remove the `title=""` attribute.

### Changing the look of the tooltips

The tooltip settings are contained in `contact-form/js/scripts.js` lines 5 - 21. The current style is "blue" (one of the built in ones of qTip). If you want to change these settings then consult the documentation of qTip available here.

## Changing the success message

The success message is the message that is displayed to the user when the form has been submitted. To change it open `config.php` and go to line 6. By default there is a mixture of HTML and text. You can add or remove as much HTML or text as you want there and it will not break the form in any way. Since the string is enclosed in single quotes `'`, if you want to include a single quote in your text or HTML you will need to escape it, by adding a backslash before it e.g. `\'`

## Changing / adding email recipients

Email recipients are the list of email addresses who will be sent the content of the form when it is submitted by the user. Some people may want this to go to multiple people so we have added the facility to do that. To add or change the recipients, open `config.php` and go to lines 18 - 20. You will find the array of current recipients. If you just want the email to go to one email address, then just change the email address that is there to your email address.

### Single recipient

    $recipients = array(
        'email@example.com'
    );

### Multiple recipients

    $recipients = array(
        'email@example.com',
        'another@email.com',
        'spam@freerangewebdesign.com'
    );

## Different email recipients based on chosen subject

You might want to change the recipients of the email based on the subject chosen by the form user. To do this you will need to change the recipients array depending on which subject was chosen. The code below shows an example of how you would do this and this code will replace lines 18 - 20 of config.php. The string after `case` should match the `value` attribute of the option in the HTML of the form.

### Different recipients per subject

    switch($_POST['subject']) {
        case 'General enquiry':
            $recipients = array(
                'email1@mydomain.com',
                'email2@mydomain.com',
                'email3@mydomain.com'
    	);
    	break;
        case 'Sales enquiry':
            $recipients = array(
                'email4@mydomain.com',
                'email5@mydomain.com',
                'email6@mydomain.com'
            );
            break;
        case 'Support enquiry':
            $recipients = array(
                'email7@mydomain.com',
                'email8@mydomain.com',
                'email9@mydomain.com'
            );
            break;
        default:
            // These will be the recipients if the subject does not match any above
            $recipients = array(
                'email1@mydomain.com',
                'email4@mydomain.com',
                'email7@mydomain.com'
            );
            break;
    }

## Changing the CAPTCHA image

It is possible that the captcha (Type the word) image that is included with the form does not match your design and you can change it quite simply. You will need to make your own image and there are 2 requirements you must follow.

- 1. The image must be placed in the `contact-form/images/` folder
- 2. The images should be png format and the filename should be be captcha.png
- 3. You will need to change the `config.php` file to change the token of the captcha validator to match the word contained in your new image. See below for more information.

In `config.php` location the configuration for the CAPTCHA field, you will see the code below

    $captcha->addValidator('identical', array('token' => 'light'));

Change the text light to match the word or letters that are in your new CAPTCHA image.

NOTE: The CAPTCHA system is very simple and will prevent random form submissions by bots roaming around the internet (which happens a lot). It will not prevent targeted attacks however, but the chances of that happening are small and most other CAPTCHAs are not safe against targeted attacks either. We beleive that an easy, simple CAPTCHA is a good trade off between the spam, usability and browser compatability of the form. Since at the end of the day you don't want to miss enquiries for new business by users being put off or unable to pass a complex CAPTCHA challenge. If you do need a more complex CAPTCHA field, see the section below for general guidelines.

## Changing the email subject

You can change the email subject to something that is more relevant to your form. To do this, open `contact-form/config.php` and go to line 29. Change the text inside the single quotes to the subject you want. You can use placeholder values inside % signs to have the value replaced by the form value of that name, such as in the default subject `%name%` will be replaced by the submitted value of the field with the name "name".

## Changing the label of an element

The element's label is shown in two places:

- The error page for non-JavaScript users (nojs.php)
- The email

By default the element's label is generated from the name of the element in the HTML be replacing underscores with spaces and capitalising the first letter. So for example, "type_the_word" becomes "Type the word". If you want to change the label you can pass a second argument in when creating the element in `config.php`. If you wanted to change the type_the_word element to say Security code in the non-JavaScript page for example, then do this:

    $captcha = new iPhorm_Element('type_the_word', 'Security code');

## Changing the "Please wait..." text

About two and a half seconds after the form has been submitted, the text "Please wait..." fades in on the form. You may want to change this to show different text or an animated loading gif, so that your users know that the form is working (e.g. uploading a file and not crashed) and so they don't try to refresh.

### Changing the text

The "Please wait..." text is located on line 83 of `index.php`, change the text to suit.

### Changing the text to an animated loading gif

The "Please wait..." text is located on line 83 of `index.php`, replace the text with your `<img>` tag pointing to your loading gif.

## Redirecting to another page after the form is submitted

You may want to have the user redirected to another page after submitting the form instead of the thank you message fading in. To achieve this you will need to do two things:

- 1. Add a JavaScript redirect for users with JavaScript enabled
- 2. Add a PHP redirect for users with JavaScript disabled

Both steps are explained in more detail below.

### 1. Add a JavaScript redirect for users with JavaScript enabled

Open `contact-form/js/scripts.js` and change the code on line 2 to read:

    $('form.iphorm').iPhorm({
        successRedirect: function() {
            window.location = 'your_thanks_page.html';
        }
    });

To reload the same page, use:

    $('form.iphorm').iPhorm({
        successRedirect: function() {
            window.location.reload();
        }
    });

### 2. Add a PHP redirect for users with JavaScript disabled

Open `contact-form/config.php` and add the following code:

    $form->setSuccessRedirect('your_thanks_page.html');

## Custom JavaScript success function

If you want to perform a custom JavaScript function when the form is submitted, use the following code in `contact-form/js/scripts.js` and change the code on line 2:

    $('form.iphorm').iPhorm({
        success: function() {
            // Your custom JS
        }
    });

## Custom JavaScript error function

If you want to perform a custom JavaScript function when the form has errors use the following code in `contact-form/js/scripts.js` and change the code on line 2.

    $('form.iphorm').iPhorm({
        error: function() {
            // Your custom JS
        }
    });

For example to show a message after the submit button if the form has errors, use the following code in `contact-form/js/scripts.js` and change the code on line 2:

    $('form.iphorm').iPhorm({
        error: function() {
            $('.submit-button-wrapper').after('<div class="error-message">There was an error in the form</div>');
        }
    });

# Advanced form customisation

## Multiple forms

You may want to have more than one form on the same site but with different fields. Such as a register form and a contact form. To do that, set up the first form as instructed in the installation guide at the start of this document. To make the second form, copy the HTML for the iPhorm again into the body of the page that you want your second form on and customise your new form as described in the Customising your form section above. Then make a copy of the `contact-form/config.php` file and call it something like `contact-form/config-register.php`. That file you should customise with the fields for your register form as described in the Customising your form section above. You should then change the `action` attribute of your register form so that it now includes a variable called `form` that has a value of the file you want to load excluding "config-" and ".php". For example in the register example set the action attribute to `<form class="iphorm" action="contact-form/process.php?form=register" ...`.

More examples...

- contact-form/process.php?form=register will load the config file config-register.php
- contact-form/process.php?form=subscribe will load the config file config-subscribe.php
- contact-form/process.php?form=sign_up will load the config file config-sign_up.php
- contact-form/process.php will load the config file config.php
- and so on...

## Multiple forms on the same page

To have more than one iPhorm on the same page, just copy the HTML for the iPhorm again and paste it into another area of your page. You will then need to create a new config file and change the form `action` attribute as described in the section Multiple forms above. There is only one issue and that is that the form elements in the iPhorm have an `id=""` attribute, so when you have more than one element with the same id on a page, it is no longer valid HTML, however the form will still work. If you want your page to pass W3C validation then you should change or remove the id attributes for the elements in the second form.

## Email settings

The emails sent out by the system are sent by the SwiftMailer library, a powerful set of classes that will allow you to do pretty much anything you need to do with sending emails from PHP.

The email success handler is responsible for generating the email content and sending the email via the library. To edit the code for this, you should check out the file `contact-form/classes/iPhorm/SuccessHandler/Email.php`. The `run()` method starting on line 200 contains the code to configure the email, if you need to make a change then that is the place to do it. You should check out the SwiftMailer documenation to help you customise the settings.

The email is sent using PHP's `mail()` function by default, if your host does not support this, you can change it to use an SMTP server instead. See the section below on how to do this.

## Customising the email

The email is sent out in both an HTML version and a plain text version, your email software will usually show you the HTML version unless it doesn't support HTML and then it will show the plain text version (the content is the same). You can customise the emails to suit your needs. The HTML version of the email is contained in the file `contact-form/emails/email-html.php`, and the plain text version is in `contact-form/emails/email-plain.php`. It is recommended to use tables and inline CSS to style HTML emails for maximum compatibility. Check out this page for help.

## Sending the form user an autoreply email

You may want to send the form user an email to let them know that their enquiry was sent successfully. To do this you will need to open the file `contact-form/config.php`. On line 30 add the following code.

    $emailSuccessHandler->setAutoReply('Thanks for your enquiry %name%',
           'autoreply-html.php', 'autoreply-plain.php');

The first argument is the email subject, the second argument is the filename of the HTML version of the email, the third argument is the filename of the plain text version of the email. The email files should be placed in `contact-form/emails/` to be found. The subject can contain placeholder variables, surrounded by `%` signs. The submitted value of the form element with that name will be used in its place. If you use the code above the auto reply feature will load these files:

- `contact-form/emails/autoreply-html.php` - HTML version of the email
- `contact-form/emails/autoreply-plain.php` - plain text version of the email

It is recommended to complete both HTML and plain text versions so that the email can be read by all email software.

### Different autoreply emails per form

If you want another form to have another auto reply, you should make a copy of `autoreply-html.php` and `autoreply-plain.php` and name them something different then customise the content. Then in the `config.php` file for your new form, use the new filenames instead. For example if you have named the HTML version for your second form `autoreply-register-html.php` and the plain text version `autoreply-register-plain.php`

    $emailSuccessHandler->setAutoReply('Thanks for your enquiry %name%',
           'autoreply-register-html.php', 'autoreply-register-plain.php');

## Sending emails via an SMTP server

To use an SMTP server to send the emails you will need to make a change to the email success handler. The file you need to change is `contact-form/classes/iPhorm/SuccessHandler/Email.php`. On line 203 there is the code telling SwiftMailer to use the PHP's `mail()` function. Comment out the line by inserting `//` at the start. You should now uncomment line 206 which will tell SwiftMailer to use an SMTP server instead. You will need to replace the host, username and password values with the correct ones for your SMTP server. For further information refer to the SwiftMailer documenation.

## Saving form data to a database

iPhorm comes with a Mysql database success handler that allows you to save the form information to a Mysql database. Below is an example of how to use this, the code should be placed in `config.php`

    $dbConfig = array(
        'host' => 'localhost',
        'username' => 'your_username',
        'password' => 'your_password',
        'dbname' => 'your_dbname',
        'table' => 'your_table'
    );

    $fieldMap = array(
        'name' => 'name',
        'email' => 'email_address',
        'phone' => 'phone_number'
    );

    $mysqlSuccessHandler = new iPhorm_SuccessHandler_Mysql($form);
    $mysqlSuccessHandler->setConfig($dbConfig);
    $mysqlSuccessHandler->setFieldMap($fieldMap);

The `$dbConfig` array must contain the settings for your database. The `$fieldMap` array is a mapping of the form element name to the database table field name. So in the above example the data in the form element `name` will save to the database table field `name`, the form element `email` will save to the database table field `email_address`, the form element `phone` will save to the database table field `phone_number`. Any other fields will be ignored unless they are specified in the field map. If the form element value is an array from a multiple field for example, it will be saved as each value joined with commas. All data entered in to the database is escaped using `mysql_real_escape_string()` so it is safe.

For more customisation than this, you would be better editing the code of the file `contact-form/classes/iPhorm/SuccessHandler/Mysql.php` and changing the code to suit your needs. Alternatively you can write your own success handler - see the section below.

## Creating your own success handler

A success handler is a PHP class containing code that will be run when the form is successfully submitted. You can created your own success handler to run custom code on the form values when the form is submitted and you can have as many success handlers on the form as you need. The success handler class has some requirements to work correctly:

- 1. Your class name must begin with iPhorm_SuccessHandler_
- 2. Your class file must be placed in the folder `contact-form/classes/iPhorm/SuccessHandler/`
- 3. Your class filename must be the last part of the class name and end with .php
- 4. Your class must extend `iPhorm_SuccessHandler_Abstract`
- 5. Your class must have a method called `run()`, which will automatically be called by the form when submitted successfully
- 6. When creating a new instance of your success handler in config.php you should pass in the `$form` as the constructor argument

If in doubt, check or copy the existing success handlers. In your run method you can enter what ever PHP code you want to maniplulate the form data. You have access to the form instance and you can iterate through the fields using the method `$this->_form->getElements()`. For more information on available class methods consult the iPhorm class documentation in the documentation folder.

## File uploads

You can add file upload form elements to your form and you can attach the uploaded files to the email that is sent out to you. You will need to do two things to get file uploads working:

- 1. Add your file upload HTML element to your form
- 2. Add code to `config.php` to make the PHP code aware of your file element

Each step is explained in more detail below:

### 1. Add your file upload HTML element to your form

Below is sample HTML for a file upload field with standard iPhorm wrappers:

    <div class="element-wrapper upload-element-wrapper clearfix">
        <label for="upload">Upload <span class="red">*</span></label>
        <div class="input-wrapper upload-input-wrapper">
            <input class="upload-element" id="upload" type="file" name="upload" />
        </div>
    </div>

NOTE: The PHP manual recommends that you add a hidden input before your file input with the maximum allowed file size in bytes, this way users do not have to wait for files to be uploaded before being told that they are too large. The code you need to add is below and should be placed before your file input element. The number is the maximum file size in bytes (1048576 bytes = 1MB) so if you wanted to allow a 10MB file set the value to 1048576 x 10 = 10485760.

    <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />

### 2. Add code to `config.php` to make the PHP code aware of your file element

Now you need to make the PHP script aware of your new file upload field. The code you need to do that is shown below.

    $upload = new iPhorm_Element_File('upload');
    $form->addElement($upload);
    $emailSuccessHandler->addAttachmentElement($upload);

See the troubleshooting section if you are having problems with the file uploads.

### Making the upload required

To make the upload required use the following code:

    $upload->setRequired(true);

### Setting allowed file extensions

You can set the allowed file extensions so that any other files will be rejected by the form. You should pass in an array of lowercase file extensions e.g.:

    $upload->setAllowedExtensions(array('gif', 'jpeg', 'jpg', 'png'));

### Setting a maximum file size

You can also limit the upload by file size. The default upload limit is 10MB since many email providers do not support attachments larger than that. To set the maximum upload size, use this code:

    $upload->setMaximumFileSize(10485760);

The maximum file size is in bytes which is (Size in MB x 1048576)

NOTE: The file upload size can be limited by 4 things:

- Your hidden input MAX_FILE_SIZE as shown above
- The iPhorm max size setting `$yourElement->setMaximumFileSize(10485760);`, you can set this to no limit by using `$yourElement->setMaximumFileSize(0);`
- The PHP configuration setting post_max_size
- The PHP configuration setting upload_max_filesize

### Grouping multiple file uploads

If you have multiple upload fields you can group them under the same element using the multiple field syntax e.g. `element_name[]`. This way you do not need to create an iPhorm_Element_Files's in the PHP code for each upload element. For example you could have the following code to group 3 uploads:

    <div class="element-wrapper upload-element-wrapper clearfix">
         <label>Grouped file upload <span class="red">*</span></label>
         <div class="input-wrapper upload-input-wrapper clearfix">
             <input type="file" class="upload-element" id="uploads-1" name="uploads[]" />
         </div>
         <div class="input-wrapper upload-input-wrapper clearfix">
             <input type="file" class="upload-element" id="uploads-2" name="uploads[]" />
         </div>
         <div class="input-wrapper upload-input-wrapper clearfix">
             <input type="file" class="upload-element" id="uploads-3" name="uploads[]" />
         </div>
     </div>

And in your config.php the code would look like:

    $uploads = new iPhorm_Element_File('uploads[]');
    $form->addElement($uploads);
    $emailSuccessHandler->addAttachmentElement($uploads);

### Require a specific number of uploads for a multiple element

If you used the grouped upload code above and you set the field to be required using `$uploads->setRequired(true);` then all 3 uploads would be required. If you wanted only one upload to be required from the group then you should add the code below:

    $uploads->setRequired(true);     // The element is required
    $uploads->setRequiredCount(1);   // At least 1 upload is required

## Storing file uploads

We have added a new success handler to store file uploads on the server. I'm going to walk through an example of having a screenshot upload field in your form and storing the uploaded files in the contact-form/screenshots/ folder. There are three things you need to do to get this working.

- 1. Add the HTML for the file upload field to your form
- 2. Add the file element to `config.php`
- 3. Configure the file storage success handler in `config.php`

### 1. Add the HTML for the file upload field to your form

Here's the HTML for a file upload field called `screenshot`, you should add this inside your form.

    <div class="element-wrapper screenshot-element-wrapper clearfix">
      <label for="screenshot">Screenshot</label>
      <div class="input-wrapper screenshot-input-wrapper">
       <input class="screenshot-element" id="screenshot" type="file" name="screenshot" />
      </div>
    </div>

### 2. Add the file element to `config.php`

Open `config.php` and add the code to create the file element, you can put this anywhere in the file.

    $screenshot = new iPhorm_Element_File('screenshot');
    $screenshot->setAllowedExtensions(array('gif', 'jpeg', 'jpg', 'png'));
    $form->addElement($screenshot);

### 3. Configure the file storage success handler in `config.php`

Now we need to add the file storage success handler and configure it. The element map shown below is set up as follows. The array key is the name of the element in the HTML (exclude the [] if its a multiple field) and the array value is the folder that the files should be stored in.

    $elementMap = array(
        'screenshot' => IPHORM_ROOT . '/screenshots/'
    );
    $fileStorageSuccessHandler = new iPhorm_SuccessHandler_FileStorage($form);
    $fileStorageSuccessHandler->setElementMap($elementMap);

For more customisation than this you will need to edit the file `classes/iPhorm/SuccessHandler/FileStorage.php` or create your own success handler.

### More than one upload field

If you have more than one upload field in your form the process is the same but the $elementMap array will change slightly, the array will have another row for each field:

    $elementMap = array(
        'screenshot' => IPHORM_ROOT . '/screenshots/',
        'upload_field_2_name' => IPHORM_ROOT . '/uploads/',
        'upload_field_3_name' => IPHORM_ROOT . '/uploads2/'
    );

## Using a more complex CAPTCHA

I will explain briefly how to make a CAPTCHA field that will generate a random image, store the result using PHP sessions, then use an iPhorm validator to check if the entered result is correct. There are three things you will need to do:

- 1. Create a PHP file that will generate the CAPTCHA image and store the expected result
- 2. Change the existing CAPTCHA image to link to the PHP file above
- 3. Customise the supplied CAPTCHA validator to check the submitted result against the expected result
- 4. Add the CAPTCHA validator to the form element

Each step is explained in more detail below.

### 1. Create a PHP file that will generate the CAPTCHA image and store the expected result

Create a random CAPTCHA image using PHP and the GD image extension. There are many examples on the internet on how to do this, for example, Step 1 of this page. Make sure to save the expected result in `$_SESSION['captcha']`. Save the file as captcha.php

### 2. Change the existing CAPTCHA image to link to the PHP file above

Change the img `src=""` attribute of the existing CAPTCHA to point to your new captcha.php file.

### 3. Customise the supplied CAPTCHA validator to check the submitted result against the expected result

Open the file classes/iPhorm/Validator/Captcha.php an make sure the code looks to suit your requirements, e.g. your security code expected result is stored in `$_SESSION['captcha']`. You should also add `<?php session_start(); ?>` to the web page with your form on it, and also at the top of `contact-form/process.php`.

### 4. Add the CAPTCHA validator to the form element

In `contact-form/config.php` add the 'captcha' validator to your CAPTCHA element.

    $captcha->addValidator('captcha');

The instructions are probably too difficult for a novice web designer to do, so if that's you then you should either stick with the basic CAPTCHA field or hire a professional web developer to set it up for you.

## Filters

You can use Filters to strip data from the user submitted value such as HTML tags (which may be harmful) and useless white space and the start and end of the value. There are filters included with the form that do just that and more, although you can add your own too - see Adding a new filter below.

### Included filters

- trim - strips whitespace and other characters from the start and end
- stripTags - strips all HTML tags
- digits - filters everything except digits
- alphaNumeric - filters everything except alphanumeric characters
- alpha - filters everything except alphabet characters

So if you assign a Filter to an Element then the value that will appear in the email will be the filtered value. The values are filtered before they are validated too.

As an extreme example, a value like ' <script></script> ' with the stripTags and trim filter and the required validator will actually fail validation, because once the tags are stripped and the white space is trimmed the value is empty so it fails the required validator.

## Adding a filter to a form element

To add a filter to an element, you will need to open `config.php` and find the code that creates the element you want to add the filter to. It may already have a line below it that is calling `addFilters()`, in that case just add the name of the filter you want to add at the end of the array that is passed in. If the element had the following code.

    $yourElement->addFilter('trim');

You can just add another line below that adds the new filter. For example if you wanted to add the alphaNumeric filter also you can make the code:

    $yourElement->addFilter('trim');
    $yourElement->addFilter('alphaNumeric');

You could also use the following code

    $yourElement->addFilters(array('trim', 'alphaNumeric'));

For the geeks out there you can also instantiate the filter directly then add it to the element. Which may help with your own custom filters if you need to make any that you need to pass options to, for example.

    $trimFilter = new iPhorm_Filter_Trim();
    $yourElement->addFilter($trimFilter);

## Removing a filter from a form element

To remove a filter from a form element, find the code that creates and configures the element in `config.php`. Look for the line that is adding the filters e.g.

    $yourElement->addFilters(array('stripTags', 'trim'));

To remove only the stripTags filter:

    $yourElement->addFilters(array('trim'));

To remove both the filters delete or comment out the entire line.

## Filter options (Advanced)

You can pass in options to filters to change the way they operate. You can pass in options using the `addFilter()` method on an element. Pass in an array as the second argument containing the array keys that are options of the filter. See the documentation below on each filter or the code for the filters in the `contact-form/classes/iPhorm/Filter/` folder to see the options you can use.

    $yourElement->addFilter('stripTags', array('allowableTags' => array('<br>', '<p>')));

You can also pass in options at instantiation and then add the filter object to your element.

    $stripTagsFilter = new iPhorm_Filter_StripTags(array('allowableTags' => array('<br>')));
    $yourElement->addFilter($stripTagsFilter);

### Trim filter

No options.

    $yourElement->addFilter('trim');

### StripTags filter

Options

- allowableTags - an array of strings of the tags you do not want to be stripped

    $yourElement->addFilter('stripTags', array('allowableTags' => array('<br>', '<p>')));

### Digits filter

No options.

    $yourElement->addFilter('digits');

### Alphanumeric filter

Options

- allowWhiteSpace - boolean true or false, if true white space is not filtered, default false

    $yourElement->addFilter('alphaNumeric', array('allowWhiteSpace' => true));

### Alpha filter

Options

- allowWhiteSpace - boolean true or false, if true white space is not filtered, default false

    $yourElement->addFilter('alpha', array('allowWhiteSpace' => true));

## Validators

Validators check the user submitted values against a set of rules to see if they are valid. If the value is valid nothing happens, the next validator and form element will be checked for validity. If the value is not valid, the error messages generated by the Validator will be returned back to the user and the form will not be submitted. If the value submitted to every form element passes that form element's validators then the entire form is valid and it is submitted.

There are 11 validators included with the form, although you are free to add as many as you want - see Adding a new validator below.

- required - The value is required and it cannot be empty
- email - The value must be a valid email address
- captcha - The value must match the letters set by captcha.php
- stringLength - The length of the value must be between the set min and max
- lessThan - The value must be less than the set max (numerically)
- greaterThan - The value must be greater than the set min (numerically)
- digits - The value must be only digits
- alphaNumeric - The value must have only alphanumeric characters
- alpha - The value must have only alphabet characters
- fileUpload - Validates the file upload against set options
- identical - The value must be identical to the set token

## Adding a validator to a form element

To add a validator to an element, you will need to open `config.php` and find the code that creates the element you want to add the validator to. It may already have a line below it that is calling `addValidators()`, in that case just add the name of the validator you want to add at the end of the array that is passed in. If the element had the following code.

    $yourElement->addValidator('required');

You can just add another line below that adds the new validator. For example if you wanted to add the digits validator also you can make the code:

    $yourElement->addValidator('required');
    $yourElement->addValidator('digits');

You could also use the following code

    $yourElement->addValidators(array('required', 'digits'));

For the geeks out there you can also instantiate the validator directly then add it to the element. Which may help with your own custom validators if you need to make any that you need to pass options to, for example.

    $emailValidator = new iPhorm_Validator_Email();
    $yourElement->addValidator($emailValidator);

## Removing a validator from a form element

To remove a validator from an element, you will need to open `config.php` and find the code that creates and configures the element you want to remove the validator from. Look for the line that has code similar to the code below.

    $yourElement->addValidators(array('required', 'email'));

To remove only the email validator make it like so.

    $yourElement->addValidators(array('required'));

To remove all validators, delete or comment out the entire line.

## Changing the error message generated by a validator

Locate the validator you want to change the error message for in the folder `contact-form/classes/iPhorm/Validator/` and find the file for the Validator you want to change. Once you've found it, open the file and look inside the `isValid()` method for code that looks like this:

    $this->addMessage('This field is required');

These are the messages that are returned to the form when validation fails, change them to whatever you like.

## Validator options (Advanced)

You can pass in options to validators to change the way they operate. You can pass in options using the `addValidator()` method on an element. Pass in an array as the second argument containing the array keys that are options of the validator. See the documentation below on each validator or the code for the validators in the files in the `contact-form/classes/iPhorm/Validator/` folder to see the options you can use.

    $yourElement->addValidator('stringLength', array('min' => 5, 'max' => 10));

You can also pass in options at instantiation and then add the validator object to your element.

    $stringLengthValidator = new iPhorm_Validator_StringLength(array('min' => 5,
                'max' => 10));
    $yourElement->addValidator($stringLengthValidator);

### Email validator

No options.

    $yourElement->addValidator('email');

### Required validator

No options.

    $yourElement->addValidator('required');

### Captcha validator

No options.

    $yourElement->addValidator('captcha');

### StringLength validator

Options

- min - (integer) the minumum length of the string
- max - (integer) the maximum length of the string, if not specified there is no maximum

    $yourElement->addValidator('stringLength', array('min' => 5, 'max' => 10));

### LessThan validator

Options

- max - (integer|string) the value must be less than max (numerically)

    $yourElement->addValidator('lessThan', array('max' => 10));

### GreaterThan validator

Options

- min - (integer|string) the value must be greater than min (numerically)

    $yourElement->addValidator('greaterThan', array('min' => 3));

### Digits validator

No options.

    $yourElement->addValidator('digits');

### AlphaNumeric validator

No options.

    $yourElement->addValidator('alphaNumeric');

### Alpha validator

No options.

    $yourElement->addValidator('alpha');

### FileUpload validator

The validator is automatically registered with your file upload elements, see the file uploads section above for options.

### Identical validator

Options

- token - (mixed) the token to compare the value against
- strict - (boolean) whether to also check for identical types (i.e. uses === instead of == if true), default true

    $yourElement->addValidator('identical', array('token' => 'light', 'strict' => false));

## Adding a new filter (Advanced)

If you want to add a new filter you should first check out the files in the folder `contact-form/classes/iPhorm/Filter/`. You will find the code for existing filters which should give you an idea of how to make your own. What you need to do is add a new class in that folder for your new filter, however there are a few things you should note.

- Your filter must have it's own class with a name that begins with iPhorm_Filter_
- The name of the file should be the part after iPhorm_Filter_ ending with .php
- Your filter class must implement iPhorm_Filter_Interface
- Your filter class must have a method called `filter()` that takes the given value and returns the filtered value

### Naming your filter

Filters have a special naming system in order to add them to an element. If you notice two of the existing filter classes called iPhorm_Filter_StripTags and iPhorm_Filter_Trim which are added to element using the names stripTags and trim. The conversion between short name and class name happens automatically. To convert from short name to class name, make the first letter uppercase and add iPhorm_Filter_ to the beginning. To convert from class name to short name make the first letter lowercase and remove iPhorm_Filter_ from the beginning. If you made a new filter with the class name `iPhorm_Filter_MyNewFilter` you could add it to an element using:

    $yourElement->addFilters(array('myNewFilter'));

You can also add the filter to the element by passing in an instance of it:

    $yourElement->addFilter(new iPhorm_Filter_MyNewFilter());

## Adding a new validator (Advanced)

Before adding a new validator you should take a look at the files in the folder `contact-form/classes/iPhorm/Validator/`. You will find the code for existing validators which should give you an idea of how to make your own. What you need to do is add a new class in that folder for your new validator, however there are a few things you should note.

- Your validator must have it's own class with a name that begins with iPhorm_Validator_
- The name of the file should be the part after iPhorm_Validator_ ending with .php
- Your validator class must extend iPhorm_Validator_Abstract
- Your validator class must have a method called `isValid()` that takes the given value and returns true if the value is valid and false otherwise.
- Inside the `isValid()` method you can add messages to display back to the user to tell them why the value failed validation by using the code `$this->addMessage('Message to send to user');`. That message will appear under the form element by default.

### Naming your validator

Validators have a special naming system in order to add them to an element. If you notice two of the existing validator classes called iPhorm_Validator_Required and iPhorm_Validator_Email which are added to element using the names required and email. The conversion between short name and class name happens automatically. To convert from short name to class name, make the first letter uppercase and add iPhorm_Validator_ to the beginning. To convert from class name to short name make the first letter lowercase and remove iPhorm_Validator_ from the beginning. If you made a new validator with the class name `iPhorm_Validator_MyNewValidator` you could add it to an element using:

    $yourElement->addValidators(array('myNewValidator'));

You can also add the validator to the element by passing in an instance of it:

    $yourElement->addValidator(new iPhorm_Validator_MyNewValidator());

## Working with forms with deep nested arrays (Advanced)

If you have set up your form elements such that they are using deep nested array structure in their names as shown below.

    <input type="text" name="customer_info[delivery_details][postcode]" />

You will need to call the following code during form element configuration:

    $yourElement->setIsArray(true);

This will tell the form to expect an array for the value submitted and the element will not work properly without it. NOTE: Single level arrays such as multiple value elements:

    <input type="checkbox" name="toppings[]" />

DO NOT need the `setIsArray(true);` code. One level deeper than that and things will not work (the value will not be passed correctly to the form element so it may appear blank in the email) and you WILL NEED to use `setIsArray(true);`.

# Troubleshooting

## You do not receive the email

The iPhorm uses PHP's `mail()` function (via the SwiftMailer library) to send the email by default. Some web hosts may not allow you to use this function or require that you set certain headers. So we need to find out if you can send a simple email using your web server. We have created a test script so that you can check to see if you can do that. The script is located `contact-form/mail-check.php`, to set up the script:

- 1. Open the file and read the introductory comment
- 2. Change the email address on line 26 to your email address
- 3. Upload the file to your web server
- 4. Visit the page in your web browser

If the script indicates there is a problem with the `mail()` function and your hosting company then you can try and set up the form to send the email via an SMTP server instead, such as your ISP's server. See the section called Sending emails via an SMTP server in the Advanced form customisation section above.

### Finding out what you need to do to use mail() with your web host

Search Google for "[your hosting company] php mail", usually there are forum posts by other people who are having trouble with the host and mail() and there is usually a solution in the forum. For example some hosts require that the "From:" address is an email address from your domain that is hosted with them. In this case you can set use the code below on line 30 of `contact-form/config.php`.

    $emailSuccessHandler->setFromAddress('email@yourdomain.com');

## Form does not submit

This could happen for a lot of reasons. Look for JavaScript errors in the status bar of your web browser, if there is an error with another script it may also break the contact form.

We recommend using the Firebug extension for debugging if you do not already. If you enable the Net tab you will be able to see the Ajax requests being sent and received by the form and this can help to debug any problems you have in the PHP code because it isn't obvious when working with an Ajax application.

A good way to check for errors is to disable JavaScript in your browser and submit the form, any errors that are in your PHP code will be sent to the browser instead of silently back to the JavaScript so this might help you find some problems.

## File upload troubleshooting

### Email does not arrive

If your email doesn't arrive, try it again without the file upload field. If it still doesn't arrive then try the suggestions in the "You do not recieve email" section above. If the email only doesn't arrive when you have a file upload field, you might be exceeding email size limits of your web host or one of the relays, so try a really small attachment. If it still does not work, contact us and we'll try and help you fix it.

### Email does not have attachments

Double check you have added the file upload element to the form and added the element to the email success handler in `config.php`, as described in the file uploads section above.

### Maximum file size problems

By default PHP only allows an `upload_max_filesize` of 2MB. You will need to change this setting in php.ini to your value, if you don't have access to change php.ini check with your web host about how to change PHP settings. Many hosts will allow you to make changes to these values. The other value you will need to check is `post_max_size`, which is needs to be larger than your `upload_max_filesize` value.

### Form returns this field is required for all fields

You may be exceeding limit the PHP ini directive `post_max_size` which apparently sets $_POST and $_FILES to empty arrays, thus your form will say that these fields are required. So increase the limit.

## Conflicts with other JavaScript libraries (prototype or Mootools etc)

If your web page uses another JavaScript library such as prototype or Mootools etc your form might not submit so you may need to set jQuery into noConflict mode for the form to still work correctly. To do this, open `js/scripts.js` and on line 1 add this code before anything else:

    jQuery.noConflict();

## Solutions to error messages

### Address in mailbox given [] does not comply with RFC 2822 , 3.6.2.

The recipient email address you have set in config.php is not valid. Enter a valid email address or see here for a workaround.

The troubleshooting section will be updated as the form develops.
Full changelog

# Further support

For additional help you may email support@freerangewebdesign.com. If you would like us to customise your form for you, we will be happy to do this at our hourly rate of £30 per hour. Contact info@freerangewebdesign.com if you would like to hire us!