How to add some extra data to a symfony 2 form

I have a form for my object called Book , and I have a type to display the form in my view. In this type, I have some fields that appear in the properties of my object.

Now I want to add another field that does not appear in my entity, and provide some source data for this field during the creation of the form.

My type is as follows

 // BookBundle\Type\Book public function buildForm(FormBuilderInterface $builder, array $options = null) { $builder->add('title'); $builder->add('another_field', null, array( 'mapped' => false )); } 

The form is created as follows

 $book = $repository->find(1); $form = $this->createForm(new BookType(), $book); 

How can I provide some source data now during form creation? Or how can I change this form creation to add the source data to another_field ?

+8
php forms symfony entity
source share
3 answers

I also have a form in which there are fields that basically correspond to a previously defined object, but one of the form fields is set to false.

To get around this in the controller, you can easily get some raw data as follows:

 $product = new Product(); // or load with Doctrine/Propel $initialData = "John Doe, this field is not actually mapped to Product"; $form = $this->createForm(new ProductType(), $product); $form->get('nonMappedField')->setData($initialData); 

just. Then, when you process the form data to prepare to save it, you can access the non-displayable data with:

 $form->get('nonMappedField')->getData(); 
+29
source share

One suggestion might be to add a constructor argument (or setter) to your BookType type that includes the "another_field" data, and the data parameter in the add arguments:

 class BookType { private $anotherFieldValue; public function __construct($anotherFieldValue) { $this->anotherFieldValue = $anotherFieldValue; } public function buildForm(FormBuilderInterface $builder, array $options = null) { $builder->add('another_field', 'hidden', array( 'property_path' => false, 'data' => $this->anotherFieldValue )); } } 

Then build:

 $this->createForm(new BookType('blahblah'), $book); 
+5
source share

You can change request parameters like this to support a form with additional data:

 $type = new BookType(); $data = $this->getRequest()->request->get($type->getName()); $data = array_merge($data, array( 'additional_field' => 'value' )); $this->getRequest()->request->set($type->getName(), $data); 

This way, your form will fill in the correct values ​​for your field when rendering. If you want to provide many fields, this may be an option.

+2
source share

All Articles