symfony plugins Symfony Plugins Using symfony forms before 1.1

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.

Share the love!

Liked this article? Please consider sharing it on your favorite network, it really helps me a lot!

You can also add your valuable insights by commenting below.