【问题标题】:SonataAdminBundle file upload: ErrorSonataAdminBundle 文件上传:错误
【发布时间】:2013-08-28 15:28:34
【问题描述】:

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

更新:03.09.2013

我有当前版本的 symfony 和奏鸣曲管理包,我的管理中需要一个表单,可以上传多个图像。

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

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

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

<?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),其中我有以下表单(以“奏鸣曲管理方式”创建):

<?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 似乎为空 每次我尝试上传。我可以使它在实体中为空,但是 那么我在数据库中根本没有得到任何网址

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

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

好像没有调用上传函数。我尝试调试它,但找不到解决方案。

我已逐步遵循文档。唯一的区别是我不使用任何 .yaml 文件来配置我的实体。我必须这样做吗?我在我的symfony上使用注解,我想orm.yaml和注解同时使用不太好……对吧?

非常欢迎任何帮助!

【问题讨论】:

  • 您好!刚刚更新了帖子。

标签: image symfony upload doctrine-orm


【解决方案1】:

"关于此主题的任何信息" 你见过http://symfony.com/doc/current/cookbook/form/form_collections.html 吗?

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

-&gt;add('myImage','collection',array('type'=&gt;new MyImageType()))

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

朝那个方向努力,祝你好运。

【讨论】:

  • 感谢您的回复。你已经在说我不知道​​的事情了。学习这个框架并不容易!尤其是一个人:/
  • 仍然不知道如何诚实地度过这个难关..你能写一个例子吗?会很不错..
  • 我提供的链接包含您需要的所有信息。我建议您创建两个实体:Task 和 Tag,就像它在文档中所说的那样。按照示例来理解它。然后你逐步调整它以满足你的特定需求。
猜你喜欢
  • 2014-06-20
  • 2010-12-28
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多