Creating an Ajax update-only form using the default validators

The new form system is very powerful and decoupled. It means that the form creation code and the validation code can be used independently.

Here is the default generated code for an update action :

public function executeUpdate($request)
{
  …
  $this->form = new ProductForm(productPeer::retrieveByPk($request->getParameter(‘id‘)));
  $this->form->bind($request->getParameter(‘product‘));
  if ($this->form->isValid())
  {
    …
  }
}

The action automatically binds the product request parameter which correspond to a entire product form.

What if you want to make a simple form for update purpose only ? Like an Ajax simple edit-and-save for one field ?

By default, if you don’t pass all the required fields explicitly, the form will not be valid.

According to the book, you can unset some fields from the from to bypass validation and save:

class ProductForm extends BaseProductForm
{
  public function configure()
  {
    unset($this['created_at']);
  }
}

Let’s create a custom product form for a simple Ajax edit-and-update. As we only want one field to be validate and saved, we have to unset all fields, except the ones we want:

in /lib/form/ProductFormAjax.class.php :

class ProductFormAjax extends BaseProductForm
{
  // Create the form only for these fields
  protected $enabled_fields = array(‘id‘, ‘name‘);
  public function configure()
  {
    foreach($this->getWidgetSchema()->getFields() as $name => $field)
    {
      if (!in_array($name, $this->enabled_fields))
      {
        unset($this[$name]);
      }
    }
  }
}

You now have a simplified update-only form that uses the same field validators defined in your /lib/form/base/BaseProductForm.class.php.

Now, in the actions class, you can choose between the default form and yours depending upon the context :

class ProductActions extends sfActions
{
  public function executeUpdate($request)
  {
    …
    if ($request->isXmlHttpRequest())
    {
      $this->form = new InstallatorFormAjax(
InstallatorPeer::retrieveByPk($request->getParameter(‘id‘)));
    }
    else
    {
      $this->form = new InstallatorForm(
InstallatorPeer::retrieveByPk($request->getParameter(‘id‘)));
    }
    …
  }
  …
  public function executeEditAjax()
  {
    $this->form = new ProductFormAjax(
InstallatorPeer::retrieveByPk($request->getParameter(‘id‘)));
  }
}
Advertisements



    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s



%d bloggers like this: