symfony : Form with one parameter

∥☆過路亽.° 提交于 2019-12-08 08:03:59

问题


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 ?


回答1:


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.




回答2:


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 }



回答3:


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.




回答4:


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

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

$form = new ClassForm($object);


来源:https://stackoverflow.com/questions/3492727/symfony-form-with-one-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!