简体   繁体   中英

Symfony2 Form File Upload into two entities

I have a form in symfony which I send to the server with ajax/xhr2. It includes a textfield and possible files (none or multiple allowed). Therefore I created an entity named "post" which holds the submitted text, the user who did it and the date/time. Plus it is associated with a OneToMany relationship to an entity named "upload".

class Post{

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="text")
 */
private $text;

/**
 * @ORM\Column(type="datetime")
 */
private $created;

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="posts")
 * @ORM\JoinColumn(name="users", referencedColumnName="id")
 *
 */
private $author;

/**
 * @ORM\OneToMany(targetEntity="Upload", mappedBy="post")
 */
private $uploads;

This entity holds all the relevant data on the uploaded file(s).

class Upload
{

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="string", length=30)
 */
private $name;

 /**
 * @ORM\Column(type="string", length=255)
 */
private $path;

/**
 * @ORM\Column(type="datetime")
 */
private $date;

/**
 * @ORM\Column(type="string", length=30)
 */
private $type;

/**
 * @ORM\Column(type="integer")
 */
private $size;

In the Upload entity I also placed the upload methods as explained on http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

Now when I persist my post, the post class tries to upload the file instead of leaving it form the upload class. Thus I get an error that no method setUploads exists in the post class. When I add it, I get the error that the method received an instance of UploadedFile instead of Upload.

Does anyone have good advice how I could upload files the way I modeled the classes or how to create a better model?

Thank you very much!

I wrote a fully explanation on how to upload files to Symfony2 here . As you guessed right, you need to add the method setUploads() to your Post entity. The uploaded file will be linked to the Upload entity not the Post itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM