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 :

Mise a jours champs file [2.x]


Sujet :

Symfony PHP

  1. #1
    Membre actif Avatar de Legenyes
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2005
    Messages
    174
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2005
    Messages : 174
    Points : 207
    Points
    207
    Par défaut Mise a jours champs file
    Bien le bonjour,

    Je souhaite avoir un attribut photo à l'un de mes objets.

    Lorsque j'ajoute un objet et que je met un photo, celle ci est bien uploadé (au bonne endroit), présente dans ma db, et visible sur le site.

    malheureusement, lorsque je veux editer mon objet, le champ input file est vide et donc si je ne fais pas attention et que je sauve l'objet, il efface mon image.

    comment corrigé ?

    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
     
    use Symfony\Component\Validator\Constraints as Assert;
     
    /**
     * @ORM\Table()
     * @ORM\HasLifecycleCallbacks
     */
    class monObjet {
    ...
     /**
         * @var string $vignette
         * @Assert\File(maxSize="6000000")     *
         * @ORM\Column(name="vignette", type="string", length=255, nullable=true)
         */
        private $vignette;
     
    /**
         * Set vignette
         *
         * @param string $vignette
         */
        public function setVignette($vignette) {
            $this->vignette = $vignette;
        }
     
        /**
         * Get vignette
         *
         * @return string 
         */
        public function getVignette() {
            return $this->vignette;
        }
     
        public function getFullPicturePath() {
            return null === $this->vignette ? null : $this->getUploadRootDir() . $this->vignette;
        }
     
        public function getVignetteWebPath() {
            return null === $this->vignette ? null : $this->getUploadDir() . '/' . $this->vignette;
        }
     
        protected function getUploadRootDir() {
            // the absolute directory path where uploaded documents should be saved
            return $this->getTmpUploadRootDir() . $this->getId() . "/";
        }
     
        protected function getTmpUploadRootDir() {
            // the absolute directory path where uploaded documents should be saved
            return __DIR__ . '/../../../../web/uploads/parcours/';
        }
     
        protected function getUploadDir() {
            // get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
            return '/uploads/parcours/' . $this->getId() . "/";
        }
     
        /**
         * @ORM\PrePersist()
         * @ORM\PreUpdate()
         */
        public function uploadPicture() {
            // the file property can be empty if the field is not required
            if (null === $this->vignette) {
                return;
            }
            if (!$this->id) {
                $this->vignette->move($this->getTmpUploadRootDir(), $this->vignette->getClientOriginalName());
            } else {
                $this->vignette->move($this->getUploadRootDir(), $this->vignette->getClientOriginalName());
            }
     
            $this->setVignette($this->vignette->getClientOriginalName());
        }
     
        /**
         * @ORM\PostPersist()
         */
        public function movePicture() {
            if (null === $this->vignette) {
                return;
            }
            if (!is_dir($this->getUploadRootDir())) {
                mkdir($this->getUploadRootDir());
            }
            copy($this->getTmpUploadRootDir() . $this->vignette, $this->getFullPicturePath());
            unlink($this->getTmpUploadRootDir() . $this->vignette);
        }
     
        /**
         * @ORM\PreRemove()
         */
        public function removePicture() {
            unlink($this->getFullPicturePath());
            rmdir($this->getUploadRootDir());
        }
    }
    http://www.anaprosy.be - Solution et réalisation informatique

  2. #2
    Membre éprouvé
    Homme Profil pro
    Inscrit en
    Juin 2011
    Messages
    725
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Juin 2011
    Messages : 725
    Points : 1 050
    Points
    1 050
    Par défaut
    Bonjour,
    Tu dois avoir deux attributs dans ta classe:
    $vignettePath ->attribut string qui est persisté en Base de données et qui indique le nom du fichier
    $vignetteFile->un attribut de classe UploadedFile , non persisté dans la base de données il est utilisé uniquement pour l'upload.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    /**
         * @var string $vignette
         * @Assert\File(maxSize="6000000")     *
         * @ORM\Column(name="vignette", type="string", length=255, nullable=true)
         */
        private $vignette;
    ton code n'est pas cohérent $vignette représente soit une chaine de caractere soit un fichier.
    Consulte bien la doc:
    http://symfony.com/doc/2.0/cookbook/...e_uploads.html

  3. #3
    Membre actif Avatar de Legenyes
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2005
    Messages
    174
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2005
    Messages : 174
    Points : 207
    Points
    207
    Par défaut
    Merci ,

    j'ai maintenant quelque chose qui me permet d'uploader mes photos.
    Mais j'ai un problème dans certains cas.

    J'ai un champs photo et un champs liens. Lorsque que je veux éditer mon objet, si le champ "lien" est définit mais que je ne le modifie pas, ma photo ne s'upload pas.

    quelqu'un comprend le rapport ?

    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
    <?php
     
    namespace Application\BlocBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
     
    /**
     * Application\BlocBundle\Entity\Bloc
     *
     * @ORM\Table() * 
     * @ORM\HasLifecycleCallbacks
     * @ORM\Entity(repositoryClass="Anaprosy\BlocBundle\Entity\BlocRepository")
     */
    class Bloc {
     
        /**
         * @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)
         */
        private $nom;
     
        /**
         * @var text $description
         *
         * @ORM\Column(name="description", type="text")
         */
        private $description;
     
        /**
         * @var string $lien
         *
         * @ORM\Column(name="lien", type="string", length=255, nullable=true)
         */
        private $lien;
     
        /**
         * @var string $photo
         * @ORM\Column(name="photo", type="string", length=255, nullable=true)
         */
        private $photo;
     
        /**
         * @Assert\File(maxSize="6000000")  
         */
        public $photoFile;
     
        /**
         * @var boolean $surligner
         *
         * @ORM\Column(name="surligner", type="boolean")
         */
        private $surligner;
     
        public function __toString() {
            return $this->nom;
        }
     
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId() {
            return $this->id;
        }
     
        /**
         * Set nom
         *
         * @param string $nom
         */
        public function setNom($nom) {
            $this->nom = $nom;
        }
     
        /**
         * Get nom
         *
         * @return string 
         */
        public function getNom() {
            return $this->nom;
        }
     
        /**
         * Set description
         *
         * @param text $description
         */
        public function setDescription($description) {
            $this->description = $description;
        }
     
        /**
         * Get description
         *
         * @return text 
         */
        public function getDescription() {
            return $this->description;
        }
     
        /**
         * Set lien
         *
         * @param string $lien
         */
        public function setLien($lien) {
            $this->lien = $lien;
        }
     
        /**
         * Get lien
         *
         * @return string 
         */
        public function getLien() {
            return $this->lien;
        }
     
        /**
         * Set photo
         *
         * @param string $photo
         */
        public function setPhoto($photo) {
            $this->photo = $photo;
        }
     
        /**
         * Get photo
         *
         * @return string 
         */
        public function getPhoto() {
            return $this->photo;
        }
     
        /**
         * Set surligner
         *
         * @param boolean $surligner
         */
        public function setSurligner($surligner) {
            $this->surligner = $surligner;
        }
     
        /**
         * Get surligner
         *
         * @return boolean 
         */
        public function getSurligner() {
            return $this->surligner;
        }
     
        public function getAbsolutePath()
        {
            return null === $this->photo ? null : $this->getUploadRootDir().'/'.$this->photo;
        }
     
        public function getWebPath()
        {
            return null === $this->photo ? null : $this->getUploadDir().'/'.$this->photo;
        }
     
        public function getPhotoWebPath()
        {        
             return null === $this->photo ? null : $this->getUploadDir().'/'.$this->photo;
        }
     
        protected function getUploadRootDir()
        {
            // the absolute directory path where uploaded documents should be saved
            return __DIR__.'/../../../../web'.$this->getUploadDir();
        }
     
        protected function getUploadDir()
        {
            // get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
            return '/uploads/blocs/'. $this->getId().'/';
        }
        /**
         * @ORM\PrePersist()
         * @ORM\PreUpdate()
         */
        public function preUpload()
        {
            if (null !== $this->photoFile) {
                // do whatever you want to generate a unique name
     
                //$this->photo = uniqid().'.'.$this->photoFile->guessExtension();
                $this->photo = \Anaprosy\Tools\Helper::slugify($this->photoFile->getClientOriginalName());
            }
        }
     
        /**
         * @ORM\PostPersist()
         * @ORM\PostUpdate()
         */
        public function upload()
        {
            if (null === $this->photoFile) {
                return;
            }
     
            if (!is_dir($this->getUploadRootDir())) {
                mkdir($this->getUploadRootDir());
            }
            // if there is an error when moving the file, an exception will
            // be automatically thrown by move(). This will properly prevent
            // the entity from being persisted to the database on error
            $this->photoFile->move($this->getUploadRootDir(), $this->photo);
     
            unset($this->photoFile);
        }
     
        /**
         * @ORM\PostRemove()
         */
        public function removeUpload()
        {
            if ($photoFile = $this->getAbsolutePath()) {
                unlink($photoFile);
            }
        }
     
    }
    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
    <?php
     
    namespace Application\BlocBundle\Form;
     
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilder;
     
    class BlocType extends AbstractType {
     
        public function buildForm(FormBuilder $builder, array $options) {
            $builder
                    ->add('nom', 'text', array(
                        'label' => 'bloc.field.name'
                    ))
                    ->add('description', "textarea", array(
                        'label' => 'bloc.field.description',
                        'required' => false,
                        'attr' => array('class' => 'ckeditor')))
     
                    ->add('photoFile', 'file', array(
                        'label' => 'bloc.field.picture',
                        'required' => false,
                    ))
                    ->add('lien', 'text', array(
                        'label' => 'bloc.field.link',
                        'required' => false,
                    ))
                    ->add('surligner', "checkbox", array(
                        'label' => 'bloc.field.highlight',
                        'required' => false
                    ));
        }
     
        public function getName() {
            return 'application_blocbundle_bloctype';
        }
     
        public function getDefaultOptions(array $options) {
            return array(
                'data_class' => 'Application\BlocBundle\Entity\Bloc',
            );
        }
     
    }
    http://www.anaprosy.be - Solution et réalisation informatique

  4. #4
    Membre éprouvé
    Homme Profil pro
    Inscrit en
    Juin 2011
    Messages
    725
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Juin 2011
    Messages : 725
    Points : 1 050
    Points
    1 050
    Par défaut
    Tu as paramétré ton entité pour que la méthode upload soit appelé sur le postUpdate et le postPersist (c'est à dire lorsque Doctrine décide de faire une requete SQL Insert ou Update).
    S'il n'y a pas de modification dans les champs persistant, Doctrine ne génere pas d'Update et par conséquent ta méthode upload n'est pas appelé.

    c'est d'ailleurs précisé dans la doc de Symfony sur l'upload avec Doctrine
    The PreUpdate and PostUpdate callbacks are only triggered if there is a change in one of the entity's field that are persisted. This means that, by default, if you modify only the $file property, these events will not be triggered, as the property itself is not directly persisted via Doctrine. One solution would be to use an updated field that's persisted to Doctrine, and to modify it manually when changing the file.
    tu peux
    - appeler upload directement dans le controleur
    - avoir une colonne persisté bidon qui est modifié lorsque l'on appelle la méthode setFile()
    - changer la façon dont Doctrine détermine qu'une entité a été modifié en utilisant le change tracking policies notify:
    http://docs.doctrine-project.org/pro...es.html#notify
    (je n'ai pas testé cette dernière méthode)

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. mise a jour champ calculer qui est stock
    Par popofpopof dans le forum Access
    Réponses: 20
    Dernier message: 23/08/2007, 00h21
  2. [WINDEV 11] Mise a jour Hyper File client serveur
    Par Bart51 dans le forum HyperFileSQL
    Réponses: 1
    Dernier message: 05/06/2007, 21h07
  3. requete de mise a jour champ date nul
    Par popofpopof dans le forum Access
    Réponses: 3
    Dernier message: 26/05/2007, 16h10
  4. TRIGGER - mise a jour champ de la table declencheur
    Par jane_ng dans le forum Oracle
    Réponses: 1
    Dernier message: 17/06/2006, 19h12
  5. recuperer valeur liste deroulante + mise a jour champs input
    Par dj_kyl dans le forum Général JavaScript
    Réponses: 4
    Dernier message: 31/03/2006, 18h42

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