views:

107

answers:

2

I am using Symfony 1.4 to create project, and i need to create dynamic forms depending upon the question set type coming from database. i have used Symfony forms in rest of my project, but in this case using symfony forms seems to be tough, as i need dynamic form. can it be safe to use normal HTML forms..in symfony project, or it is advisable to use Symfony forms. so need your help.

+1  A: 

You can use html forms, but it would bypass symfony's form validation system.

You can still build dynamic forms by creating and adding input widgets to the current form, or a new form inside an action. You can then echo the form in the template and the dynamically generated fields will be part of the form as well.

If you start with a MyForm.class.php in the lib/forms, make sure to add:

$this->validatorSchema->setOption('allow_extra_fields', true);

Otherwise, you will automatically get validation errors. If you want to add fields to a form in an action you would do something like this:

$this->form = new MyForm();
$widgetSchema = $this->form->getWidgetSchema();
$widgetSchema['add_field'] = new sfWidgetFormInputText();

When you echo your form the 'add_field' input will be added to it.

Jestep
@Jestep i will try this, because i want to add HTML elements at runtime and with out loosing Symfony form validation system..
Harish Kurup
+1  A: 

It would help to have more information about what you're doing, but here's one way in which forms can be dynamic in Symfony. This code creates widgets and validators for a survey dynamically based on the "type" of a question:

class SurveyAnswerForm extends BaseSurveyAnswerForm
{
  public function configure()
  {
    $question = $this->object->Question;

    $method = sprintf('createWidgetAndValidatorFor%sInputType', $question->type);
    $this->$method($question);
    $this->getWidget('value')->setOption('label', $question->question);
    $this->getValidator('value')->setOption('required', $question->required);
  }

  protected function createWidgetAndValidatorForTextFieldInputType(Question $question)
  {
    $this->setWidget('value', new sfWidgetFormInputText());
    $this->setValidator('value', new sfValidatorString());
  }

  protected function createWidgetAndValidatorForTextAreaInputType(Question $question)
  {
    $this->setWidget('value', new wfWidgetFormTextareaAutosize());
    $this->setValidator('value', new sfValidatorString());
  }

  //etc. for as many types as you require
}

Note: while this answer is code from one of my projects, it was heavily influenced by this answer over on SymfonyExperts.

jeremy