我有一个实体代理与实体Photo相关的OneToOne
代理
class Agence
{
/**
* @ORM'OneToOne(targetEntity="Project'DashboardBundle'Entity'Photo", cascade={"persist"})
* @ORM'JoinColumn(nullable=true)
*/
private $photo;
这是实体照片的简介
<?php
namespace Project'DashboardBundle'Entity;
use Doctrine'ORM'Mapping as ORM;
use Symfony'Component'Validator'Constraints as Assert;
/**
* Photo
*
* @ORM'Table()
* @ORM'Entity(repositoryClass="Project'DashboardBundle'Entity'PhotoRepository")
* @ORM'HasLifecycleCallbacks
*/
class Photo
{
/**
* @var integer
*
* @ORM'Column(name="id", type="integer")
* @ORM'Id
* @ORM'GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM'Column(name="url", type="string", length=255)
*/
private $url;
/**
* @var string
*
* @ORM'Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* @Assert'File(maxSize="1M")
*/
public $file;
public function setFile($file)
{
$this->file = $file;
if (null !== $this->url) {
$this->tempFilename = $this->url;
$this->url = null;
$this->alt = null;
}
}
public function getFile()
{
return $this->file;
}
private $tempFilename;
/**
* @ORM'PrePersist()
* @ORM'PreUpdate()
*/
public function preUpload()
{
if (null === $this->file) {
return;
}
$this->url = $this->file->guessExtension();
$this->alt = $this->file->getClientOriginalName();
}
/**
* @ORM'PostPersist()
* @ORM'PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
if (null !== $this->tempFilename) {
$oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;
if (file_exists($oldFile)) {
unlink($oldFile);
}
}
$this->file->move(
$this->getUploadRootDir(),
$this->id.'.'.$this->url
);
}
/**
* @ORM'PreRemove()
*/
public function preRemoveUpload()
{
$this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}
/**
* @ORM'PostRemove()
*/
public function removeUpload()
{
if (file_exists($this->tempFilename)) {
unlink($this->tempFilename);
}
}
public function getUploadDir()
{
return 'uploads/img';
}
protected function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath()
{
return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}
当试图上传照片时,我得到了这个错误:
致命错误异常:错误:对D:''wamp''www''agence''src''Project''DashboardBundle''Entity''Photo.php行135中的非对象调用成员函数guessExtension()
奇怪的是,同样的代码在另一个实体上运行良好!!
已解决我忘记添加{{form_enctype(form)}}
您只需要像那样插入你的表格{{form_enctype(form)}}
action="{{ path('your_path') }}" {{form_enctype(form)}} method="post"