[Symfony 2.6] Soumission de formulaires imbriqués

Fermé
patrice86 Messages postés 1378 Date d'inscription dimanche 26 octobre 2008 Statut Membre Dernière intervention 26 novembre 2023 - Modifié par patrice86 le 17/05/2015 à 11:41
patrice86 Messages postés 1378 Date d'inscription dimanche 26 octobre 2008 Statut Membre Dernière intervention 26 novembre 2023 - 17 mai 2015 à 11:42
Bonjour,

Je suis entrain de développer une application qui permet de saisir des commandes à l'aide de Symfony 2.6.
L'idée est qu'une commande est liée obligatoirement à une personne et peut être composée de 1 ou plusieurs produits.

4 entités pour cela :
Shopping(les commandes)
class Shopping
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

<gras>    /**
     * @ORM\OneToMany(targetEntity="XXXXX\OrderBundle\Entity\ShoppingProduct", mappedBy="shopping", cascade={"persist"})
     */
    private $shoppingProducts;</gras>

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    private $totalPrice;

    /**
     * @ORM\Column(type="datetime")
     */
    private $date;

    /**
     * @ORM\ManyToOne(targetEntity="XXXX\RhBundle\Entity\Customer", inversedBy="orders")
     * @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
     */
    protected $customer;

//Les GETTERS et SETTERS
}


Customer (les clients)
class Customer
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=5)
     */
    protected $sexe;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $nom;

    /**
     * @ORM\Column(type="string", length=50)
     */
    protected $prenom;

    /**
     * @ORM\Column(type="string", length=10)
     */
    protected $tel;

    /**
     * @ORM\Column(type="string", length=50)
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length=50)
     */
    protected $address;

    /**
     * @ORM\Column(type="string", length=5)
     */
    protected $cp;

    /**
     * @ORM\Column(type="string", length=50)
     */
    protected $city;

    /**
     * @ORM\OneToMany(targetEntity="XXXXX\ShoppingBundle\Entity\Shopping", mappedBy="customer")
     */
    protected $shopping;
// les GETTERS et SETTERS
}


Product (les produits)
class Product
{
    /**
     * @ORM\Column(name="reference", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    protected $reference;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $libelle;

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    protected $price;

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    protected $category;

    /**
     * @ORM\OneToMany(targetEntity="XXXXX\OrderBundle\Entity\ShoppingProduct", mappedBy="product")
     */
    private $shoppingProducts;

// Les GETTERS et SETTERS
}


ShoppingProduct (table de liaison entre Shoppinget Product)

class ShoppingProduct
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\ManyToOne(targetEntity="XXXXX\ShoppingBundle\Entity\Order", inversedBy="shoppingProducts")
     * @ORM\JoinColumn(name="order_id", referencedColumnName="id")
     */
    private $shoping;

    /**
     * @ORM\ManyToOne(targetEntity="XXXXX\ProductBundle\Entity\Product", inversedBy="orderProducts")
     * @ORM\JoinColumn(name="product_reference", referencedColumnName="reference")
     */
    private $product;

    /**
     * @ORM\Column()
     */
    private $quantity;

//Les GETTERS et SETTERS
}


J'ai créé deux formType:
ShoppingType

    
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('totalPrice', 'text', array("label" => "XXXXXRhBundle.customers.page_new_edit.sexe"))
            ->add('date', 'date', array("label" => "XXXXXRhBundle.customers.page_new_edit.firstName"))
            ->add('customer','entity', array ('class' => 'XXXXX\RhBundle\Entity\Customer', 'empty_value' => 'Choisissez un client...', 'required' => true))
            ->add('shoppingProducts', 'collection', array('type' => new ShoppingProductType(),
                                                      'allow_add' => true,
                                                      'allow_delete' => true ));
    }


ShoppingProductType
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('quantity', 'integer', array("label" => "XXXXXRhBundle.customers.page_new_edit.firstName"))
            ->add('product','entity', array ('class' => 'XXXXX\ProductBundle\Entity\Product', 'empty_value' => 'Choisissez un produit...', 'required' => true));
    }


Lors de la soumission du formulaire ShoppingType, il faut donc dans un premier temps créer une commande dans la base de données et juste après créer des lignes dans l'entité ShoppingProduct afin d'avoir pour une commande, plusieurs produits et la quantité pour chacun des produits.

Pour tester, je submit mon formulaire en indiquant deux produits dans la commande.
Lors du flush, une nouvelle commande est créée dans Shopping et dans ShoppingProduct deux lignes sont bien créées (une par produit). Hors, voici ce qui est enregistré :


Comme vous pouvez le voir, le premier produit est enregistré correctement dans le second il manque les informations de shopping ! Et là, je ne vois pas du tout comment résoudre ce problème !
</ital>

OrderController
    public function createAction(Request $request)
    {
        public function createAction(Request $request)
    {
        $shopping = new Shopping();
        $shoppingProduct = new ShoppingProduct();

        $form = $this->createCreateForm($shopping);
        $shopping->addShoppingProduct($shoppingProduct);

        if ($request->isMethod('POST')) {
            $form->handleRequest($request);
            var_dump($shopping->getShoppingProducts());

            $em = $this->getDoctrine()->getManager();
            $em->persist($shopping);
            $em->flush();

            return $this->redirect($this->generateUrl('stanhome_shopping_shopping_show', array('id' => $shopping->getId())));
        }

        return array(
            'entity' => $shopping,
            'form'   => $form->createView(),
        );
    }


Merci beaucoup pour votre aide.

1 réponse

patrice86 Messages postés 1378 Date d'inscription dimanche 26 octobre 2008 Statut Membre Dernière intervention 26 novembre 2023 125
17 mai 2015 à 11:42
Up du sujet, personne ne peut m'aider ? :(
0