简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM