簡體   English   中英

上傳到多多多關系symfony2

[英]upload to manytomany relationship symfony2

我有一個與圖片具有多對多關系的對象“內容”(圖片模型)。 一切正常,直到我堅持(將圖像上傳,移動到適當的文件夾后,一切正常)。 persist命令返回以下錯誤:

在關聯Creator \\ MainBundle \\ Entity \\ Content#pictures上找到類型為Symfony \\ Component \\ HttpFoundation \\ File \\ UploadedFile的實體,但是期望Creator \\ MainBundle \\ Entity \\ Picture

我了解錯誤的含義,它期望的是Picture對象而不是上載的文件對象。 不過,我不知道從哪里去,我只讀的所有文檔都顯示了如何將單個文件上傳到單個列。

圖片模型只有一個字段:文件(字符串)。

任何幫助將非常感激。

內容控制器代碼:

$form = $this->createFormBuilder($content, array('validation_groups'=>array('upload_'.$type)))
        ->add('picture')
        ->add('Upload '.ucfirst($type), 'submit')
        ->getForm();

$form->handleRequest($request);

if($request->getMethod()=='POST' && $form->isvalid())
{
    $content->uploadPicture();
    $em->persist($content);
    $em->flush();

    $session = $request->getSession();
    $session->getFlashBag()->add('success', 'Upload successful');                   
}

內容模型代碼:

public function addPictures($picture)
{
    $this->pictures[] = $picture;
    return $this;
}

public function getPicture()
{
    return $this->picture;
}

public function setPicture($picture)
{
    $this->picture = $picture;
    return $this;
}

public function getPictures()
{
    return $this->pictures;
}

public function setPictures($pictures)
{
    $this->pictures = $pictures;
    return $this;
}

public function uploadPicture()
{       
    if (null === $this->getPicture()) {
        return;
    }

    $extension = $this->getPicture()->getExtension();
    if(!$extension) $extension = 'jpg';

    // unique file name
    $fname = uniqid().'.'.$extension;

    $this->getPicture()->move(
        $this->getUploadRootDir(),
        $fname
    );

    $this->makeThumbnail($fname, $extension);
    $this->addPictures($this->getPicture());
}

好吧,我知道了。

$picture = new Picture();

$form = $this->createFormBuilder($picture)
    ->add('file')
    ->add('Upload Picture', 'submit')
    ->getForm();

$form->handleRequest($request);

if($request->getMethod()=='POST' && $form->isvalid())
{
  $picture->uploadFile();
  $em->persist($picture);
  $content->addPicture($entity);
  $em->persist($content);
  $em->flush();
}

將上載函數移到了Picture實體。.還必須在Content實體中重命名幾個函數,但是如果有人嘗試復制我所做的事情,這應該是不顯而易見的。.現在它很好用並插入了關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM