symfony2:在表单外部、控制器动作内部设置表单字段的值 [英] symfony2: setting the value of a form field outside the form, inside a controller action
问题描述
我需要设置一个 symfony2 表单元素的值.我在我的 Controllers Action 中使用了一个 dotric2 实体、一个 SymfonyComponentFormAbstractType 和 createForm() 方法.
I need to set the value of a symfony2 form element. I use a doctrine2 entity, a SymfonyComponentFormAbstractType 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');
仅供参考:我需要这样做才能正确呈现该字段(使用 这种方法,我的 image 字段始终为空,我需要将其设置为 imagePath 的内容以显示上传图像的预览)
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)
推荐答案
要获得更准确的答案,您应该在此表单中包含您使用的实体,以便我们可以看到 getter 和 setter.但根据您的问题,这应该可行:在控制器内部这样做:
$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());
要获取数据,请使用:
$saleDataForm->getData()->getImage()->getValue();
这篇关于symfony2:在表单外部、控制器动作内部设置表单字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!