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 :

[Form] Deux entitées


Sujet :

Symfony PHP

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2013
    Messages
    54
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Janvier 2013
    Messages : 54
    Points : 27
    Points
    27
    Par défaut [Form] Deux entitées
    Bonjour,

    J'ai un formulaire pour ajouter une application mobile.
    Cette application contient:

    BASE APPLICATION
    - son titre
    - sa description
    - son logo
    - son prix
    - sa catégorie

    BASE FICHIER
    - la version du fichier
    - le nom du fichier


    Mon problème:

    Lorsque je valide le formulaire, je tombe sur cette erreur:
    An exception occurred while executing 'INSERT INTO gosoft_fichiers (version, dateajout, publication, apk, user_id, application_id) VALUES (?, ?, ?, ?, ?, ?)' with params {"1":1,"2":"2013-01-21 15:35:14","3":0,"4":null,"5":1,"6":46}:

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'apk' cannot be null
    Le problème est donc:
    - la valeur de "version" est toujours à 1 (voir message d'erreur) même si j'indique 3 dans le formulaire par exemple.
    - le champ d'upload "apk" qui ne fonctionne pas (en effet l'apk ne s'upload pas). Pourtant j'ai utilisé le même principe que pour le logo de l'application qui lui s'upload bien.




    Voici donc mes fichiers:

    ApplicationType.php
    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
    <?php
     
    namespace GoSoft\MainBundle\Form;
     
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
     
    class ApplicationType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('nom', 'text')
                ->add('description', 'textarea')
    			->add('prix', 'number')
    			->add('categorie', 'entity', array('class' => 'GoSoftMainBundle:Categorie','property' => 'nom',))
    			->add('logo')
    			->add('fichier',  'collection', array('type'         => new FichierType(),
                                                         'allow_add'    => true,
                                                         'allow_delete' => false,
                                                         'by_reference' => false))
            ;
        }
     
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'GoSoft\MainBundle\Entity\Application'
            ));
        }
     
        public function getName()
        {
            return 'gosoft_mainbundle_applicationtype';
        }
    }
    FichierType.php
    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
    <?php
     
    namespace GoSoft\MainBundle\Form;
     
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
     
    class FichierType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('version', 'number')
    			->add('apk')
            ;
        }
     
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'GoSoft\MainBundle\Entity\Fichier'
            ));
        }
     
        public function getName()
        {
            return 'gosoft_mainbundle_fichiertype';
        }
    }
    Application.php
    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
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    <?php
     
    namespace GoSoft\MainBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
     
    /**
     * GoSoft\MainBundle\Entity\Application
     *
     * @ORM\Table(name="gosoft_applications")
     * @ORM\HasLifecycleCallbacks
     * @ORM\Entity(repositoryClass="GoSoft\MainBundle\Entity\ApplicationRepository")
     */
    class Application
    {
        /**
         * @var integer $id
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
        /**
         * @var string $nom
         *
         * @ORM\Column(name="nom", type="string", length=255)
         * @Assert\MinLength(limit = 2)
         */
    	 //@Assert\MinLength(limit = 2, message = "Le nom de famille doit avoir au moins {{ limit }} caractères")
        private $nom;
     
    	/**
    	 * @ORM\ManyToOne(targetEntity="GoSoft\UserBundle\Entity\User", inversedBy="applications")
         * @ORM\JoinColumn(nullable=false)
    	 * @Assert\Type(type="GoSoft\UserBundle\Entity\User")
    	 */
    	private $user;
     
        /**
         * @var text $description
         *
         * @ORM\Column(name="description", type="text")
         * @Assert\NotBlank()
         */
        private $description;
     
    	/**
         * @var decimal $prix
         *
         * @ORM\Column(name="prix", type="decimal", scale=2)
         * @Assert\NotBlank()
         */
        private $prix;
     
    	/**
         * @var decimal $prixpromo
         *
         * @ORM\Column(name="prixpromo", type="decimal", scale=2)
         */
        private $prixpromo;
     
    	/**
         * @var datetime $dateajout
         *
         * @ORM\Column(name="dateajout", type="datetime")
         * @Assert\DateTime()
         */
        private $dateajout;
     
        /**
    	 * @var boolean $publication
         * @ORM\Column(name="publication", type="boolean")
         */
        private $publication;
     
    	/**
         * @ORM\ManyToOne(targetEntity="GoSoft\MainBundle\Entity\Categorie", inversedBy="applications")
         * @ORM\JoinColumn(nullable=false)
         */
        private $categorie;
     
    	/**
         * @var string $logo
         * @Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
         * @ORM\Column(name="logo", type="string", length=255)
         */
        private $logo;
     
     
    	public function __construct()
        {
    		$this->dateajout   = new \Datetime;
            $this->publication  = false;
    		$this->prixpromo  = 0;
    		$this->fichier   = new \Doctrine\Common\Collections\ArrayCollection();
        }
     
     
     
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId()
        {
            return $this->id;
        }
     
        /**
         * Set nom
         *
         * @param string $nom
         * @return Application
         */
        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 Application
         */
        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 GoSoftApplication
         */
        public function setPrix($prix)
        {
            $this->prix = $prix;
     
            return $this;
        }
     
        /**
         * Get prix
         *
         * @return float 
         */
        public function getPrix()
        {
            return $this->prix;
        }
     
        /**
         * Set publication
         *
         * @param boolean $publication
         * @return Application
         */
        public function setPublication($publication)
        {
            $this->publication = $publication;
     
            return $this;
        }
     
        /**
         * Get publication
         *
         * @return boolean 
         */
        public function getPublication()
        {
            return $this->publication;
        }
     
        /**
         * Set categorie
         *
         * @param GoSoft\MainBundle\Entity\GoSoftCategorie $categorie
         * @return GoSoftApplication
         */
        public function setCategorie(\GoSoft\MainBundle\Entity\Categorie $categorie)
        {
            $this->categorie = $categorie;
     
            return $this;
        }
     
        /**
         * Get categorie
         *
         * @return GoSoft\MainBundle\Entity\GoSoftCategorie 
         */
        public function getCategorie()
        {
            return $this->categorie;
        }
     
        /**
         * Set prixpromo
         *
         * @param float $prixpromo
         * @return GoSoftApplication
         */
        public function setPrixpromo($prixpromo)
        {
            $this->prixpromo = $prixpromo;
     
            return $this;
        }
     
        /**
         * Get prixpromo
         *
         * @return float 
         */
        public function getPrixpromo()
        {
            return $this->prixpromo;
        }
     
        /**
         * Set dateajout
         *
         * @param \DateTime $dateajout
         * @return Application
         */
        public function setDateajout($dateajout)
        {
            $this->dateajout = $dateajout;
     
            return $this;
        }
     
        /**
         * Get dateajout
         *
         * @return \DateTime 
         */
        public function getDateajout()
        {
            return $this->dateajout;
        }
     
        /**
         * Set user
         *
         * @param GoSoft\UserBundle\Entity\User $user
         * @return Application
         */
        public function setUser(\GoSoft\UserBundle\Entity\User $user)
        {
            $this->user = $user;
     
            return $this;
        }
     
        /**
         * Get user
         *
         * @return GoSoft\UserBundle\Entity\User 
         */
        public function getUser()
        {
            return $this->user;
        }
     
        /**
         * Add user
         *
         * @param GoSoft\UserBundle\Entity\User $user
         * @return Application
         */
        public function addUser(\GoSoft\UserBundle\Entity\User $user)
        {
            $this->user[] = $user;
     
            return $this;
        }
     
        /**
         * Remove user
         *
         * @param GoSoft\UserBundle\Entity\User $user
         */
        public function removeUser(\GoSoft\UserBundle\Entity\User $user)
        {
            $this->user->removeElement($user);
        }
     
        /**
         * Set logo
         *
         * @param string $logo
         * @return logo
         */
        public function setLogo($logo)
        {
            $this->logo = $logo;
     
            return $this;
        }
     
        /**
         * Get logo
         *
         * @return string 
         */
        public function getLogo()
        {
            return $this->logo;
        }
     
     
     
    	public function getFullLogoPath() {
            return null === $this->logo ? null : $this->getUploadRootDir().'/logo/'. $this->logo;
        }
     
        protected function getUploadRootDir() {
            // the absolute directory path where uploaded documents should be saved
            return __DIR__ . '/../../../../web/upload/'.$this->getId().'/';
        }
     
        protected function getTmpUploadRootDir() {
            // the absolute directory path where uploaded documents should be saved
            return __DIR__ . '/../../../../web/upload/temp/';
        }
     
        /**
         * @ORM\PrePersist()
         * @ORM\PreUpdate()
         */
        public function uploadLogo() {
            // the file property can be empty if the field is not required
            if (null === $this->logo) {
                return;
            }
            if(!$this->id){
                $this->logo->move($this->getTmpUploadRootDir(), $this->logo->getClientOriginalName());
            }else{
                $this->logo->move($this->getUploadRootDir(), $this->logo->getClientOriginalName());
            }
            $this->setLogo($this->logo->getClientOriginalName());
        }
     
        /**
         * @ORM\PostPersist()
         */
        public function moveLogo()
        {
            if (null === $this->logo) {
                return;
            }
            if(!is_dir($this->getUploadRootDir())){
                mkdir($this->getUploadRootDir());
            }
     
    		$chemin_final = $this->getUploadRootDir().'/logo/';
    		if(!is_dir($chemin_final)){
                mkdir($chemin_final);
            }
     
            copy($this->getTmpUploadRootDir().$this->logo, $this->getFullLogoPath());
            unlink($this->getTmpUploadRootDir().$this->logo);
        }
     
        /**
         * @ORM\PreRemove()
         */
        public function removeLogo()
        {
            unlink($this->getFullLogoPath());
            rmdir($this->getUploadRootDir());
        }
    }
    Fichier.php
    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
    <?php
     
    namespace GoSoft\MainBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
     
    /**
     * GoSoft\MainBundle\Entity\Fichier
     *
     * @ORM\Table(name="gosoft_fichiers")
     * @ORM\HasLifecycleCallbacks
     * @ORM\Entity(repositoryClass="GoSoft\MainBundle\Entity\FichierRepository")
     */
    class Fichier
    {
        /**
         * @var integer $id
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
    	/**
    	 * @ORM\ManyToOne(targetEntity="GoSoft\UserBundle\Entity\User", inversedBy="fichiers")
         * @ORM\JoinColumn(nullable=false)
    	 * @Assert\Type(type="GoSoft\UserBundle\Entity\User")
    	 */
    	private $user;
     
    	/**
    	 * @ORM\ManyToOne(targetEntity="GoSoft\MainBundle\Entity\Application", inversedBy="fichiers")
         * @ORM\JoinColumn(nullable=false)
    	 * @Assert\Type(type="GoSoft\MainBundle\Entity\Application")
    	 */
    	private $application;
     
    	/**
         * @var decimal $version
         *
         * @ORM\Column(name="version", type="decimal", scale=2)
         */
        private $version;
     
    	/**
         * @var datetime $dateajout
         *
         * @ORM\Column(name="dateajout", type="datetime")
         * @Assert\DateTime()
         */
        private $dateajout;
     
        /**
    	 * @var boolean $publication
         * @ORM\Column(name="publication", type="boolean")
         */
        private $publication;
     
    	/**
         * @var string $apk
         * @Assert\File( maxSize = "100M", mimeTypesMessage = "Please upload a valid Apk")
         * @ORM\Column(name="apk", type="string", length=255)
         */
        private $apk;
     
     
    	public function __construct()
        {
    		$this->dateajout   = new \Datetime;
            $this->publication  = false;
    		$this->version  = 1.0;
        }
     
     
     
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId()
        {
            return $this->id;
        }
     
        /**
         * Set publication
         *
         * @param boolean $publication
         * @return Fichier
         */
        public function setPublication($publication)
        {
            $this->publication = $publication;
     
            return $this;
        }
     
        /**
         * Get publication
         *
         * @return boolean 
         */
        public function getPublication()
        {
            return $this->publication;
        }
     
        /**
         * Set dateajout
         *
         * @param \DateTime $dateajout
         * @return Fichier
         */
        public function setDateajout($dateajout)
        {
            $this->dateajout = $dateajout;
     
            return $this;
        }
     
        /**
         * Get dateajout
         *
         * @return \DateTime 
         */
        public function getDateajout()
        {
            return $this->dateajout;
        }
     
    	/**
         * Set version
         *
         * @param string $version
         * @return Fichier
         */
        public function setVersion($version)
        {
            $this->version = $version;
     
            return $this;
        }
     
        /**
         * Get version
         *
         * @return string 
         */
        public function getVersion()
        {
            return $this->version;
        }
     
    	/**
         * Set application
         *
         * @param GoSoft\MainBundle\Entity\Application $application
         * @return Fichier
         */
        public function setApplication(\GoSoft\MainBundle\Entity\Application $application)
        {
            $this->application = $application;
     
            return $this;
        }
     
        /**
         * Get application
         *
         * @return GoSoft\MainBundle\Entity\Application
         */
        public function getApplication()
        {
            return $this->application;
        }
     
        /**
         * Set user
         *
         * @param GoSoft\UserBundle\Entity\User $user
         * @return Application
         */
        public function setUser(\GoSoft\UserBundle\Entity\User $user)
        {
            $this->user = $user;
     
            return $this;
        }
     
        /**
         * Get user
         *
         * @return GoSoft\UserBundle\Entity\User 
         */
        public function getUser()
        {
            return $this->user;
        }
     
        /**
         * Set apk
         *
         * @param string $apk
         * @return apk
         */
        public function setApk($apk)
        {
            $this->apk = $apk;
     
            return $this;
        }
     
        /**
         * Get apk
         *
         * @return string 
         */
        public function getApk()
        {
            return $this->apk;
        }
     
     
    	public function getFullApkPath() {
            return null === $this->apk ? null : $this->getUploadRootDir().'/apk/'. $this->apk;
        }
     
        protected function getUploadRootDir() {
            // the absolute directory path where uploaded documents should be saved
            return __DIR__ . '/../../../../web/upload/'.$this->getApplication()->getId().'/';
        }
     
        protected function getTmpUploadRootDir() {
            // the absolute directory path where uploaded documents should be saved
            return __DIR__ . '/../../../../web/upload/temp/';
        }
     
        /**
         * @ORM\PrePersist()
         * @ORM\PreUpdate()
         */
        public function uploadApk() {
            // the file property can be empty if the field is not required
            if (null === $this->apk) {
                return;
            }
            if(!$this->id){
                $this->apk->move($this->getTmpUploadRootDir(), $this->apk->getClientOriginalName());
            }else{
                $this->logo->move($this->getUploadRootDir(), $this->apk->getClientOriginalName());
            }
            $this->setApk($this->apk->getClientOriginalName());
        }
     
        /**
         * @ORM\PostPersist()
         */
        public function moveApk()
        {
            if (null === $this->apk) {
                return;
            }
            if(!is_dir($this->getUploadRootDir())){
                mkdir($this->getUploadRootDir());
            }
     
    		$chemin_final = $this->getUploadRootDir().'/apk/';
    		if(!is_dir($chemin_final)){
                mkdir($chemin_final);
            }
     
            copy($this->getTmpUploadRootDir().$this->apk, $this->getFullApkPath());
            unlink($this->getTmpUploadRootDir().$this->apk);
        }
     
        /**
         * @ORM\PreRemove()
         */
        public function removeApk()
        {
            unlink($this->getFullApkPath());
            rmdir($this->getUploadRootDir());
        }
    }

  2. #2
    Membre expérimenté Avatar de Nico_F
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2011
    Messages
    728
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Avril 2011
    Messages : 728
    Points : 1 310
    Points
    1 310
    Par défaut
    Salut,

    Je pense que tu ne devrais pas utiliser $apk comme un objet fichier si tu le mappes à une colonne de type string. Ce que tu veux stocker dans la base (et donc ce que tu vas persister) c'est une chaîne de caractère, pas le fichier lui même. Qu'il s'agisse du chemin pour accéder à ce fichier, ou uniquement son nom mais ça reste une chaîne de caractère.

    Je te suggère de rajouter un attribut $objFile à ta classe Fichier, qui serait non mappé mais stockerait ton objet. C'est ce champs que tu mettras dans ton formulaire et il sera de type 'file'. Ton champs apk lui n'appartient pas au formulaire mais est mappé.

    Ensuite tu peux, comme tu l'as fait, utiliser les méthodes prePersist ou preUpdate pour récupérer cet objet fichier, et setter ton champs apk en fonction des informations de ton objet fichier (et faire d'autres choses comme déplacer ton fichier dans un répertoire donné etc.)

    Au moment tu persist(), ton attribut apk ne sera plus null puisque tu auras défini son contenu en prePersist et tu continueras à pouvoir manipuler ton objet fichier en postPersist, on Flush etc.

    EDIT : Quelque chose dans ce goût là

    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
    class Fichier
    {
    	// ...
     
    	/**
    	 * @var string $apk
    	 * @ORM\Column(name="apk", type="string", length=255)
    	 */
    	private $apk;
     
    	/**
    	 * @var object $objFile
    	 * @Assert\File( maxSize = "100M", mimeTypesMessage = "Please upload a valid Apk")
    	 */
    	private $objFile
     
    	// ...
     
    	/**
    	 * Set apk
    	 *
    	 * @param string $apk
    	 * @return Fichier
    	 */
    	public function setApk($apk)
    	{
    	    $this->apk = $apk;
     
    	    return $this;
    	}
     
    	/**
    	 * Get apk
    	 *
    	 * @return string 
    	 */
    	public function getApk()
    	{
    	    return $this->apk;
    	}
     
    	/**
    	 * Set objFile
    	 *
    	 * @param object $objFile
    	 * @return Fichier
    	 */
    	public function setFile($objFile)
    	{
    	    $this->objFile = $objFile;
     
    	    return $this;
    	}
     
    	/**
    	 * Get apk
    	 *
    	 * @return object 
    	 */
    	public function getFile()
    	{
    	    return $this->objFile;
    	}
     
    	// ...
     
    	/**
             * @ORM\PrePersist()
    	 */
    	 public function setApkPrePersist()
    	 {
    	    // Ceci n'est qu'un exemple
    	    $this->apk = $this->objFile->getClientOriginalName();
    	 }
    Et tu mets objFile au lieu de apk dans le builder de ton form.

    Une dernière chose sur laquelle il faut être vigilent, en édition (update) si la seule modification que tu fais est de changer le fichier, comme ce champs n'est pas persisté, l'entity manager estimera qu'aucun changement n'a été fait. Il faudra alors forcer l'upload via le UnitOfWork.

    Bon courage

    ++

  3. #3
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2013
    Messages
    54
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Janvier 2013
    Messages : 54
    Points : 27
    Points
    27
    Par défaut
    Salut Nico,

    Tout d'abord merci de ta réponse.

    J'ai donc utilisé le principe que tu m'a expliqué en utilisant la documentation de Symfony.
    http://symfony.com/fr/doc/current/co...e_uploads.html


    Cependant j'ai quelques petits soucis:
    1) J'obtient comme chemin le chemin temporaire pour le champ "apk" => C:\wamp\tmp\php478C.tmp (j'ai bien le bon nom de l'apk dans le champ "path")
    2) Lors de la modification j'ai un soucis; le champ d'upload n'est pas récupéré contrairement aux autres (version)
    3) Je souhaiterais pouvoir choisir de ne pas mettre à jour l'apk, cependant lorsque je ne le met pas à jour, le champ apk est remplacé par une valeur nulle (pas null mais vide).

    Voici mes fichiers:

    Fichier.php
    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
    <?php
     
    namespace GoSoft\MainBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
     
    /**
     * GoSoft\MainBundle\Entity\Fichier
     *
     * @ORM\Table(name="gosoft_fichiers")
     * @ORM\HasLifecycleCallbacks
     * @ORM\Entity(repositoryClass="GoSoft\MainBundle\Entity\FichierRepository")
     */
    class Fichier
    {
        /**
         * @var integer $id
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
    	/**
    	 * @ORM\ManyToOne(targetEntity="GoSoft\MainBundle\Entity\Application", inversedBy="fichiers")
         * @ORM\JoinColumn(nullable=false)
    	 * @Assert\Type(type="GoSoft\MainBundle\Entity\Application")
    	 */
    	private $application;
     
    	/**
         * @var integer $telechargement
         *
         * @ORM\Column(name="telechargement", type="integer")
         */
        private $telechargement;
     
    	/**
         * @var decimal $version
         *
         * @ORM\Column(name="version", type="decimal", scale=2)
         */
        private $version;
     
    	/**
         * @var string $apk
         * @Assert\File( maxSize="100M", mimeTypesMessage = "Please upload a valid Apk")
         * @ORM\Column(name="apk", type="string", length=255)
         */
        private $apk;
     
     
    	public function __construct()
        {
    		$this->version  = 1;
    		$this->telechargement  = 0;
        }
     
     
     
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId()
        {
            return $this->id;
        }
     
    	/**
         * Set version
         *
         * @param string $version
         * @return Fichier
         */
        public function setVersion($version)
        {
            $this->version = $version;
     
            return $this;
        }
     
        /**
         * Get version
         *
         * @return string 
         */
        public function getVersion()
        {
            return $this->version;
        }
     
    	/**
         * Set application
         *
         * @param GoSoft\MainBundle\Entity\Application $application
         * @return Fichier
         */
        public function setApplication(\GoSoft\MainBundle\Entity\Application $application)
        {
            $this->application = $application;
     
            return $this;
        }
     
        /**
         * Get application
         *
         * @return GoSoft\MainBundle\Entity\Application
         */
        public function getApplication()
        {
            return $this->application;
        }
     
        /**
         * Set apk
         *
         * @param string $apk
         * @return apk
         */
        public function setApk($apk)
        {
            $this->apk = $apk;
     
            return $this;
        }
     
        /**
         * Get apk
         *
         * @return string 
         */
        public function getApk()
        {
            return $this->apk;
        }
     
        /**
         * Set telechargement
         *
         * @param integer $telechargement
         * @return Fichier
         */
        public function setTelechargement($telechargement)
        {
            $this->telechargement = $telechargement;
     
            return $this;
        }
     
        /**
         * Get telechargement
         *
         * @return integer 
         */
        public function getTelechargement()
        {
            return $this->telechargement;
        }
     
     
     
    	/**
         * @ORM\Column(type="string", length=255, nullable=true)
         */
        public $path;
     
    	// propriété utilisé temporairement pour la suppression
        private $filenameForRemove;
     
        /**
         * @ORM\PrePersist()
         * @ORM\PreUpdate()
         */
        public function preUpload()
        {
    		// the file property can be empty if the field is not required
            if (null === $this->apk) {
                return;
            }
            elseif (null !== $this->apk) {
                $this->path = $this->apk->getClientOriginalName();
            }
        }
     
        /**
         * @ORM\PostPersist()
         * @ORM\PostUpdate()
         */
        public function upload()
        {
            if (null === $this->apk) {
                return;
            }
     
            // vous devez lancer une exception ici si le fichier ne peut pas
            // être déplacé afin que l'entité ne soit pas persistée dans la
            // base de données comme le fait la méthode move() de UploadedFile
            $this->apk->move($this->getUploadRootDir(), $this->id.'.'.$this->apk->guessExtension());
    		//$this->setLogo($this->apk->getClientOriginalName());
            unset($this->apk);
        }
     
        /**
         * @ORM\PreRemove()
         */
        public function storeFilenameForRemove()
        {
            $this->filenameForRemove = $this->getAbsolutePath();
        }
     
        /**
         * @ORM\PostRemove()
         */
        public function removeUpload()
        {
            if ($this->filenameForRemove) {
                unlink($this->filenameForRemove);
            }
        }
     
        public function getAbsolutePath()
        {
            return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->id.'.'.$this->path;
        }
     
    	public function getWebPath()
        {
            return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
        }
     
        protected function getUploadRootDir()
        {
            // le chemin absolu du répertoire où les documents uploadés doivent être sauvegardés
            return __DIR__.'/../../../../web/'.$this->getUploadDir();
        }
     
        protected function getUploadDir()
        {
            // on se débarrasse de « __DIR__ » afin de ne pas avoir de problème lorsqu'on affiche
            // le document/image dans la vue.
            return 'upload/apk';
        }
    }
    FichierType.php
    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
    <?php
     
    namespace GoSoft\MainBundle\Form;
     
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
     
    class FichierType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('version', 'number')
    			->add('apk')
            ;
        }
     
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'GoSoft\MainBundle\Entity\Fichier'
            ));
        }
     
        public function getName()
        {
            return 'gosoft_mainbundle_fichiertype';
        }
    }

  4. #4
    Membre expérimenté Avatar de Nico_F
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2011
    Messages
    728
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Avril 2011
    Messages : 728
    Points : 1 310
    Points
    1 310
    Par défaut
    Je crois que tu n'as pas tout à fait compris là ou je voulais en venir.
    As-tu essayé comme je te le suggérais dans mon premier post d'ajouter un attribut 'file' dans ta classe Fichier ? Là je ne vois que ton champs apk mais nulle part je ne vois le champs ou tu récupères le fichier : et c'est ce champs qu'il faudra mettre dans le form : le 'file' pas le champs 'apk'.

    Quand tu vas récupérer ton formulaire, file contiendra un objet de type file, et apk ne contiendra rien du tout. C'est normal : c'est à toi, dans les event listeners comme le prePersist, de faire en sorte de récupérer le pathfile, ou le filename ou ce que tu veux à partir du fichier et de le setter dans ton champs apk qui lui n'attend rien d'autre qu'un string.

    Si je reprends ton FormType, ton builder devrait ressembler à ça (en me basant sur l'entité que je t'ai fourni dans mon premier post)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('version', 'number')
            ->add('objFile', 'file')
        ;
    }
    Pour finir rien ne t’empêche d'affecter la valeur null ou vide par défaut à l'apk, et de ne le modifier que s'il y a un fichier. De toute façon la valeur de ce champs ne peut être modifiée que par le prePersist, puisqu'il ne doit pas apparaître dans ton formulaire.

    ++

  5. #5
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2013
    Messages
    54
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Janvier 2013
    Messages : 54
    Points : 27
    Points
    27
    Par défaut
    Merci,

    C'était effectivement ce que je recherchais.
    Grâce à ta méthode j'ai résolus tous mes soucis.

    Je peux désormais uploader une apk, la mettre à jour ou non si je laisse le champ vide.

Discussions similaires

  1. [2.x] [Form] Formulaire avec deux entités abstraites
    Par L0rD59 dans le forum Symfony
    Réponses: 1
    Dernier message: 24/03/2013, 21h43
  2. [2.x] [Symfony2]Problème Ajout de deux entités dans un même form
    Par the ing dans le forum Symfony
    Réponses: 1
    Dernier message: 14/12/2012, 17h48
  3. [MCD] Historiser deux entités et leurs relations
    Par fayred dans le forum Schéma
    Réponses: 2
    Dernier message: 23/05/2007, 11h04
  4. une <form> deux actions
    Par rexxys dans le forum Général JavaScript
    Réponses: 7
    Dernier message: 13/01/2007, 15h10
  5. [XSL / XML] Conserver un espace entre deux entités
    Par alkolo dans le forum XSL/XSLT/XPATH
    Réponses: 6
    Dernier message: 29/03/2006, 14h26

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