The Form Object
Staple includes a built in form building framework.
Create a Form
You can make a new Form object with either the new keyword or the create() factory method.
$form = new Form();
$form2 = Form::create();
The constructor and factory method accepts parameters for name, action and method.
$form = Form::create('MyForm', 'go/to/page/', 'POST');
Set the Form Name
$form->setName('MyForm');
By adding a form name an ident field is automatically added to the Form object. This ident field
acts as a CSRF hash to prevent CSRF attacks against the form.
The CSRF hash can be disabled by calling the disableIdentifier() method on the Form object.
Set Form Action
$form->setAction('/go/to/page');
Set Form Method
$form->setMethod('POST');
Adding Fields
Forms require fields before they can function. You can add field objects to the Form object with the
addField(FieldElement $field1, $field2, field3....) method. All fields must be implementations of the
FieldElement object. Many fields are built in, but custom FieldElement objects could be created as
well.
This example adds a TextElement object to the Form object.
$form = Form::create('MyForm');
$textField = TextElement::create('first_name', 'First Name');
$form->addField($textField);
Fields can also be added dynamically by setting a dynamic property on the form object:
$form->first_name = TextElement::create('first_name', 'First Name');
Derived Forms
Deriving from the Form object also has many benefits. You can create a form and initialize all of the
elements within your derived object. Derived forms live in the /application/forms folder by default and
the derived objects must in with the word Form for the autoloader to pick them up.
Extend from Form, name the form MyForm and attach a TextElement upon creation.
use Staple\Form\Form;
class MyForm extends Form
{
//The Form startup method
public function _start()
{
$this->setName('MyForm');
TextElement::create('first_name', 'First Name')
->addToForm($this);
}
}