Формы Симфонии. Файл загружен

Пытаюсь управлять загрузкой файлов с помощью Entity, но получаю эту ошибку:

Неустранимая ошибка: вызов функции-члена move() для необъекта в /home/projectpath/src/BS/MyBundle/Entity/Items.php в строке 327 Стек вызовов: 0,0002 333264 1. {main}() /home /projectpath/web/app_dev.php:0 0,0450 1158160...

Вот класс сущности:

namespace BS\BackstretcherBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;

/**
* MB\MyBundle\Entity\Items
*
* @ORM\Table(name="items")
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Items
{
    private $filenameForRemove;

    /**
     * @Assert\File(maxSize="60000000")
     */
    public $file;
    ...

    protected function getUploadDir()
    {
       return 'images/items/';
    }

    protected function getUploadRootDir()
    {
      return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    public function getWebPath()
    {
      return null === $this->file ? null : $this->getUploadDir().'/'.$this->getNameEn();
    }

    public function getAbsolutePath()
    {
      return null === $this->file ? null : $this->getUploadRootDir().'/'.$this->getNameEn().'.jpg';
    }

  /**
   * @ORM\PrePersist()
   * @ORM\PreUpdate()
   */
    public function preUpload()
    {
      if (null !== $this->file)
      {
         $this->file = $this->getId() .'.'. $this->file->guessExtension();
      }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
      if (null === $this->file)
      {
        return;
      }

      $this->file->move($this->getUploadRootDir(), $this->file);
      unset($this->file);
    }

    /**
     * @ORM\PostRemove()
     */
     public function removeUpload()
     {
       if ($file = $this->getAbsolutePath())
       {
         unlink($file);
       }
     }

И контроллер:

public function new_productAction(Request $request)
{
  $product = new Items();
  $product->setPrice(0);

  $form = $this->createFormBuilder($product)
    ->add('Type', 'choice', array(
      'choices'   => array('1' => 'Product', '0' => 'Article'),
      'required'  => false,))
    ->add('Price',  'number')
    ->add('nameEn', 'text')
    ->add('file', 'file', array('label' => 'Image', 'required' => true))
    ->getForm();

  if ($request->getMethod() == 'POST')
  {
    if ($form->isValid())
    {
      $form->bindRequest($request);
      $em = $this->getDoctrine()->getEntityManager();
      $em->persist($product);
      $em->flush();

      return new Response('<html><body>Success!</body></html>');
    }
  }

  return $this->render('MyBundle:Default:admin_page.html.twig', array(
    'form' => $form->createView(),
  ));
}

Версия Symfony: 2.1.0


person duke_nukem    schedule 28.07.2012    source источник


Ответы (3)


Проверьте свой файл php.ini и убедитесь, что параметры post_max_size и upload_max_filesize достаточно велики.

person Tac Tacelosky    schedule 03.08.2012

Я не думаю, что duke_nukem больше беспокоится об этом через 6 месяцев, но если кто-то еще столкнется с этим вопросом, у меня была точно такая же проблема, и я получил отличный ответ здесь:

Ошибка загрузки файла в symfony 2

Похоже, мы с duke_nukem совершили ту же ошибку. Метод preUpload() должен выглядеть так:

  /**
   * @ORM\PrePersist()
   * @ORM\PreUpdate()
   */
    public function preUpload()
    {
      if (null !== $this->file)
      {
         $this->path = $this->getId() .'.'. $this->file->guessExtension();
      }
    }

Настоящий код преобразует $this->file в строку, вызывая ошибку. На самом деле путь должен быть назначен $this->path.

Сибио в другом вопросе понял это, а не я. Я просто хочу распространять любовь.

person eimajenthat    schedule 09.01.2013

это странно

ваш код неверен в вашем контроллере. Вы должны привязать свой запрос к форме перед проверкой. После этого вы можете получить свои данные

if ($request->getMethod() == 'POST')
  {
    //Note: bindRequest is now deprecated
    $form->bind($request);
    if ($form->isValid())
    {
      //retrieve your model hydrated with your form values
      $product = $form->getData();

      //has upload file ?
      if($product->getFile() instanceof UploadedFile){
        //you can do your upload logic here wihtout doctrine event if you want
      }

      $em = $this->getDoctrine()->getEntityManager();
      $em->persist($product);
      $em->flush();

      return new Response('<html><body>Success!</body></html>');
    }
  }
person Julien Rollin    schedule 15.02.2013