Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 773
Andresch Serj Avatar asked Nov 06 '12 10:11

Andresch Serj


2 Answers

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();
like image 92
Mats Rietdijk Avatar answered Sep 24 '22 02:09

Mats Rietdijk


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());
like image 32
Tomáš Tibenský Avatar answered Sep 26 '22 02:09

Tomáš Tibenský