简体   繁体   中英

how upload in Blog Entity in SonataAdminBundle?

I am new symfony, and I try upload img in SonataAdminBundle.I folow this documentation: http://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_file_uploads.html But I got error:

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

Can anybody help me with it?

My Blog Entity: //src/MyBLogBundle/Entity/Blog.php class Blog {

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"));
}

}

my BlogAdmin: namespace 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();
        }
    }
}

and Blog.orm.yml

src/MyBlogBundle/Resources/config/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 ]

You forgot to add the use statement for the UploadedFile class, you must add :

src/MyBLogBundle/Entity/Blog.php

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

class Blog
{
}

You need to specify where is located the UploadedFile if it's not in the default namespace of your file (currently : src/MyBLogBundle/Entity)

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