Submit multiple entities in a single form

Showing 1-7 of 7 messages
Submit multiple entities in a single form lifo 2/16/12 12:49 PM
I'm trying to figure out how to submit multiple entities in a single
form. And I don't mean embedding multiple different types into a form.
I'm trying to make a form where I can submit multiple items and then
persist each to the database. I can try to go into more detail but I
don't want to confuse the question right now.

To clarify one thing, I've been able to add a "collection" of items to
one of my other forms that allows me to edit a single item and any of
the items in the related collection but for the life of me I can't get
Symfony to just allow me to have a global form that is a collection of
items in itself.
Re: [Symfony2] Submit multiple entities in a single form Tarjei Huse 2/16/12 11:41 PM

Have you tried creating a form where each item has it's own subtype but
where the parent form does not?

Something like:

$builder->add("person", new PersonType())->add("dog", new DogType());

I think you might need some fidling with the form options as well - or
create a parent object with getters and setters for person and dog.

Tarjei
>

Re: [Symfony2] Submit multiple entities in a single form lifo 2/21/12 3:32 AM
I don't think that would work because my form will be dynamic and the user may add any number of entries in the form (via javascript) before submitting.


Re: Submit multiple entities in a single form lifo 2/22/12 3:31 AM
I finally figured this out with some trial and error and it turned out to be quite easy. For anyone else who might have a similar question I'll outline what I did here.

My controller looks something like this (removed extraneous code):

    /**
     * @Route("/receive/item", name="receive_item")
     * @Template()
     */
    public function receiveInventoryItemAction(Request $request)
    {
        $items = new InventoryItems();
        $form = $this->createFormBuilder($items)
            ->add('items', 'collection', array(
                'required' => false,
                'allow_add' => true,
                'prototype' => true,
                'type' => new InventoryItemReceiveType(),
            ))
            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
           
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getEntityManager();
                foreach ($items->getItems() as $item) {
                    $em->persist($item);
                }
                $em->flush();
            }
        }
        return array(
            'items' => $items,
            'form'    => $form->createView()
        );
    }

The InventoryItems object is a dummy entity that is not persisted directly and only contains a couple of getter/setters to maintain the list of $items.

The InventoryItemReceiveType form object is just like any other form type object that defines which fields I want in the form.

My view has the normal form fields in it that you would expect and the following:

    <input id="prototype" type="hidden" value="{{ form_row(form.items.get('prototype'))|e }}" />
    {% for item in form.items %}
        <div class="row">{{ form_widget(item) }}</div>
    {% endfor %}

There's javascript in the view that allows me to add/remove new rows by injecting the content from the prototype.
Re: Submit multiple entities in a single form Brad Saverino 9/26/13 12:41 PM
I am trying to get this to work right now.  When you ->add('items', 'collection'

What is 'items'?  Would you mind showing what InventroyItems looks like.  I can't seem to get this to work for the life of me!  I know that this was posted some time ago but any help is appreciated! 
Re: [Symfony2] Re: Submit multiple entities in a single form Bernhard Schussek 9/27/13 1:30 AM
One easy way for creating a form with two separate entities is to add them as embedded forms to an array-based form:

$form = $this->createFormBuilder()
    ->add('foo', 'foo_type', array(
        'data_class' => 'Foo',
    )
    ->add('bar', 'bar_type', array(
        'data_class' => 'Bar',
    )
    ->getForm();

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $foo = $form->get('foo')->getData();
    $bar = $form->get('bar')->getData();

    // do stuff
}

Cheers,
Bernhard

--
Bernhard Schussek
Blog: http://webmozarts.com
Twitter: http://twitter.com/webmozart


2013/9/26 Bradley Saverino <bsav...@gmail.com>
--
--
If you want to report a vulnerability issue on Symfony, please read the procedure on http://symfony.com/security

 
You received this message because you are subscribed to the Google
Groups "Symfony2" group.
To post to this group, send email to symf...@googlegroups.com
To unsubscribe from this group, send email to
symfony2+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/symfony2?hl=en
---
You received this message because you are subscribed to the Google Groups "Symfony2" group.
To unsubscribe from this group and stop receiving emails from it, send an email to symfony2+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Re: [Symfony2] Re: Submit multiple entities in a single form Elvis McNeely 4/20/15 6:01 AM
Thank you for this example. I am new to symfony and this was a big help, I didn't want to go the form embedding / collection route.

I successfully implemented your example and in the process discovered how brilliant symfony is at mapping data properly. Here is my working example using symfony 2.6:


<?php

        // Inside your customAction...

        $em = $this->getDoctrine()->getManager();

        $user = $this->get('security.token_storage')->getToken()->getUser();
        $uid = $user->getUserid();

        if ($uid) {
            $consultant = $em->getRepository('CompanyBundle:Consultant')->findOneBy(array('userid' => $uid));
            if ($consultant) {
                $billingAddressId = $consultant->getBillingaddressid();
                if($billingAddressId) {
                    $billingAddress = $em->getRepository('CompanyBundle:Address')->find($billingAddressId);
                }
                $shippingAddressId = $consultant->getShippingaddressid();
                if($shippingAddressId) {
                    $shippingAddress = $em->getRepository('CompanyBundle:Address')->find($shippingAddressId);
                }
            }
        }

        $data = array('billingAddress' => $billingAddress, 'shippingAddress' => $shippingAddress);

        $form = $this->createFormBuilder($data)
            ->add('billingAddress', new AddressType(), array(
                'data_class' => 'Acme\Entities\CompanyBundle\Entity\Address', // Where we store our entities
            ))
            ->add('shippingAddress', new AddressType(), array(
                'data_class' => 'Acme\Entities\CompanyBundle\Entity\Address', // Where we store our entities
            ))
            ->add(gettext('Save'), 'submit')
            ->getForm();

        $form->handleRequest($this->getRequest());

        if ($form->isSubmitted() && $form->isValid()) {
            $billing = $form->get('billingAddress')->getData();
            $em->persist($billing);
            $em->flush();

            $shipping = $form->get('shippingAddress')->getData();
            $em->persist($shipping);
            $em->flush();

            $session = $this->getRequest()->getSession();
            $session->getFlashBag()->add('message', gettext('Saved!'));

            return $this->redirect($this->generateUrl('profile_account'));
        }

        return $this->render('CompanyBundle:Profile:account.html.twig', array('form' => $form->createView()));