there are two things here, one is the Forms Builder (here we can re-use Phalcon\Tag to create the elements), the objectives of this component are:
- Create forms in a more structured way
- Apply validations to the entire form
- Get and display validation messages on forms easily
So its basic usage can be:
class PostsController extends \Phalcon\Mvc\Controller
{
protected function getForm()
{
return $this->forms->createBuilder()
->setAction('posts/save')
->add('login', 'text')
->add('password', 'password')
->getForm();
}
public function createAction()
{
$this->view->setVar('form', $this->getForm());
}
Then in the view:
<!-- this will produce the whole form -->
<?php echo $form->render(); ?>
Or creating it with more free:
<form method="post" action="<?php echo $form->getAction() ?>">
<label for="login">Login</label> <?php echo $form->render("login"); ?>
<label for="password">Password</label> <?php echo $form->render("password"); ?>
<input type="submit" value="Send"/>
The save action receives the form data to perform the validation:
class SessionController extends \Phalcon\Mvc\Controller
{
protected function getForm()
{
return $this->forms->createBuilder()
->setAction('posts/save')
->add('login', 'text')
->add('password', 'password')
->getForm();
}
public function createAction()
{
$this->view->setVar('form', $this->getForm());
}
public function saveAction()
{
$form = $this->getForm();
//All fields are filled?
if ($form->isValid($_POST) {
$user = Users::findFirst(array(
'login = ?0',
'bind' => array($form->get('login'))
));
if ($user) {
if ($this->security->checkHash($form->get('password'), $user->password) {
$this->flash->success('Welcome ' . $user->name);
return $this->dispatcher->forward(
array('controller' => 'index')
);
}
}
}
$this->view->setVar('form', $form);
}
}
Let's pretend the validation has failed (in the view):
<!-- Get all the messages -->
if ($form->hasMessages()) {
echo '<div class="messages">', $forms->messages(), '</div>';
}
<!-- Get messages for a field -->
<p>
<label for="login">Login</label> <?php echo $form->render("login"); ?>
<?php echo $form->messagesFor('login') ?>
</p>
The validator component is implicitly built inside the forms builder, also filters can be applied too:
protected function getForm()
{
return $this->forms->createBuilder()
->setAction('posts/save')
->add('login', 'text', array(
'label' => 'Le Login',
'validators' => array(
'MyApp\Validatiors\\Length' => array(
'minimum' => 8,
'message' => 'The login is not valid'
)
),
'filters' => array( //For Phalcon\Filter
'alphanum'
),
'attributes' => array( // For Phalcon\Tag::textField
'size' => 40,
'class' => 'input-btn'
)
))
->add('password', 'password', array(
'label' => 'Le Password',
'attributes' => array(
'size' => 40,
'class' => 'input-btn'
)
))
->getForm();
}