Project Versions

Table Of Contents

Previous topic

Validation

Next topic

Reading Configurations

This Page

Forms

Phalcon\Forms is a component aids the developer in the creation and maintenance of forms in web applications.

The following example shows its basic usage:

<?php

use Phalcon\Forms\Form,
        Phalcon\Forms\Element\Text,
        Phalcon\Forms\Element\Select;

$form = new Form();

$form->add(new Text("name"));

$form->add(new Text("telephone"));

$form->add(new Select("telephoneType", array(
        'H' => 'Home',
        'C' => 'Cell'
)));

Forms can be rendered based on the form definition:

<h1>Contacts</h1>

<form method="post">

        <p>
                <label>Name</label>
                <?php echo $form->render("name") ?>
        </p>

        <p>
                <label>Telephone</label>
                <?php echo $form->render("telephone") ?>
        </p>

        <p>
                <label>Type</label>
                <?php echo $form->render("telephoneType") ?>
        </p>

        <p>
                <input type="submit" value="Save" />
        </p>

</form>

Each element in the form can be rendered as required by the developer. Internally, Phalcon\Tag is used to produce the right HTML for each element, you can pass additional html attributes as second parameter for render:

<p>
        <label>Name</label>
        <?php echo $form->render("name", array('maxlength' => 30, 'placeholder' => 'Type your name')) ?>
</p>

HTML Attributes also can be set in the element’s definition:

<?php

$form->add(new Text("name", array(
        'maxlength' => 30,
        'placeholder' => 'Type your name'
)));

Initializing forms

As seen before, forms can be initialized outside the form class by adding elements to it. You can re-use code or organize your form classes implementing the form in a separated file:

<?php

use Phalcon\Forms\Form,
        Phalcon\Forms\Element\Text,
        Phalcon\Forms\Element\Select;

class ContactsForm extends Form
{
        public function initialize()
        {
                $this->add(new Text("name"));

                $this->add(new Text("telephone"));

                $this->add(new Select("telephoneType", TelephoneTypes::find(), array(
                        'using' => array('id', 'name')
                )));
        }
}

Validation

Phalcon forms are integrated with the validation component to offer instant validation. Built-in or custom validators could be set to each element:

<?php

use Phalcon\Forms\Element\Text,
        Phalcon\Validation\Validator\PresenceOf,
        Phalcon\Validation\Validator\StringLength;

$name = new Text("name");

$name->addValidator(new PresenceOf(array(
        'message' => 'The name is required'
)));

$name->addValidator(new StringLength(array(
        'min' => 10,
        'messageMinimum' => 'The name is too short'
)));

$form->add($name);

Then you can validate the form according to the input entered by the user:

<?php

if (!$form->isValid($_POST)) {
        foreach ($form->getMessages() as $message) {
                echo $message, '<br>';
        }
}

Validators are executed in the same order as they were registered.

By default messages generated by all the elements in the form are joined so they can be traversed using a single foreach, you can change this behavior to get the messages separated by the field:

<?php

foreach ($form->getMessages(false) as $attribute => $messages) {
        echo 'Messages generated by ', $attribute, ':', "\n";
        foreach ($messages as $message) {
                echo $message, '<br>;
        }
}

Or get specific messages for an element:

<?php

foreach ($form->getMessagesFor('name') as $message) {
        echo $message, '<br>;
}

Forms + Entities

An entity such as a model/collection instance or just a plain PHP class can be linked to the form in order to set default values in the form’s elements or assign the values from the form to the entity easily:

<?php

$robot = Robots::findFirst();

$form = new Form($robot);

$form->add(new Text("name"));

$form->add(new Text("year"));

Once the form is rendered if there is no default values assigned to the elements it will use the ones provided by the entiy:

<?php echo $form->render('name') ?>

You can validate the form and assign the values from the user input in the following way:

<?php

$form->bind($_POST, $robot);

//Check if the form is valid
if ($form->isValid()) {

        //Save the entity
        $robot->save();
}

Form Elements

Phalcon provides a set of built-in elements to use in your forms:

Name Description Example
Text Generate INPUT[type=text] elements Example
Password Generate INPUT[type=password] elements Example
Select Generate SELECT tag (combo lists) elements based on choices Example
Check Generate INPUT[type=check] elements Example
Textarea Generate TEXTAREA elements Example

Rendering Forms

You can render the form with total flexibility, the following example shows how to render each element using an standard procedure:

<?php

<form method="post">
        <?php
                //Traverse the form
                foreach ($form as $element) {

                        //Get any generated messages for the current element
                        $messages = $form->getMessagesFor($element->getName());

                        if (count($messages)) {
                                //Print each element
                                echo '<div class="messages">';
                                foreach ($messages as $message) {
                                        echo $message;
                                }
                                echo '</div>';
                        }

                        echo '<p>';
                        echo '<label for="', $element->getName(), '">', $element->getLabel(), '</label>';
                        echo $element;
                        echo '</p>';

                }
        ?>
        <input type="submit" value="Send"/>
</form>

Or reuse the logic in your form class:

<?php

class ContactForm extends Phalcon\Forms\Form
{
        public function initialize()
        {
                //...
        }

        public function renderDecorated($name)
        {
                $element = $this->get($name);

                //Get any generated messages for the current element
                $messages = $this->getMessagesFor($element->getName());

                if (count($messages)) {
                        //Print each element
                        echo '<div class="messages">';
                        foreach ($messages as $message) {
                                echo $message;
                        }
                        echo '</div>';
                }

                echo '<p>';
                echo '<label for="', $element->getName(), '">', $element->getLabel(), '</label>';
                echo $element;
                echo '</p>';
        }

}

Creating Form Elements

In addition to the form elements provided by Phalcon you can create your own custom elements:

<?php

class MyElement extends Phalcon\Forms\Element
{
        public function render($attributes=null)
        {
                $html = //... produce some html
                return $html;
        }
}