18

Symfony2 を使用しています。タイトルと画像フィールドを持つエンティティPostがあります。

私の問題:投稿を作成するときはすべて問題ありませんが、写真などがあります。しかし、それを変更したい場合、アップロードされたファイルである「写真」フィールドに問題があり、Symfony はファイルタイプを必要としています。文字列 (アップロードされたファイルのパス) :

The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File. 

私は本当にこの問題に悩まされており、解決方法が本当にわかりません。どんな助けでも大歓迎です! どうもありがとう!

これが私のPostType.php ( newAction() と modifiyAction() で使用される) であり、問​​題を引き起こす可能性があります ( Form/PostType.php ):

<?php
namespace MyBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;

use MyBundle\Entity\Post;

class PostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('title')
        ->add('picture', 'file');//there is a problem here when I call the modifyAction() that calls the PostType file.
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'MyBundle\Entity\Post',
        );
    }

    public static function processImage(UploadedFile $uploaded_file, Post $post)
    {
        $path = 'pictures/blog/';
        //getClientOriginalName() => Returns the original file name.
        $uploaded_file_info = pathinfo($uploaded_file->getClientOriginalName());
        $file_name =
            "post_" .
            $post->getTitle() .
            "." .
            $uploaded_file_info['extension']
            ;

        $uploaded_file->move($path, $file_name);

        return $file_name;
    }

    public function getName()
    {
        return 'form_post';
    }
}

ここに私の投稿エンティティEntity/Post.php)があります:

<?php

namespace MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

use Symfony\Component\Validator\Constraints as Assert;

/**
 * MyBundle\Entity\Post
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Post
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\Image(
     *      mimeTypesMessage = "Not valid.",
     *      maxSize = "5M",
     *      maxSizeMessage = "Too big."
     *      )
     */
    private $picture;

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

   //getters and setters
   }

これが私のnewAction() ( Controller/PostController.php )です。すべてこの関数で正常に動作します

public function newAction()
{
    $em = $this->getDoctrine()->getEntityManager();
    $post = new Post();
    $form = $this->createForm(new PostType, $post);
    $post->setPicture("");
    $form->setData($post);
    if ($this->getRequest()->getMethod() == 'POST') 
    {
        $form->bindRequest($this->getRequest(), $post);
        if ($form->isValid()) 
        {
            $uploaded_file = $form['picture']->getData();
            if ($uploaded_file) 
            {
                $picture = PostType::processImage($uploaded_file, $post);
                $post->setPicture('pictures/blog/' . $picture);
            }
            $em->persist($post);
            $em->flush();
            $this->get('session')->setFlash('succes', 'Post added.');

            return $this->redirect($this->generateUrl('MyBundle_post_show', array('id' => $post->getId())));
        }
    }

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

これが私のmodifyAction()Controller/PostController.php)です:この関数には問題があります

public function modifyAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();
    $post = $em->getRepository('MyBundle:Post')->find($id);
    $form = $this->createForm(new PostType, $post);//THIS LINE CAUSES THE EXCEPTION
    if ($this->getRequest()->getMethod() == 'POST') 
    {
        $form->bindRequest($this->getRequest(), $post);
        if ($form->isValid()) 
        {
            $uploaded_file = $form['picture']->getData();
            if ($uploaded_file) 
            {
                $picture = PostType::processImage($uploaded_file, $post);
                $post->setPicture('pictures/blog/' . $picture);
            }
            $em->persist($post);
            $em->flush();
            $this->get('session')->setFlash('succes', 'Modifications saved.');

            return $this->redirect($this->generateUrl('MyBundle_post_show', array('id' => $post->getId())));
        }
    }
    return $this->render('MyBundle:Post:modify.html.twig', array('form' => $form->createView(), 'post' => $post));
}
4

3 に答える 3

44

問題の設定data_classnull次のように解決しました。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('title')
    ->add('picture', 'file', array('data_class' => null)
    );
}
于 2013-03-21T11:07:32.997 に答える
3

SymfonyとDoctrineを使用したファイルアップロードのドキュメントを読むことをお勧めします。Doctrineを使用したファイルアップロードの処理方法と、ライフサイクルコールバックの一部に対する強力な推奨事項

簡単に言うと、通常、フォームでは「file」変数を使用し(ドキュメントを参照)、オプションに別のラベルを付けることができます。次に、「picture」フィールドに、必要なときにファイルの名前を保存するだけです。 getWebpath()メソッドを呼び出すだけのsrcファイル。

->add('file', 'file', array('label' => 'Post Picture' )
);

小枝テンプレートを呼び出す

<img src="{{ asset(entity.webPath) }}" />
于 2013-02-01T15:55:02.900 に答える
1

PostType.phpで以下の変更を行ってください。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('title')
    ->add('picture', 'file', array(
            'data_class' => 'Symfony\Component\HttpFoundation\File\File',
            'property_path' => 'picture'
        )
    );
}
于 2013-01-20T12:03:35.580 に答える