symfony2: setting the value of a form field outside the form, inside a controller action

蹲街弑〆低调 提交于 2020-01-10 08:59:13

问题


I need to set the value of a symfony2 form element. I use a doctrine2 entity, a Symfony\Component\Form\AbstractType and the createForm() method inside my Controllers Action.

$saleDataForm = $this->createForm(new SaleType(), $sale);

Now, how do i get an element from that form, and how can i set it's value? I want to do something like this, but it doesn't work:

$saleDataForm->get('image')->setValue('someimapge.jpg');

FYI: I need to do this to render the field correctly (using this approach, my image field is always empty and i need to set it to the content of imagePath to present a preview of an uploaded image)


回答1:


For a more exact answer you should include the entities you use in this form so we can see the getters and setters. But based on your question this should work: Inside the controller do this:

$saleDataForm->getData()->getImage()->setValue('someimage.jpg');
$form->setData($form->getData());

This is if the form is already created so:

$saleDataForm = $this->createForm(new SaleType(), $sale);
$saleDataForm->getData()->getImage()->setValue('someimage.jpg');
$form->setData($form->getData());

To get the data use this:

$saleDataForm->getData()->getImage()->getValue();



回答2:


thanks MatsRietdijk, you helped me, but I had to change code to this

$form = $this->createForm(new SaleType(), $sale);
$form->getData()->setImage('someimage.jpg');
$form->setData($form->getData());



回答3:


If you try fill file upload field - it's wrong idea. Ask yourself: what data should be there? If an user upload an image, then in this field will be a path to the image on his local system. But then after file is uploaded you change its name and location, so you don't need info about this path and you just don't keep it.

The appropriate way should be left empty upload field below (or above, or wherever you have it ;) ) image. Then after form is submitted and if the field is not empty you should change edited image.



来源:https://stackoverflow.com/questions/13249485/symfony2-setting-the-value-of-a-form-field-outside-the-form-inside-a-controlle

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