Asier
Asier

Reputation: 11

Symfony dynamic forms

I started with a form, which is made by hand because of it's complexity (it's a javascript modified form, with sortable parts, etc). The problem is that now I need to do the validation, and it's a total mess to do it from scratch in the action using the sfValidator* classes.

So, I am thinking to do it using sfForm so that my form validation and error handling can be done more easier and so I can reuse this form for the Edit and Create pages.

The form is something like this:

<form>
  <input name="form[year]"/>
  <textarea name="form[description]"></textarea>
  <div class="sortable">
    <div class="item">
      <input name="form[items][0][name]"/>
      <input name="form[items][0][age]"/>
    </div>
    <div class="item">
      <input name="form[items][1][name]"/>
      <input name="form[items][1][age]"/>
    </div>
  </div>
</form>

The thing is that the sortable part of the form can be expanded from 2 to N elements on the client side. So that it has variable items quantity which can be reordered.

How can I approach this problem?

Any ideas are welcome,
thank you. :)

Upvotes: 1

Views: 980

Answers (1)

gruner
gruner

Reputation: 1570

I'm doing something similar using embedded forms for the repeating fields.

In your form class you could do something like:

$form_data = $this->getObject();

if (isset($form_data['items']) && is_array($form_data['items']))
{
  $items_form = new BaseForm();

  foreach ($form_data['items'] as $count => $values)
  {
    $form = new BaseForm();
    $form->widgetSchema['name'] = new sfWidgetFormInputText();
    $form->widgetSchema['age'] = new sfWidgetFormInputText();

    $items_form->embedForm($count, $form);
  }

  $this->embedForm('items', $items_form);
  $this->validatorSchema['items'] = new sfValidatorPass(array('required' => false));
}

Upvotes: 2

Related Questions