SonataAdminBundle文件上传:错误 [英] SonataAdminBundle file upload: Error

查看:559
本文介绍了SonataAdminBundle文件上传:错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名学生,实际上是在自己的Symfony2项目上工作,现在几天我找不到解决问题的办法。

I'm a student actually working on my own Symfony2 project and it's few days now I can't find a solution to my problem.

更新:03.09。 2013

UPDATE: 03.09.2013

我拥有当前版本的symfony和sonata管理软件包,并需要一个表单在我的管理员多个图像上传。

I have the current version of symfony and of the sonata admin bundle and need a form in my admin with multiple image uploads.

我提供的以下代码基于此安装文档:

The following code I present is based on this installation documentation:

http://sonata-project.org/bundles/admin/master/doc/reference/recipe_file_uploads.html

在我的情况下,我的包中有一个实体项目(Pf\Bundle\BlogBu​​ndle\Entity\Projects.php)。在这个实体中,我有$ image1(相当于文档中的文件名),当然还有未映射的属性文件。所有的字符串和配置,因为它必须是。 (请注意,在我的案例中,我使用的是image1而不是文件名)。

In my case I have an entity Projects (Pf\Bundle\BlogBundle\Entity\Projects.php) in my bundle. In this entity I have $image1 (which is the equivalent of filename in the doc) and of course the unmapped property file. All strings and configured as it has to be. (Note that I use image1 instead of filename in my case // documentation).

<?php

namespace Pf\Bundle\BlogBundle\Entity;

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


/**
 * Projects
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Pf\Bundle\BlogBundle\Entity\ProjectRepository")
  * @ORM\HasLifecycleCallbacks()
 */
class Projects
{

    const SERVER_PATH_TO_IMAGE_FOLDER = '/uploads/medias';

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

    /**
     * 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(
            Projects::SERVER_PATH_TO_IMAGE_FOLDER,
            $this->getFile()->getClientOriginalName()
        );

        // set the path property to the filename where you've saved the file
        $this->image1 = $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(date('Y-m-d H:i:s'));
    }

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

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

    //...

    /**
     * @var datetime
     *
     * @ORM\Column(name="updated", nullable=true)
     */
    private $updated;

     /**
     * Set updated
     *
     * @param string $updated
     * @return Projects
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

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

我还有一个管理控制器(Pf\Bundle \BlogBu​​ndle\Admin\ProjectsAdmin.php)其中我有以下表单(在sonata管理方式中创建):

I also have an admin controller (Pf\Bundle\BlogBundle\Admin\ProjectsAdmin.php) where I have the following form (created in the "sonata admin way"):

<?php
namespace Pf\Bundle\BlogBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Validator\ErrorElement;

use Sonata\AdminBundle\Form\FormMapper;

class ProjectsAdmin extends Admin
{
    // setup the default sort column and order
    protected $datagridValues = array(
        '_sort_order' => 'DESC',
        '_sort_by' => 'id'
    );

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('file', 'file', array('required' => false, 'data_class' => null))
            ->add('image2',  'text')
            ->add('image3', 'text')
            ->add('link', 'text')
            ->add('download_link', 'text')
            ->add('content1', 'text')
            ->add('content2', 'text')
            ->add('title', 'text')
            ->add('thumbnail', 'text')
        ;
    }

    public function prePersist($projects) {
        $this->manageFileUpload($projects);
    }

    public function preUpdate($projects) {
        $this->manageFileUpload($projects);
    }

    private function manageFileUpload($projects) {
        if ($projects->getFile()) {
            $projects->refreshUpdated();
        }
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('title')
        ;
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('title')
        ;
    }
}

我有几个问题:


  • 如果我尝试创建一个新项目,image1似乎是空的
    每次我尝试上传。我可以使其在实体中为空,但
    那么我根本就不会在数据库中获取任何url

  • If I try to CREATE A NEW project, the image1 appears to be null every time I try to upload. I can make it nullable in the entity but then I don't get any url at all in the database

执行INSERT INTO Projects时发生异常...
完整性约束违规:1048列'image1'不能为空

An exception occurred while executing 'INSERT INTO Projects... Integrity constraint violation: 1048 Column 'image1' cannot be null

通过在管理员中编辑现有项目,似乎工作..well几乎。我上传文件时没有任何错误,但是我在数据库中获得一个临时路径,没有文件已被移动到好的文件夹。

By editing an existing project in the admin, it seems to work..well nearly..I don't get any errors when uploading the file BUT I get a temporary path in the database and no file has been moved in the good folder.

看起来上传功能没有被调用。我尝试调试它,但找不到解决方案。

It looks like the upload function isn't called. I try to debug it but can't find a solution.

我已经按照一步一步的文档。唯一的区别是我不使用任何.yaml文件配置我的实体..我必须?我在symfony上使用注释,我想在同一时间使用orm.yaml和注释是不好的...对吗?

I have followed step by step the documentation. The only difference is that I don't use any .yaml file to configure my entity.. Does I have to? I'm using annotations on my symfony, I guess it's not good to use orm.yaml and annotation in the same time...right?

任何帮助超过欢迎!

推荐答案

这个话题的任何信息
你看过 http://symfony.com/doc/current/cookbook/form/form_collections.html

您应该将图像表单嵌入到父表单中。例如,

You should embed image form into the parent form. For instance,

- > add('myImage','collection',array('type'=> new MyImageType() )

而不是放置多个image1,image2,...使另一个表单类,例如。 MyImageType()并将其作为集合类型添加到现有的表单中。

Instead of putting multiple image1, image2,... make another form class, eg. MyImageType() and add it as a collection type in to an existing form.

在这个方向上工作,祝你好运。

Work in that direction, good luck.

这篇关于SonataAdminBundle文件上传:错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆