symfony2:在控件动作内设置表单外的表单域的值 [英] symfony2: setting the value of a form field outside the form, inside a controller action

查看:109
本文介绍了symfony2:在控件动作内设置表单外的表单域的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设置一个symfony2表单元素的值。
我使用一个doctrine2实体,一个 Symfony\Component\Form\AbstractType 和我的Controllers Action中的createForm()方法。



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

现在,我如何从该表单中获取元素,我如何设置它的价值?
我想做这样的事情,但它不起作用:

  $ saleDataForm-> get '图像') - >的setValue( 'someimapge.jpg'); 

FYI:我需要这样做来正确渲染字段(使用这种方法,我的图像字段始终为空,我需要设置它

解决方案

对于 imagePath 的内容,以呈现上传的图像的预览)一个更准确的答案应该包括你在这个表单中使用的实体,所以我们可以看到getter和setter。但是根据你的问题,这应该是有效的:
控制器内部执行以下操作:

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

这是如果表单已经创建了:



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

要获取数据,请使用:

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


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)

解决方案

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();

这篇关于symfony2:在控件动作内设置表单外的表单域的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆