Using symfony forms before 1.1

By Romain Dorgueil
Outdated Content
This article is preserved for historical purposes and does not reflect current practices or technologies.

The new symfony 1.1 form/validation framework is 100% symfony-independant, and though is not limited to the (very) awaited 1.1 stable release. To use it in your own symfony 1.0 projects, you can use sfForms11Plugin. It’s content is very thin: it only sets up externals to symfony 1.1 form/widget/validator libraries.

To use it, simply add the following external to your project:

sfForms11Plugin http://svn.symfony-project.com/plugins/sfForms11Plugin

Or check it out from your project base directory:

svn co http://svn.symfony-project.com/plugins/sfForms11Plugin plugins/sfForms11Plugin

Let’s try it…

Now you’ll be able to define sfForm sub-classes to materialize forms:

<?php
class HelloWorldForm extends sfForm
{
  public function configure()
  {
  }

  public function setup()
  {
    $this->setWidgetSchema(new sfWidgetFormSchema(array(
            'name' => new sfWidgetFormInput(),
            )));

    $this->setValidatorSchema(new sfValidatorSchema(array(
            'name' => new sfValidatorString(array('required'=>true, 'min_length'=>1, 'max_length'=>50)),
            )));

    $this->widgetSchema->setNameFormat('hello[%s]');
    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    parent::setup();
  }
}

This class define the model of your HelloWorldForm, and you can now use it in your actions:

<?php
class testActions extends sfActions
{
  function executeHelloWorld()
  {
    $this->form = new HelloWorldForm();

    if ($this->getRequest()->getMethod() == sfRequest::POST)
    {
      if (null !== ($hello = $this->getRequestParameter('hello', null)))
      {
        $this->form->bind($hello);

        if ($this->form->isValid())
        {
          $this->redirect('@hello?name='.$this->form->getValue('name'));
        }
      }
    }
  }
}

At this point, the only little detail still missing is the view:

<form method="POST">
<table>
<?php echo $form; ?>
<tr>
  <td colspan="2" align="right">
    <input type="submit" value="Greetings, Mr Computer!" />
  </td>
</tr>
</table>
</form>

That’s it! You now have a simple form, self-validating, protected against CSRF attacks and redirecting to some place if values entered matched our sfValidatorSchema.