Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add some extra data to a symfony 2 form

I have a form for my entity called Book and I have a type to display a form in my view. In this type I have some fields that are mapped to properties in my entity.

Now I want to add another field which is not mapped in my entity and supply some initial data for that field during form creation.

My Type looks like this

// 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 like this

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

How can I supply some initial data now during form creation? Or how do I have to change that creation of the form to add initial data to the another_field field?

like image 389
Benjamin Paap Avatar asked Jan 08 '13 20:01

Benjamin Paap


3 Answers

I also have a form that has fields that mostly match a previously defined entity, but one of the form fields has mapped set to false.

To get around this in the controller, you can give it some initial data pretty easily like this:

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

simple as that. Then when you're processing the form data to get ready to save it, you can access the non-mapped data with:

$form->get('nonMappedField')->getData();
like image 177
targnation Avatar answered Nov 19 '22 12:11

targnation


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

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 construct:

$this->createForm(new BookType('blahblah'), $book);
like image 37
Mike Avatar answered Nov 19 '22 12:11

Mike


You can change the request parameters like this to support the 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 at rendering. If you want to supply many fields this may be an option.

like image 2
Benjamin Paap Avatar answered Nov 19 '22 13:11

Benjamin Paap