2015-03-18 2 views
0

Я новичок Symfony, и я пытаюсь загрузить в IMG SonataAdminBundle.I Folow эту документацию: http://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_file_uploads.html Но я получил ошибку:Как загрузить в Blog Entity в SonataAdminBundle?

Catchable Fatal Error: Argument 1 passed to MyBlogBundle\Entity\Blog::setFile() must be an instance of MyBlogBundle\Entity\UploadedFile, instance of Symfony\Component\HttpFoundation\File\UploadedFile given, called in C:\OpenServer\domains\Symfony.test\vendor\symfony\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php on line 442 and defined

Может кто-нибудь помочь мне с этим?

Мой блог Entity: //src/MyBLogBundle/Entity/Blog.php класс Блог {

const SERVER_PATH_TO_IMAGE_FOLDER = 'src/MyBlogBundle/Resources/public/images'; 

/** 
* Unmapped property to handle file uploads 
*/ 
private $file; 

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

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

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

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

/** 
* @var \DateTime 
* 
* @ORM\Column(name="createDate", type="datetime") 
*/ 
private $createDate; 

/** 
* @var \DateTime 
* 
* @ORM\Column(name="updateDate", type="datetime") 
*/ 
private $updateDate; 

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

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

/** 
* 
* @ORM\OneToMany(targetEntity="Comment",mappedBy="blog") 
*/ 
private $comment; 

/** 
* Get id 
* 
* @return integer 
*/ 
public function getId() { 
    return $this->id; 
} 

/** 
* Set author 
* 
* @param string $author 
* @return Blog 
*/ 
public function setAuthor($author) { 
    $this->author = $author; 

    return $this; 
} 

/** 
* Get author 
* 
* @return string 
*/ 
public function getAuthor() { 
    return $this->author; 
} 

/** 
* Set title 
* 
* @param string $title 
* @return Blog 
*/ 
public function setTitle($title) { 
    $this->title = $title; 

    return $this; 
} 

/** 
* Get title 
* 
* @return string 
*/ 
public function getTitle() { 
    return $this->title; 
} 

/** 
* Set text 
* 
* @param string $text 
* @return Blog 
*/ 
public function setText($text) { 
    $this->text = $text; 

    return $this; 
} 

/** 
* Get text 
* 
* @return string 
*/ 
public function getText($count = NULL) { 
    if ($count != NULL) { 
     $arr = explode(' ', $this->text); 
     $arr = array_slice($arr, 0, $count); 
     $this->text = implode(' ', $arr) . '...'; 
    } 
    return $this->text; 
} 

/** 
* Set createDate 
* @ORM\PrePersist 
* @param \DateTime $createDate 
* @return Blog 
*/ 
public function setCreateDate() { 
    $this->createDate = new \DateTime(); 

    return $this; 
} 

/** 
* Get createDate 
* 
* @return \DateTime 
*/ 
public function getCreateDate() { 
    return $this->createDate; 
} 

/** 
* Set updateDate 
* @ORM\PreUpdate 
* @param \DateTime $updateDate 
* @return Blog 
*/ 
public function setUpdateDate() { 
    $this->updateDate = new \DateTime(); 
    return $this; 
} 
/** 
* Get updateDate 
* 
* @return \DateTime 
*/ 
public function getUpdateDate() { 
    return $this->updateDate; 
} 

/** 
* Set image 
* 
* @param string $image 
* @return Blog 
*/ 
public function setImage($image) { 
    $this->image = $image; 

    return $this; 
} 
/** 
* Get image 
* 
* @return string 
*/ 
public function getImage() { 
    return $this->image; 
} 

/** 
* Set tag 
* 
* @param string $tag 
* @return Blog 
*/ 
public function setTag($tag) { 
    $this->tag = $tag; 

    return $this; 
} 

/** 
* Get tag 
* 
* @return string 
*/ 
public function getTag() { 
    return $this->tag; 
} 

public function __construct() { 
    $this->comment = new ArrayCollection(); 
    $this->updateDate = new \DateTime(); 
} 

/** 
* Add comment 
* 
* @param \MyBlogBundle\Entity\Comment $comment 
* @return Blog 
*/ 
public function addComment(\MyBlogBundle\Entity\Comment $comment) { 
    $this->comment[] = $comment; 

    return $this; 
} 

/** 
* Remove comment 
* 
* @param \MyBlogBundle\Entity\Comment $comment 
*/ 
public function removeComment(\MyBlogBundle\Entity\Comment $comment) { 
    $this->comment->removeElement($comment); 
} 

/** 
* Get comment 
* 
* @return \Doctrine\Common\Collections\Collection 
*/ 
public function getComment() { 
    return $this->comment; 
} 

/** 
* Sets file. 
* 
* @param UploadedFile $file 
*/ 
public function setFile(UploadedFile $file = null) { 
    $this->file = $file; 
} 

/** 
* Get file. 
* 
* @return UploadedFile 
*/ 
public function getFile() { 
    return $this->file; 
} 

/** 
* Manages the copying of the file to the relevant place on the server 
*/ 
public function upload() { 
    // the file property can be empty if the field is not required 
    if (null === $this->getFile()) { 
     return; 
    } 

    // we use the original file name here but you should 
    // sanitize it at least to avoid any security issues 
    // move takes the target directory and target filename as params 
    $this->getFile()->move(
      Image::SERVER_PATH_TO_IMAGE_FOLDER, $this->getFile()->getClientOriginalName() 
    ); 

    // set the path property to the filename where you've saved the file 
    $this->filename = $this->getFile()->getClientOriginalName(); 

    // clean up the file property as you won't need it anymore 
    $this->setFile(null); 
} 

/** 
* Lifecycle callback to upload the file to the server 
*/ 
public function lifecycleFileUpload() { 
    $this->upload(); 
} 

/** 
* Updates the hash value to force the preUpdate and postUpdate events to fire 
*/ 
public function refreshUpdated() { 
    $this->setUpdated(new \DateTime("now")); 
} 

} 

мой BlogAdmin: имен MyBlogBundle \ Admin;

use Sonata\AdminBundle\Admin\Admin; 
use Sonata\AdminBundle\Datagrid\ListMapper; 
use Sonata\AdminBundle\Datagrid\DatagridMapper; 
use Sonata\AdminBundle\Form\FormMapper; 

class BlogAdmin extends Admin 
{ 
    protected $baseRouteName = 'MyBlogBundle\Entity\BlogAdmin'; 
    protected $baseRoutePattern = 'blog_admin'; 

    protected function configureFormFields(FormMapper $formMapper) 
    { 
     $formMapper 
      ->add('title', 'text', array('label' => 'Blog Title')) 
      ->add('tag','text') 
      ->add('file', 'file', array('required' => false)) 
      ->add('text','textarea') //if no type is specified, SonataAdminBundle tries to guess it 
      ->add('author') 
     ; 
    } 
    protected function configureDatagridFilters(DatagridMapper $datagridMapper) 
    { 
     $datagridMapper 
      ->add('title') 
      ->add('author') 
     ; 
    } 
    protected function configureListFields(ListMapper $listMapper) 
    { 
     $listMapper 
      ->addIdentifier('title') 
      ->add('author') 
     ; 
    } 

    public function prePersist($image) { 
     $this->manageFileUpload($image); 
    } 
    public function preUpdate($image) { 
     $this->manageFileUpload($image); 
    } 
    private function manageFileUpload($image) { 
     if ($image->getFile()) { 
      $image->refreshUpdated(); 
     } 
    } 
} 

и Blog.orm.yml

SRC/MyBlogBundle/Ресурсы/конфигурации/Doctrine/Image.orm.yml

MyBlogBundle\Entity\Image: 
    type: entity 
    repositoryClass: MyBlogBundle\Entity\Repositories\ImageRepository 
    table: images 
    id: 
    id: 
     type:   integer 
     generator: { strategy: AUTO } 
    fields: 
    filename: 
     type:   string 
     length:  100 
    updated:  # changed when files are uploaded, to force preUpdate and postUpdate to fire 
     type:   datetime 
     nullable:  true 
    # ... other fields ... 
    lifecycleCallbacks: 
     prePersist: [ lifecycleFileUpload ] 
     preUpdate: [ lifecycleFileUpload ] 

ответ

0

Вы забыли добавить использовать заявление для класса UploadedFile , вы должны добавить:

SRC/MyBLogBundle/Entity/blog.php

<?php 
use Symfony\Component\HttpFoundation\File\UploadedFile; 

class Blog 
{ 
} 

Вы должны указать где находится UploadedFile, если это не в пространстве имен по умолчанию файла (в настоящее время: SRC/MyBLogBundle/Entity)

+0

Это помогло мне, но потом была еще одна ошибка: Пытался позвонить метод «setUpdated» в классе «MyBlogBundle \ Entity \ Blog». – YuriiChmil

+0

Я добавил новое значение пропорциональности и метод setUpdated и getUpdated: Но если я попытаюсь снова добавить новую ошибку post posture: произошла ошибка во время создания элемента «MyBlogBundle \ Entity \ Blog: 0000000018b75cc6000000001badb528». – YuriiChmil

+0

Я оштрафовал свои ошибки: repositoryClass: MyBlogBundle \ Entity \ Repositories \ ImageRepository -ImageRepository необходимо заменить на BlogRepository и добавить -> добавить ('image', 'file', array ( 'data_class' => NULL)) – YuriiChmil

Смежные вопросы