Elorfin
Elorfin

Reputation: 2497

symfony : Form with one parameter

I have a form, and I want to pass it one parameter which must use to fill a widget.

I pass the parameter in my url :

url_for('myModule/new?parameter='.$myParam)

I have tried to take the parameter in my action and display it in my tamplate, but it doesn't work.

Action :

$this->param = $request->getParameter('parameter');

Template :

echo param;

But I can't recover it in my form.

How can I do this ?

Upvotes: 1

Views: 4003

Answers (4)

Elorfin
Elorfin

Reputation: 2497

If the parameter is an attribute of the object, you can do :

$object = new Class();
$object->setAttribute($request->getParameter('myParam'));

$form = new ClassForm($object);

Upvotes: 0

lunohodov
lunohodov

Reputation: 5399

If this parameter is needed for initializing your form then you could do it like this (keep in mind that you should always validate user input)

  public function executeNew($request)
  {
    $formOptions = array('parameter' => $request->getParameter('parameter'));
    $this->form = new MyForm(array(), $formOptions);
    // Then within your form you access it with:
    // $parameter = $this->options['parameter'];
    // or even better:
    // $parameter = $this->getOption('parameter');
    ... more code ...
  }

If the parameter is submitted as part of the form then you should bind it like this:

  public function executeNew($request)
  {
    $this->form = new MyForm();
    if ( $request->isMethod('post') ) {
      $this->form->bind($request->getPostParameters());
    }
    ... more code ...
  }

Please refer to the Symfony's Forms in Action for more on how to create and use forms.

Edit: Added $this->getOption('parameter') to the code example.

Upvotes: 5

Maerlyn
Maerlyn

Reputation: 34107

You need to pass it to the form constructor, both the constructors of sfForm and sf{Propel,Doctrine}Form take a parameter called $options, use that. Store the value in a private property, so you can use in in the form's configure method.

Upvotes: 0

funkdoobiest
funkdoobiest

Reputation: 37

you have to define a route for this URL in your routing.yml and add your parameter to this route.

for example:

mymoduel_new:
   url:    myModule/new/:paramter/
   param:  { module: myModule, action: new }

Upvotes: 0

Related Questions