caramba
caramba

Reputation: 22490

Multiple file upload not saving each path in database

I have ActivityFile Entity which should handle files:

class ActivityFile {

    // all properties / setters / getters and so on

    public function upload()
    {
        foreach($this->uploadedFiles as $uploadedFile) {

            $fileName = md5(uniqid()) . '.' . $uploadedFile->getClientOriginalName();

            $uploadedFile->move(
                $this->getUploadRootDir(),
                $fileName
            );

            $this->path = $fileName;
            $this->name = $uploadedFile->getClientOriginalName();

            $this->setRealPath($this->getUploadDir() . '/' . $fileName);

            $this->file = null;
        }
    }

That works fine. I'll get all uploaded files in the desired folder.

Problem is, I don't get the data in Database. Because of my Controller:

    class DashboardController extends Controller
    {
        public function indexAction(Request $request)
        {
            $activityFile = new ActivityFile();
            $activityFile->setUser($this->getUser());

            $form = $this->createFormBuilder($activityFile)
                ->add('uploadedFiles', FileType::class, array(
                    'multiple' => true,
                    'data_class' => null,
                ))
                ->add('save', SubmitType::class, array('label' => 'Upload'))
                ->getForm();

            $form->handleRequest($request);

            if ($form->isValid()) {

                $em = $this->getDoctrine()->getManager();

                // here is PROBLEM
                // $activityFile only contains the last file
                // from selected upload files

                $activityFile->upload();

                $em->persist($activityFile);


                $em->flush();

                return $this->redirect($this->generateUrl('dashboard'));
            }

            return $this->render('ACMEBundle:Dashboard:index.html.twig', array(
                'form' => $form->createView(), 'activityFile' => $activityFile
            ));
        }
    }

How can I do the Database Entry for each uploaded file?

Upvotes: 2

Views: 190

Answers (1)

wookieb
wookieb

Reputation: 4489

You're moving all uploaded files to destination directory but the result of this operation is being stored in a property that is not an array but string. You just simply override it every time.

$this->path = $fileName;

Change the structure of your ActivityFile to store list of files not only one.

Otherwise create multiple ActivityFiles for every uploaded file using collection form type http://symfony.com/doc/current/reference/forms/types/collection.html

Upvotes: 2

Related Questions