PalmsForm User Guide & API
PalmsForm takes all the hard work out of form building. You can get a form up and running within minutes. Form configuration and validation was never so easy. The best part about this library is that it is so flexible and convenient for you to customize your form, add / remove form fields, modify error messages, and extend core functionality of the library with minimal effort. As a result, you can use PalmsForm for all kinds of form, in all kinds of web sites and applications. It just works.
For users who only want to implement a contact form, it would take you only thirty seconds to set it up. Please play around with our example to see it in action.
Table of Contents
Implementing a contact form
To start using PalmsForm, you need to include the library and create an instance of the form.
require_once( 'palmsform.php' ); $form = new PalmsForm();
Then, in your HTML code, to insert the form, simply put this line of code where you want the form to be displayed:
$form->show( 'my-form-id' );
Replace my-form-id with the desired ID of your <form> element. If you want the form to be submitted to a different page. Specify the "action" attribute as well:
$form->show( 'my-form-id', 'http://example.com/form.php' );
Finally, to send an email containing the contact form's contents in case the user submitted data is valid, put this snippet of code anywhere, preferably before where you put your contact form.
if ( isset( $_POST['submit'] ) ) {
if ( $form->isValid() ) {
$form->mail( 'your_email_address@domain.com', 'Your Email Subject' );
}
}
In case the user enter invalid data, the error messages will automatically be displayed. There, all done!
Please check out our example contact form to see it in action.
Basic form configuration
With PalmsForm, you can easily add or remove fields from your contact form. The library also comes with many built-in validation rules that you can set for your form fields.
In order for these configurations to work, you need to do it before the form is displayed.
Adding form fields
In order to add a form field, you will need to use these two methods:
$form->addFieldBefore( $name, $fieldProperties, $beforeField ); $form->addFieldAfter( $name, $fieldProperties, $afterField );
$name: the name of the new field. This will be put in the "name" attribute of the HTML element.$fieldProperties: an array that contain information regarding the new field. Each type of field requires slightly different field properties.$beforeField / $afterField: the name of the existing field that you want to prepend / append the new field to.
Let's look at an example. To add a text field called "Homepage" before "Message", or after "Phone", we can use one of following methods:
$homeField = array( 'type' => 'text', // specify type as text field 'rules' => 'required', // specify this as a required field 'label' => 'Homepage', // specify the label (title) of the field ); $form->addFieldBefore( 'homepage', $homeField, 'message' ); /* or */ $form->addFieldAfter( 'homepage', $homeField, 'phone' );
Below you will find how to set up the field properties for different kinds of fields. There are required properties and optional properties. Required properties must be given when you add a field, while you don't have to define optional properties unless you want to.
Textfield
Required properties:
type: should be set to "text".label: the label (title) of the field.
Optional properties:
id: the ID of the input field.rules: a comma-separated lists of validation rules to apply to this field.messages: an array containing pairs of values, the first value is the name of a validation rule, the other is a custom validation error message for that rule which applies only to this field.default: default value of the field.maxlength: the same as "maxlength" attribute of the <input type="text" /> element.size: the same as "size" attribute of the <input type="text" /> element.
Example:
$homeField = array( 'type' => 'text', 'label' => 'Homepage', 'maxlength' => 70, );
Password
Basically the same as Textfield, but the 'type' must be "password".
Example:
$password = array( 'type' => 'password', 'rules' => 'required, min_length[8]', 'label' => 'Homepage', );
Text Area
Required properties
type: should be set to "textarea".label: the label (title) of the field.
Optional properties:
id: the ID of the textarea field.rules: a comma-separated lists of validation rules to apply to this field.messages: an array containing pairs of values, the first value is the name of a validation rule, the other is a custom validation error message for that rule which applies only to this field.default: default value of the field.cols: the same as "cols" attribute of the <textarea> element. Defaults to a blank string.rows: the same as "rows" attribute of the <textarea> element. Defaults to a blank string
Example:
'message' => array( 'type' => 'textarea', 'label' => 'Message', 'rules' => 'required', 'cols' => 40, 'rows' => 5, ),
Checkbox
Required properties
type: should be set to "checkbox".label: the label (title) of the field.value: the value of the checkbox
Optional properties:
id: the ID of the input field.rules: a comma-separated lists of validation rules to apply to this field.messages: an array containing pairs of values, the first value is the name of a validation rule, the other is a custom validation error message for that rule which applies only to this field.checked:trueorfalse. Specifies whether the checkbox be checked by default.
Example:
$checkbox = array( 'type' => 'checkbox', 'label' => 'I agree with the Terms of Condition.', 'checked' => true, 'rules' => 'required', 'value' => 'yes', );
Radio
Basically this is the same as a checkbox. The only difference is that "type" should be set to "radio".
Example:
$radio = array( 'type' => 'radio', 'label' => 'A random radio box', 'value' => 'some_value', );
Checkbox and Radio Group
This type of field is used to display multiple checkboxes or radios that are closely related to one another.
Required properties
type: should be set to "checkboxes" or "radios".label: the label (title) of the group.items: an associative array containing pairs of strings, specifying the values and titles of each individual checkbox / radio.
Optional properties:
rules: a comma-separated lists of validation rules to apply to this field.messages: an array containing pairs of values, the first value is the name of a validation rule, the other is a custom validation error message for that rule which applies only to this field.
Example:
$checkboxes = array( 'type' => 'checkboxes', 'label' => 'Which fruits would you like for breakfast?', 'items' => array( 'banana' => 'Banana', 'apple' => 'Apple', 'orange' => 'Orange', ), ); $radios = array( 'type' => 'radios', 'label' => 'Select one fruit.', 'items' => array( 'banana' => 'Banana', 'apple' => 'Apple', 'orange' => 'Orange', ), );
Dropdown
Required properties
type: should be set to "select".label: the label (title) of the group.options: an associative array containing pairs of strings, specifying the values and titles of each option in the dropdown.
Optional properties:
rules: a comma-separated lists of validation rules to apply to this field.messages: an array containing pairs of values, the first value is the name of a validation rule, the other is a custom validation error message for that rule which applies only to this field.
Example:
$dropdown = array( 'type' => 'select', 'label' => 'Select a fruit', 'options' => array( 'banana' => 'Banana', 'apple' => 'Apple', 'orange' => 'Orange', ), );
Hidden Field
Required properties
type: should be set to "hidden".value: the value of the hidden field.
Example:
$hidden = array( 'type' => 'hidden', 'value' => 'hiddenValue', );
Submit Button
Required properties
type: should be set to "submit".label: the label (title) of the group.
Example:
$submitButton = array( 'type' => 'submit', 'label' => 'Send', );
Removing form fields
To remove a form field, simply use this method:
$form->removeField( $fieldName );
Replace $fieldName with the name of the field you want to remove.
Setting / modifying validation rules
As described above, each form field can have an optional property called "rules". This property is basically a comma-delimited list of validation rules to apply when the form is submitted. Here is a list of available built-in validation rules:
| Rule | Description | Example |
|---|---|---|
| required | Fails if the form field is left empty. | |
| Fails if the value of the field is not a valid email address. | ||
| matches[] | Fails if the value of the field does not match that of another field of which the name is specified inside the brackets. | matches[another_field_name] |
| min_length[] | Fails if the length of the field is below the number specified inside the brackets. | min_length[8] |
| max_length[] | Fails if the length of the field exceeds the number specified inside the brackets. | max_length[20] |
| exact_length[] | Fails if the field does not have the exact same length specified inside the brackets. | exact_length[8] |
| alpha | Fails if the field contains anything other than alphabetical characters. | |
| alpha_numeric | Fails if the field contains anything other than alpha-numeric characters. | |
| alpha_dash | Fails if the field contains anything other than alpha-numeric characters, underscores and dashes. | |
| numeric | Fails if the field is not a valid number. | |
| integer | Fails if the field is not a valid integer. |
Adding / removing validation rules for existing fields
If you want to add / remove validation rules of a pre-defined field, use the following two methods:
$form->addRule( $fieldName, $rules ); $form->removeRule( $fieldName, $rules );
Replace $fieldName with the name of the field you want to modify, $rules with a comma-delimited list of rules (or an array of rules).
Changing validation error messages
If you happen to dislike the default error messages, changing them is a piece of cake:
$form->setMessage( $rule, $message );
For example:
$form->setMessage( 'required', 'Please don't leave the %s field blank.' ); $form->setMessage( 'exact_length', 'The %s field requires exactly %s letters.' );
Notice that in the $message string, the first %s represents the label (title) of the fields. If there is a second %s, it will be replaced automatically with the value in the brackets of the rules.
Advanced form configuration
This section is useful for PHP developers who want to modify and extend the default behavior of a form instance. Read on if you're confident with your PHP skills.
Customizing HTML mark-up
There are cases where the default HTML mark-up that PalmsForm outputs is not enough for you. Sometimes you need to wrap the error messages within a <div> instead of a <ol>, or add a custom class to the error messages. Below you can find the anatomy of a PalmsForm field, and how to change the mark-up.
Anatomy of a form field
{field_before}
<label for="xx">abc</label>
<input type = ....>
{field_after}
Anatomy of a error messages div
{error_div_before}
{error_div_title_before}
Cannot process your form due to the following errors:
{error_div_title_after}
{error_list_before}
{error_before}
Error Message
{error_after}
{error_before}
Error Message
{error_after}
{error_before}
Error Message
{error_after}
....
{error_list_after}
{error_div_after}
The curly braces with text inside can be considered template tags, and you can modify these template tags by using the following method:
$form->setting( $templateTag, $newValue );
Examples:
Wrap the form fields using <p> instead of <div>:
$form->setting( 'field_before', '<p id="%s" class="%s">' ); $form->setting( 'field_after', '</p>' );
The placeholders (%s) will automatically be replaced with id and class of that element.
Another example, display error list as a <div>, and individual error message inside a <p>
$form->setting( 'error_list_before', '<div>' ); $form->setting( 'error_list_after', '</div>' ); $form->setting( 'error_before', '<p>' ); $form->setting( 'error_after', '</p>' );
Modifying existing form fields
There are a couple of more methods that could help you alter the properties of a certain pre-defined field.
To override a set of properties of a field:
$form->overrideField( $name, $properties );
For example, to change the default property of the Email field:
$form->overrideField( 'email', array( 'default' => 'Enter your email' ) );
To remove a pre-defined property of a field:
$form->removeProperty( $name, $propertyName );
For example, to remove the size and maxlength properties of the "Name" field:
$form->removeProperty( 'name', 'size' ); $form->removeProperty( 'name', 'maxlength' );
Extending default behavior
PalmsForm is developed using OOP principles, therefore it allows you to easily extend the core functionality of the library to suit your needs.
Defining a custom form other than contact form
It is possible for you to use PalmsForm to build forms other than for contacting purposes. All you have to do is pass an array of form fields into the constructor method. The form fields are defined as pairs of values, one is the field name, the other is the field property array.
For example, to display a log in form:
$loginFields = array( 'username' => array( 'type' => 'text', 'label' => 'Username', 'rules' => 'required, alpha_dash', ), 'password' => array( 'type' => 'password', 'label' => 'Password', 'rules' => 'required', ), 'submit' => array( 'type' => 'submit', 'label' => 'Log in', ), ); $loginForm = new PalmsForm( $loginFields ); $loginForm->show();
Custom validation rules
Sometimes you might want to use validation rules other than the native ones. It is possible to do that by creating a form class of your own that inherits PalmsForm, then add validation callbacks and define error messages for your custom validation rules.
For example, adding custom validation rules named 'zip' to validate zip codes:
require_once( '../palmsform.php' );
class MyForm extends PalmsForm
{
// instantiates a contact form in case no arguments are passed to the constructor
function __construct( $setting = 'contact' ) {
// calls PalmsForm constructor
parent::__construct( $setting );
// defines the error message for our new "zip" rule
$this->messages['zip'] = 'The %s field must contain a valid zip code.';
}
// defines the callback function that validates a field with "zip" rule
// the callback function name must be in the form of: callback_validate_{your new rule's name}
// replace {your new rule's name} with your actual new rule's name, in this case "zip"
function callback_validate_zip( $fieldName ) {
// returns true if valid, returns false if invalid
if( preg_match( "/^([0-9]{5})(-[0-9]{4})?$/i", $_POST[$fieldName] ) )
return true;
else
return false;
}
}
$myForm = new MyForm();
Creating reusable customized forms
You can inherit and create as many custom classes based on PalmsForm as you want. This comes in handy especially when you want to use PalmsForm with customized settings (custom template tags or validation rules) for various kinds of form in your web site or application.
All you have to do is create a separate file to contain your new class, and extend PalmsForm:
require_once( '../palmsform.php' );
class MyForm extends PalmsForm
{
// instantiates a contact form in case no arguments are passed to the constructor
function __construct( $setting = 'contact' ) {
// calls PalmsForm constructor
parent::__construct( $setting );
// customizes settings here, for example:
$this->setting( 'error_list_before', '<div>' );
$this->setting( 'error_list_after', '</div>' );
$this->setting( 'error_before', '<p>' );
$this->setting( 'error_after', '</p>' );
}
// from here on, defines your own methods, or validation rules etc.
}
By doing this, you can avoid having to make the same customization over and over again for each kind of form you need.