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 :

Upload de plusieurs fichiers [2.x]


Sujet :

Symfony PHP

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Août 2007
    Messages
    26
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2007
    Messages : 26
    Points : 12
    Points
    12
    Par défaut Upload de plusieurs fichiers
    Bonjour à tous,

    Je débute avec Symfony2 et j'essaie de développer une application qui consiste à créer des projets et leur associer une entreprise. L'utilisateur peut créer, éditer et visualiser les données dans un tableau.

    j'ai un problème qui me bloque depuis plusieurs jours. Dans un formulaire, j'aimerais que l'utilisateur puisse uploader plusieurs fichiers via un champ "file". Les fichiers sont stockés sur le serveur et leurs URL dans un champ de la base de donnée.
    Actuellement, j'ai cette erreur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Expected argument of type "string or Symfony\Component\Form\FormTypeInterface", "array" given
    Voici mon code :
    Entity :
    Code Project.php : 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
    <?php
     
    namespace Vestnieciba\ComDbBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
     
    /**
     * Vestnieciba\ComDbBundle\Entity\Project
     *
     * @ORM\Table()
     * @ORM\HasLifecycleCallbacks
     * @ORM\Entity(repositoryClass="Vestnieciba\ComDbBundle\Entity\ProjectRepository")
     */
    class Project
    {
    /**
         * @var object $files
         * @Assert\File()
         * @ORM\Column(type="array", length=255, nullable=true)
         */
        public $files;
    /**
         * Set files
         *
         * @param object $files
         */
        public function setFiles(array $files)
        {
            $this->files = $files;
        }
     
        /**
         * Get files
         *
         * @return object 
         */
        public function getFiles()
        {
            return $this->files;
        }
     
        public function __construct() 
        {
            $files = array();
        }
    /**
        * Upload files
        *
        */
        public function getFullFilesPath() {
            return null === $this->files ? null : $this->getUploadRootDir(). $this->files;
        }
     
        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/files/';
        }
     
        /**
         * @ORM\PrePersist()
         * @ORM\PreUpdate()
         */
        public function uploadFiles() {
            // the files property can be empty if the field is not required
            if (null === $this->files) {
                return;
            }
            if(!$this->id){
                $this->files->move($this->getTmpUploadRootDir(), $this->files->getClientOriginalName());
            }else{
                $this->files->move($this->getUploadRootDir(), $this->files->getClientOriginalName());
            }
            $this->setFiles($this->files->getClientOriginalName());
        }
     
        /**
         * @ORM\PostPersist()
         */
        public function moveFiles()
        {
            if (null === $this->files) {
                return;
            }
            if(!is_dir($this->getUploadRootDir())){
                mkdir($this->getUploadRootDir());
            }
            copy($this->getTmpUploadRootDir().$this->files, $this->getFullFilesPath());
            unlink($this->getTmpUploadRootDir().$this->files);
        }
     
        /**
         * @ORM\PreRemove()
         */
        public function removeFiles()
        {
            unlink($this->getFullFilesPath());
            rmdir($this->getUploadRootDir());
        }
    }

    Controller :
    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
    <?php
     
    namespace Vestnieciba\ComDbBundle\Controller;
     
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\File\UploadedFile;
    use Vestnieciba\ComDbBundle\Entity\Project;
    use Vestnieciba\ComDbBundle\Form\ProjectType;
    use Symfony\Component\Finder\Finder;
     
    /**
     * Project controller.
     *
     */
    class ProjectController extends Controller
    {
        /**
         * Lists all Project entities.
         *
         */
        public function indexAction()
        {
            $em = $this->getDoctrine()->getEntityManager();
     
            $entities = $em->getRepository('VestniecibaComDbBundle:Project')->findAll();
     
            return $this->render('VestniecibaComDbBundle:Project:index.html.twig', array(
                'entities'  => $entities
            ));
        }
     
        /**
         * Finds and displays a Project entity.
         *
         */
        public function showAction($id)
        {
            $em = $this->getDoctrine()->getEntityManager();
     
            $entity = $em->getRepository('VestniecibaComDbBundle:Project')->find($id);
     
            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Project entity.');
            }
     
            $deleteForm = $this->createDeleteForm($id);
     
            return $this->render('VestniecibaComDbBundle:Project:show.html.twig', array(
                'entity'      => $entity,
                'delete_form' => $deleteForm->createView(),
     
            ));
        }
     
        /**
         * Displays a form to create a new Project entity.
         *
         */
        public function newAction()
        {
            $entity = new Project();
            $form   = $this->createForm(new ProjectType(), $entity);
     
            return $this->render('VestniecibaComDbBundle:Project:new.html.twig', array(
                'entity' => $entity,
                'form'   => $form->createView()
            ));
        }
     
        /**
         * Creates a new Project entity.
         *
         */
       public function createAction()
        {
            $entity  = new Project();
            $form = $this->createForm(new Create(), $entity);
            $formView = $form->createView();
            $formView->getChild('files')->set('full_name', 'ProjectType[files][]');
     
            $request = $this->getRequest();
            if($request->getMethod() == "POST")
            {
                $form->bindRequest($request);
     
                if ($form->isValid()) {
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($entity);
                $em->flush();
     
                return $this->redirect($this->generateUrl('project_show', array('id' => $entity->getId())));
     
                }
            }        
     
            return $this->render('VestniecibaComDbBundle:Project:new.html.twig', array("form" => $formView));
        }
     
        /**
         * Displays a form to edit an existing Project entity.
         *
         */
        public function editAction($id)
        {
            $em = $this->getDoctrine()->getEntityManager();
     
            $entity = $em->getRepository('VestniecibaComDbBundle:Project')->find($id);
     
            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Project entity.');
            }
     
            $editForm = $this->createForm(new ProjectType(), $entity);
            $deleteForm = $this->createDeleteForm($id);
     
            return $this->render('VestniecibaComDbBundle:Project:edit.html.twig', array(
                'entity'      => $entity,
                'edit_form'   => $editForm->createView(),
                'delete_form' => $deleteForm->createView(),
            ));
        }
     
        /**
         * Edits an existing Project entity.
         *
         */
        public function updateAction($id)
        {
            $em = $this->getDoctrine()->getEntityManager();
     
            $entity = $em->getRepository('VestniecibaComDbBundle:Project')->find($id);
     
            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Project entity.');
            }
     
            $editForm   = $this->createForm(new ProjectType(), $entity);
            $deleteForm = $this->createDeleteForm($id);
     
            $request = $this->getRequest();
     
            $editForm->bindRequest($request);
     
            if ($editForm->isValid()) {
                $em->persist($entity);
                $em->flush();
     
                return $this->redirect($this->generateUrl('project_edit', array('id' => $id)));
            }
     
            return $this->render('VestniecibaComDbBundle:Project:edit.html.twig', array(
                'entity'      => $entity,
                'edit_form'   => $editForm->createView(),
                'delete_form' => $deleteForm->createView(),
            ));
        }
     
        /**
         * Deletes a Project entity.
         *
         */
        public function deleteAction($id)
        {
            $form = $this->createDeleteForm($id);
            $request = $this->getRequest();
     
            $form->bindRequest($request);
     
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getEntityManager();
                $entity = $em->getRepository('VestniecibaComDbBundle:Project')->find($id);
     
                if (!$entity) {
                    throw $this->createNotFoundException('Unable to find Project entity.');
                }
     
                $em->remove($entity);
                $em->flush();
            }
     
            return $this->redirect($this->generateUrl('project'));
        }
     
        private function createDeleteForm($id)
        {
            return $this->createFormBuilder(array('id' => $id))
                ->add('id', 'hidden')
                ->getForm()
            ;
        }
    }
    Le formulaire :
    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
    <?php
     
    namespace Vestnieciba\ComDbBundle\Form;
     
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilder;
     
     
    class ProjectType extends AbstractType
    {
        public function buildForm(FormBuilder $builder, array $options)
        {
            $builder->add('files', 'file', array('label' => 'Files', 'required' => false, 'multiple' => true));
        }
     
        public function getName()
        {
            return 'vestnieciba_comdbbundle_projecttype';
        }
    }
    et la vue Twig :
    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
    {% extends "::base.html.twig" %}
    {% block body %}
    <h1>Project edit</h1>
     
    <form action="{{ path('project_update', { 'id': entity.id }) }}" method="post" {{ form_enctype(edit_form) }}>
        {{ form_errors(edit_form) }}
     
        <ol>
          <li>
            {{ form_label(edit_form.files, "Files") }}
            {{ form_errors(edit_form.files) }}
            {{ form_widget(edit_form.files) }}
          </li>
        </ol>
     
        {{ form_rest(edit_form) }}
    </form>
     
    <ul class="record_actions">
        <li>
            <a href="{{ path('project') }}">
                Back to the list
            </a>
        </li>
        <li>
            <form action="{{ path('project_delete', { 'id': entity.id }) }}" method="post">
                {{ form_widget(delete_form) }}
                <button type="submit">Delete</button>
            </form>
        </li>
    </ul>
    {% endblock %}
    J'ai réussi avec 1 seul fichier mais avec plusieurs je n'arrive à rien.

    Merci d'avance pour votre aide !

  2. #2
    Membre à l'essai
    Profil pro
    Inscrit en
    Août 2007
    Messages
    26
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2007
    Messages : 26
    Points : 12
    Points
    12
    Par défaut
    J'ai posté mon problème sur le forum de Symfony2, voilà la réponse si jamais ça intéresse quelqu'un :

    Type "file" is just a special subtype of a string. This is what is generating your error.
    The thing is that Symfony's forms aren't prepared to handle multiple file uploads. So either you do it by Ajax, and use a paralel controller to handle that, or you upload a file by POST, and do some controller mojo jojo to append the file name to your array.

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

Discussions similaires

  1. [Upload] upload de plusieurs fichiers
    Par jc_cornic dans le forum Langage
    Réponses: 7
    Dernier message: 12/07/2010, 17h33
  2. [Upload] Upload de plusieurs fichiers via formulaire
    Par seb67110 dans le forum Langage
    Réponses: 2
    Dernier message: 02/05/2007, 11h55
  3. Réponses: 6
    Dernier message: 01/04/2007, 18h39
  4. Réponses: 10
    Dernier message: 12/06/2006, 16h45
  5. Réponses: 3
    Dernier message: 21/02/2006, 16h43

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