IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

update d'une entité contenant un array collection


Sujet :

Symfony PHP

  1. #1
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2015
    Messages
    32
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2015
    Messages : 32
    Par défaut update d'une entité contenant un array collection
    Bonjour,

    j'ai deux entités Produits et Couleur : ou chaque produit peut avoir plusieurs couleurs (l'entité couleur contient 3 champs : coul, taille, quantité)

    j'ai pu faire les relations entre ces entités ainsi que l'ajout dynamique de la couleur (lors de l'ajout d'un produit) :

    le problème est lors du modification d'un produit : je peut modifier les couleurs ajoutés précédemment , mais quand je veux ajouter une autre couleur là commence les problèmes : la couleur est enregistré dans ma BD mais avec un id_produit null


    Entité Produits :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    <?php
     
    namespace Ecommerce\EcommerceBundle\Entity;
     
    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints\Collection;
    use Symfony\Component\Validator\Constraints as Assert;
     
    /**
     * Produits
     *
     * @ORM\Table()
     * @ORM\Entity(repositoryClass="Ecommerce\EcommerceBundle\Repository\ProduitsRepository")
     * @ORM\HasLifecycleCallbacks
     */
    class Produits
    {
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
        /**
         * @ORM\ManyToOne(targetEntity="Categories", cascade={"persist"})
         * @ORM\JoinColumn(nullable=false)
         */
        private $categorie;
     
        /**
         * @var string
         *
         * @ORM\Column(name="nom", type="string", length=255)
         */
        private $nom;
     
        /**
         * @var string
         *
         * @ORM\Column(name="prixb", type="string", length=50, nullable=true)
         */
        private $prixb;
     
        /**
         * @var string
         *
         * @ORM\Column(name="marque", type="string", length=255, nullable=true)
         */
        private $marque;
     
        /**
         * @var string
         *
         * @ORM\Column(name="description", type="text")
         */
        private $description;
     
        /**
         * @var float
         *
         * @ORM\Column(name="prix", type="float")
         */
        private $prix;
     
        /**
         * @var integer
         *
         * @ORM\Column(name="qte", type="integer")
         */
        private $qte;
     
        /**
         * @var float
         *
         * @ORM\Column(name="poids", type="float")
         */
        private $poids;
     
        /**
         * @var boolean
         *
         * @ORM\Column(name="disponible", type="boolean")
         */
        private $disponible;
     
        /**
         * @var boolean
         *
         * @ORM\Column(name="solde", type="boolean", nullable=true)
         */
        private $solde;
     
     
        /**
         * @ORM\OneToMany(targetEntity="Couleur", mappedBy="produits", cascade={"persist"})
         * @ORM\JoinColumn(nullable=true)
         */
        private $couleur;
     
        public function setCouleur(ArrayCollection $couleur) {
            $this->couleur = $couleur;
            foreach ($couleur as $couleur) {
                $couleur->setProduits($this);
            }
        }
     
        /**
         * Add couleur
         *
         * @param Couleur $couleur
         * @return Produits
         */
        public function addCouleur(Couleur $couleur) {
            $this->couleur[] = $couleur;
            return $this;
        }
     
        /**
         * Remove couleur
         *
         * @param Couleur $couleur
         */
        public function removeCouleur(Couleur $couleur) {
            $this->couleur->removeElement($couleur);
        }
     
        /**
         * Get couleur
         *
         * @return Collection
         */
        public function getCouleur() {
            return $this->couleur;
        }
     
     
        /**
         * Get id
         *
         * @return integer
         */
        public function getId()
        {
            return $this->id;
        }
     
        /**
         * Set nom
         *
         * @param string $nom
         * @return Produits
         */
        public function setNom($nom)
        {
            $this->nom = $nom;
     
            return $this;
        }
     
        /**
         * Get nom
         *
         * @return string
         */
        public function getNom()
        {
            return $this->nom;
        }
     
        /**
         * Set description
         *
         * @param string $description
         * @return Produits
         */
        public function setDescription($description)
        {
            $this->description = $description;
     
            return $this;
        }
     
        /**
         * Get description
         *
         * @return string
         */
        public function getDescription()
        {
            return $this->description;
        }
     
        /**
         * Set prix
         *
         * @param float $prix
         * @return Produits
         */
        public function setPrix($prix)
        {
            $this->prix = $prix;
     
            return $this;
        }
     
        /**
         * Get prix
         *
         * @return float
         */
        public function getPrix()
        {
            return $this->prix;
        }
     
        /**
         * Set disponible
         *
         * @param boolean $disponible
         * @return Produits
         */
        public function setDisponible($disponible)
        {
            $this->disponible = $disponible;
     
            return $this;
        }
     
        /**
         * Get disponible
         *
         * @return boolean
         */
        public function getDisponible()
        {
            return $this->disponible;
        }
     
        function getCategorie() {
            return $this->categorie;
        }
     
     
        function setCategorie($categorie) {
            $this->categorie = $categorie;
        }
     
        function getQte() {
            return $this->qte;
        }
     
        function setQte($qte) {
            $this->qte = $qte;
        }
     
        function getMarque() {
            return $this->marque;
        }
     
        function setMarque($marque) {
            $this->marque = $marque;
        }
     
     
        function getPrixb() {
            return $this->prixb;
        }
     
        function setPrixb($prixb) {
            $this->prixb = $prixb;
        }
     
        function getPoids() {
            return $this->poids;
        }
     
        function setPoids($poids) {
            $this->poids = $poids;
        }
     
        function getSolde() {
            return $this->solde;
        }
     
        function setSolde($solde) {
            $this->solde = $solde;
        }
     
     
    }
    Entité Couleur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    <?php
     
    namespace Ecommerce\EcommerceBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
     
    /**
     * Couleur
     *
     * @ORM\Table()
     * @ORM\Entity(repositoryClass="Ecommerce\EcommerceBundle\Repository\CouleurRepository")
     */
    class Couleur {
     
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
        /**
         * @var string
         *
         * @ORM\Column(name="nomc", type="string", length=255)
         */
        private $nomc;
     
        /**
         * @var string
         *
         * @ORM\Column(name="taille", type="string", length=255)
         */
        private $taille;
     
        /**
         * @var integer
         *
         * @ORM\Column(name="quant", type="integer")
         */
        private $quant;
     
        /**
         * @ORM\ManyToOne(targetEntity="Produits", inversedBy="couleur")
         * @ORM\JoinColumn(name="produit_id", referencedColumnName="id",  onDelete="SET NULL")
         * @var type
         */
        private $produits;
     
        /**
         * Set produits
         *
         * @param Produits $produits
         * @return couleur
         */
        public function setProduits(Produits $produits = null) {
            $this->produits = $produits;
     
            return $this;
        }
     
        /**
         * Get produits
         *
         * @return \Ecommerce\EcommerceBundle\Entity\Produits
         */
        public function getProduits() {
            return $this->produits;
        }
     
        /**
         * Get id
         *
         * @return integer
         */
        public function getId() {
            return $this->id;
        }
        function getNomc() {
            return $this->nomc;
        }
     
        function setNomc($nomc) {
            $this->nomc = $nomc;
        }
     
        function getTaille() {
            return $this->taille;
        }
     
        function getQuant() {
            return $this->quant;
        }
     
        function setTaille($taille) {
            $this->taille = $taille;
        }
     
        function setQuant($quant) {
            $this->quant = $quant;
        }
     
     
     
    }
    ProduitType:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    <?php
     
    namespace Ecommerce\EcommerceBundle\Form;
     
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
     
     
    class ProduitsType extends AbstractType
    {
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('nom')
                ->add('description','textarea',array('attr' => array('class' => 'ckeditor')))
                ->add('marque', 'text', array('required' => false))
                ->add('prix')
                ->add('prixb', 'text', array('required' => false))
                ->add('poids')
                ->add('disponible')
                ->add('solde')
                ->add('qte')
                ->add('categorie')
                ->add('couleur', 'collection', array('type' => new CouleurType(), 'allow_add' => true, 'label' => false, 'required' => false, 'by_reference' => false))
            ;
        }
     
        /**
         * @param OptionsResolverInterface $resolver
         */
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'Ecommerce\EcommerceBundle\Entity\Produits'
            ));
        }
     
        /**
         * @return string
         */
        public function getName()
        {
            return 'ecommerce_ecommercebundle_produits';
        }
    }
    ProduitsController
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    <?php
     
    namespace Ecommerce\EcommerceBundle\Controller;
     
    use Ecommerce\EcommerceBundle\Entity\Couleur;
    use Ecommerce\EcommerceBundle\Entity\Produits;
    use Ecommerce\EcommerceBundle\Entity\Image;
    use Ecommerce\EcommerceBundle\Form\ProduitsType;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;
     
    /**
     * Produits controller.
     *
     * @Route("/produits")
     */
    class ProduitsController extends Controller
    {
     
        /**
         * Lists all Produits entities.
         *
         * @Route("/", name="produits")
         * @Method("GET")
         * @Template()
         */
        public function indexAction()
        {
            $em = $this->getDoctrine()->getManager();
     
            $entities = $em->getRepository('EcommerceEcommerceBundle:Produits')->findAll();
     
            return array(
                'entities' => $entities,
            );
        }
        /**
         * Creates a new Produits entity.
         *
         * @Route("/", name="produits_create")
         * @Method("POST")
         * @Template("EcommerceEcommerceBundle:Produits:new.html.twig")
         */
        public function createAction()
        {
            $produits = new Produits();
            $produits->addCouleur(new Couleur());
            $form = $this->createForm(new ProduitsType(), $produits)->add('submit','submit');
            $request = $this->get('request');
            if ($request->getMethod() == 'POST') {
                $form->bind($request);
                if ($form->isValid()) {
                    $em = $this->getDoctrine()->getManager();
                    $em->persist($produits);
                    $em->flush();
     
                    foreach ($form->get('couleur')->getData() as $c) {
                        $c->setProduits($produits);
                        $em->persist($c);
                    }
                    $em->flush();               
                }
                return $this->redirect($this->generateUrl('produits_show', array('id' => $produits->getId())));
            }
     
            return array(
                'entity' => $entity,
                'form'   => $form->createView(),
            );
        }
     
        /**
         * Creates a form to create a Produits entity.
         *
         * @param Produits $entity The entity
         *
         * @return \Symfony\Component\Form\Form The form
         */
        private function createCreateForm(Produits $entity)
        {
            $entity = new Produits();
            $entity->addImage(new Image());
            $form = $this->createForm(new ProduitsType(), $entity);
     
            $form->add('submit', 'submit', array('label' => 'Create'));
     
            return $form;
        }
     
        /**
         * Displays a form to create a new Produits entity.
         *
         * @Route("/new", name="produits_new")
         * @Method("GET")
         * @Template()
         */
        public function newAction()
        {
            $entity = new Produits();
            $form   = $this->createCreateForm($entity);
     
            return array(
                'entity' => $entity,
                'form'   => $form->createView(),
            );
        }
     
        /**
         * Finds and displays a Produits entity.
         *
         * @Route("/{id}", name="produits_show")
         * @Method("GET")
         * @Template()
         */
        public function showAction($id)
        {
            $em = $this->getDoctrine()->getManager();
     
            $entity = $em->getRepository('EcommerceEcommerceBundle:Produits')->find($id);
     
            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Produits entity.');
            }
     
            $deleteForm = $this->createDeleteForm($id);
     
            return array(
                'entity'      => $entity,
                'delete_form' => $deleteForm->createView(),
            );
        }
     
        /**
         * Displays a form to edit an existing Produits entity.
         *
         * @Route("/{id}/edit", name="produits_edit")
         * @Method("GET")
         * @Template()
         */
        public function editAction($id)
        {
            $em = $this->getDoctrine()->getManager();
     
            $entity = $em->getRepository('EcommerceEcommerceBundle:Produits')->find($id);
     
            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Produits entity.');
            }
     
            $editForm = $this->createEditForm($entity);
            $deleteForm = $this->createDeleteForm($id);
     
            return array(
                'entity'      => $entity,
                'edit_form'   => $editForm->createView(),
                'delete_form' => $deleteForm->createView(),
            );
        }
     
        /**
        * Creates a form to edit a Produits entity.
        *
        * @param Produits $entity The entity
        *
        * @return \Symfony\Component\Form\Form The form
        */
        private function createEditForm(Produits $entity)
        {
            $form = $this->createForm(new ProduitsType(), $entity, array(
                'action' => $this->generateUrl('produits_update', array('id' => $entity->getId())),
                'method' => 'PUT',
            ));
     
            $form->add('submit', 'submit', array('label' => 'Update'));
     
            return $form;
        }
        /**
         * Edits an existing Produits entity.
         *
         * @Route("/{id}", name="produits_update")
         * @Method("PUT")
         * @Template("EcommerceEcommerceBundle:Produits:edit.html.twig")
         */
        public function updateAction(Request $request, $id)
        {
            $em = $this->getDoctrine()->getManager();
     
            $entity = $em->getRepository('EcommerceEcommerceBundle:Produits')->find($id);
     
            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Produits entity.');
            }
     
            $deleteForm = $this->createDeleteForm($id);
            $editForm = $this->createEditForm($entity);
            $editForm->handleRequest($request);
     
            if ($editForm->isValid()) {
                $em->flush();
     
                return $this->redirect($this->generateUrl('produits_edit', array('id' => $id)));
            }
     
            return array(
                'entity'      => $entity,
                'edit_form'   => $editForm->createView(),
                'delete_form' => $deleteForm->createView(),
            );
        }
        /**
         * Deletes a Produits entity.
         *
         * @Route("/{id}", name="produits_delete")
         * @Method("DELETE")
         */
        public function deleteAction(Request $request, $id)
        {
            $form = $this->createDeleteForm($id);
            $form->handleRequest($request);
     
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $entity = $em->getRepository('EcommerceEcommerceBundle:Produits')->find($id);
     
                if (!$entity) {
                    throw $this->createNotFoundException('Unable to find Produits entity.');
                }
     
                $em->remove($entity);
                $em->flush();
            }
     
            return $this->redirect($this->generateUrl('produits'));
        }
     
        /**
         * Creates a form to delete a Produits entity by id.
         *
         * @param mixed $id The entity id
         *
         * @return \Symfony\Component\Form\Form The form
         */
        private function createDeleteForm($id)
        {
            return $this->createFormBuilder()
                ->setAction($this->generateUrl('produits_delete', array('id' => $id)))
                ->setMethod('DELETE')
                ->add('submit', 'submit', array('label' => 'Delete'))
                ->getForm()
            ;
        }
    }
    Merci pour vos aides

  2. #2
    Membre extrêmement actif
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Par défaut
    déjà, enleve le nullable=true car idProduit ne doit jamais etre égal à null.

    ça doit peter une erreur si c'est le cas

Discussions similaires

  1. [2.x] modifier une entité avec array collection via la console
    Par cuscodkr dans le forum Symfony
    Réponses: 1
    Dernier message: 15/10/2014, 11h36
  2. [Entity] Perte de la référence vers une entité quand collection vidée
    Par strat0 dans le forum Windows Presentation Foundation
    Réponses: 0
    Dernier message: 10/05/2009, 20h11
  3. Save or Update sur une collection
    Par *alexandre* dans le forum Hibernate
    Réponses: 2
    Dernier message: 04/01/2009, 14h29
  4. Réponses: 4
    Dernier message: 20/02/2008, 13h34
  5. [Tableaux] Lecture d'une variable contenant plusieurs arrays
    Par MightyDucks dans le forum Langage
    Réponses: 10
    Dernier message: 27/03/2006, 12h40

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo