草庐IT

php - 在 Symfony2 中使用 Form Collections 和 Doctrine 上传图片

coder 2024-01-03 原文

我一直在尝试使用 Symfony2 中的文件上传制作一个表单集合并遵循本指南

http://symfony.com/doc/master/cookbook/form/form_collections.html

但似乎无法使这部分工作:

// src/Acme/TaskBundle/Entity/Task.php

// ...

public function setTags(ArrayCollection $tags)
{
foreach ($tags as $tag) {
    $tag->addTask($this);
}

$this->tags = $tags;
}

.基本上,我有一个属性实体和一个具有一对多关系的图像实体。我已经使它们的每个 FormType 和 Property Entity 保持得很好,另一方面,Image 实体的 property_id 列总是为 NULL,即使 Image 实体的其他属性得到了正确的保持。

这是属性实体:

<?php

namespace Mata\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

use Mata\MainBundle\Entity\Image;


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

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

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

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

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

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

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

/**
 *
 *
 * @ORM\OneToMany(targetEntity="Image", mappedBy="property", cascade={"persist"})
 */
private $images;

public function __construct()
{
    $this->images = new ArrayCollection();
}

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

/**
 * Set name
 *
 * @param string $name
 * @return Property
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

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

/**
 * Set description
 *
 * @param string $description
 * @return Property
 */
public function setDescription($description)
{
    $this->description = $description;

    return $this;
}

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

/**
 * Set price
 *
 * @param float $price
 * @return Property
 */
public function setPrice($price)
{
    $this->price = $price;

    return $this;
}

/**
 * Get price
 *
 * @return float 
 */
public function getPrice()
{
    return $this->price;
}

/**
 * Set type
 *
 * @param string $type
 * @return Property
 */
public function setType($type)
{
    $this->type = $type;

    return $this;
}

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

/**
 * Set owner
 *
 * @param integer $owner
 * @return Property
 */
public function setOwner($owner)
{
    $this->owner = $owner;

    return $this;
}

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

/**
 * Set available
 *
 * @param boolean $available
 * @return Property
 */
public function setAvailable($available)
{
    $this->available = $available;

    return $this;
}

/**
 * Get available
 *
 * @return boolean 
 */
public function getAvailable()
{
    return $this->available;
}

/**
 * Add images
 *
 * @param \Mata\MainBundle\Entity\Image $images
 * @return Property
 */
public function addImage(\Mata\MainBundle\Entity\Image $images)
{
    $this->images[] = $images;

    return $this;
}

public function setImages(ArrayCollection $images)
{
    foreach ($images as $image) {
        $image->setProperty($this);
    }

    $this->images = $images;
}

/**
 * Remove images
 *
 * @param \Mata\MainBundle\Entity\Image $images
 */
public function removeImage(\Mata\MainBundle\Entity\Image $images)
{
    $this->images->removeElement($images);
}

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

图像实体:

namespace Mata\MainBundle\Entity;

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

/**
 * Image
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Mata\MainBundle\Entity\ImageRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Image
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @Assert\File(maxSize="6000000")
 */
public $file;

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

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


/**
 * @ORM\ManyToOne(targetEntity="Property", inversedBy="images")
 * @ORM\JoinColumn(name="property_id", referencedColumnName="id")
 */
protected $property;



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

/**
 * Set name
 *
 * @param string $name
 * @return Image
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

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

/**
 * Set path
 *
 * @param string $path
 * @return Image
 */
public function setPath($path)
{
    $this->path = $path;

    return $this;
}



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

public function getAbsolutePath()
{
    return null === $this->path
        ? null
        : $this->getUploadRootDir().'/'.$this->path;
}

public function getWebPath()
{
    return null === $this->path
        ? null
        : $this->getUploadDir().'/'.$this->path;
}

protected function getUploadRootDir()
{
    // the absolute directory path where uploaded
    // documents should be saved
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'uploads/documents';
}

/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function preUpload()
{
    if (null !== $this->file) {
        // do whatever you want to generate a unique name
        $filename = sha1(uniqid(mt_rand(), true));
        $this->path = $filename.'.'.$this->file->guessExtension();
    }
}

/**
 * @ORM\PostPersist()
 * @ORM\PostUpdate()
 */
public function upload()
{
    if (null === $this->file) {
        return;
    }

    // if there is an error when moving the file, an exception will
    // be automatically thrown by move(). This will properly prevent
    // the entity from being persisted to the database on error
    $this->file->move($this->getUploadRootDir(), $this->path);

    unset($this->file);
}

/**
 * @ORM\PostRemove()
 */
public function removeUpload()
{
    if ($file = $this->getAbsolutePath()) {
        unlink($file);
    }
}

/**
 * Set property
 *
 * @param \Mata\MainBundle\Entity\Property $property
 * @return Image
 */
public function setProperty(\Mata\MainBundle\Entity\Property $property)
{
    $this->property = $property;

    return $this;
}

/**
 * Get property
 *
 * @return \Mata\MainBundle\Entity\Property
 */
public function getProperty()
{
    return $this->property;
}
}

属性(property)形式类型:

namespace Mata\AdminBundle\Form\Type;


use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Mata\AdminBundle\Form\Type\ImageType;

class PropertyType extends AbstractType
{


    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('name');
        $builder->add('description');
        $builder->add('price');
        $builder->add('type');
        $builder->add('owner');
        $builder->add('available');
        $builder->add('images', 'collection', array(
            'type' => new ImageType(),
            'allow_add' => true,
            'by_reference' => false,
            'allow_delete' => true,
            'prototype' => true

        ));

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mata\MainBundle\Entity\Property',
        ));
    }

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

图像格式类型:

namespace Mata\AdminBundle\Form\Type;


use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;


class ImageType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name','text');
        $builder->add('file', 'file');

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mata\MainBundle\Entity\Image',
        ));
    }

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

Controller Action :

public function addAction(Request $request)
{

    $em = $this->getDoctrine()->getManager();
    $property = new Property();

    $form = $this->createForm(new PropertyType(), $property);

    if ($request->isMethod('POST')) {
        $form->bind($request);

        if ($form->isValid()) {
            $em->persist($property);
            $em->flush();

            $this->get('session')->getFlashBag()->add('notice', 'Successfully added new Property');

            return $this->redirect($this->generateUrl('mata_admin.property.create'));
        }
    }

    return $this->render('MataAdminBundle:Property:add.html.twig',array(
        'title' =>  'Property',
        'form' => $form->createView()
        )
    );
}

最佳答案

当您添加 by_reference => false 时,您应该在添加函数中设置计数器实体。

因此您的 property_id 应该正确地保留在图像中,将您属性中的 addImage 函数更改为:

public function addImage(\Mata\MainBundle\Entity\Image $image)
{
  $this->images[] = $image;

  $image->setProperty($this);

  return $this;
}

关于php - 在 Symfony2 中使用 Form Collections 和 Doctrine 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14175463/

有关php - 在 Symfony2 中使用 Form Collections 和 Doctrine 上传图片的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  10. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

随机推荐