我是Symfony2的新用户,我尝试使用Symfony2 cookbook文档上传文件。 我的问题是,我的文件实体没有持久化,因此我的文件没有上传
这是我的文件实体
<?php
namespace JuridicoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
*
* @ORM\Table(name="JURIDICO_ANEXOS_TESTE")
* @ORM\Entity(repositoryClass="JuridicoBundle\Repository\AnexoRepository")
*/
class Anexo {
/**
* @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="path", type="string", length=255)
*/
public $path;
/**
* @ORM\ManyToOne(targetEntity="Liminar" ,inversedBy="anexos", cascade={"persist"})
* @ORM\JoinColumn(name="LIMINAR", referencedColumnName="cdliminar")
**/
private $liminar;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @param string $path
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* @return mixed
*/
public function getLiminar()
{
return $this->liminar;
}
/**
* @param mixed $liminar
*/
public function setLiminar($liminar)
{
$this->liminar = $liminar;
}
public $file;
/**
* Get file.
*
* @return UploadedFile
*/
public function getFile()
{
return $this->file;
}
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';
}
private $temp;
/**
* Sets file.
*
* @param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// check if we have an old image path
if (isset($this->path)) {
// store the old name to delete after the update
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
// do whatever you want to generate a unique name
$filename = sha1(uniqid(mt_rand(), true));
$this->path = $filename.'.'.$this->getFile()->guessExtension();
$this->name = $this->getFile()->getClientOriginalName();
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->getFile()) {
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->getFile()->move($this->getUploadRootDir(), $this->path);
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->getUploadRootDir().'/'.$this->temp);
// clear the temp image path
$this->temp = null;
}
$this->file = null;
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
$file = $this->getAbsolutePath();
if ($file) {
@unlink($file);
}
}
}
我的班级与oneToMany关系
<?php
namespace JuridicoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Liminar
*
* @ORM\Table(name="juridico_liminar")
* @ORM\Entity(repositoryClass="JuridicoBundle\Repository\LiminarRepository")
*/
class Liminar
{
/**
* @var integer
* @ORM\Id
* @ORM\Column(name="cdliminar", type="string")
*/
private $id;
/**
* @var string
* @ORM\Column(name="cdprocesso", type="string", length=20)
*/
private $cdprocesso;
/**
* @var \Datetime
* @ORM\Column(name="dtrecebimento", type="datetime")
*/
private $dataRecebimento;
/**
* @var string
* @ORM\Column(name="cdcliente", type="string", length=20)
*/
private $codigoCliente;
/**
* @var string
* @ORM\Column(name="nocliente", type="string", length=100)
*/
private $nomeCliente;
/**
* @var string
* @ORM\Column(name="cdcliente2", type="string" , length=20)
*/
private $codigoCliente2;
/**
* @var string
* @ORM\Column(name="nocliente2", type="string", length=100)
*/
private $nomeCliente2;
/**
* @ORM\ManyToOne(targetEntity="MotivoAcao", inversedBy="liminar")
* @ORM\JoinColumn(name="CDMOTIVO_ACAO", referencedColumnName="CDMOTIVO_ACAO")
**/
private $codigoMotivoAcao;
/**
* @var string
* @ORM\Column(name="motivo_obs", type="string", length=200)
*/
private $motivoObservacao;
/**
* @var float
* @ORM\Column(name="multa", type="float")
*/
private $multa;
/**
* @var string
* @ORM\Column(name="cumprimento", type="string", length=1)
*/
private $cumprimento;
/**
* @var float
* @ORM\Column(name="valor", type="float")
*/
private $valor;
/**
* @var string
* @ORM\Column(name="sem_valor", type="string" , length=100)
*/
private $semValor;
/**
* @var string
* @ORM\Column(name="hospital", type="string", length=100)
*/
private $hospital;
/**
* @var string
* @ORM\Column(name="medico_solicitante", type="string", length=100)
*/
private $medicoSolicitante;
/**
* @var string
* @ORM\Column(name="cooperado", type="string", length=1)
*/
private $cooperado;
/**
* @ORM\ManyToOne(targetEntity="UnimedOrigem", inversedBy="liminar")
* @ORM\JoinColumn(name="UNIMED_ORIGEM", referencedColumnName="CDPRESTADOR")
**/
private $unimedOrigem;
/**
* @var string
* @ORM\Column(name="contrato", type="string", length=100)
*/
private $contrato;
/**
* @var \Datetime
* @ORM\Column(name="dtcadastro", type="datetime")
*/
private $dataCadastro;
/**
* @var string
* @ORM\Column(name="idcadastro", type="integer", length=6)
*/
private $codigoCadastro;
/**
*
* @ORM\OneToMany(targetEntity="Anexo", mappedBy="liminar", cascade={"persist", "remove"})
*/
private $anexos;
function __construct()
{
$this->anexos = new ArrayCollection();
}
/**
* @return mixed
*/
public function getAnexos()
{
$anexos = $this->anexos;
foreach($anexos as $anexo) {
$anexo->setLiminar($this);
}
return $this->anexos;
}
/**
* @param mixed $anexo
*/
public function setAnexos($anexos)
{
foreach($anexos as $anexo) {
$anexo->setLiminar($this);
}
$this->anexos = $anexos;
}
public function addAnexo($anexo)
{
$anexo->setLiminar($this);
$this->anexos[] = $anexo;
}
public function removeAnexo($anexo)
{
$this->anexos->removeElement($anexo);
}
/**
* @return string
*/
public function getCodigoCadastro()
{
return $this->codigoCadastro;
}
/**
* @param string $codigoCadastro
*/
public function setCodigoCadastro($codigoCadastro)
{
$this->codigoCadastro = $codigoCadastro;
}
/**
* @return \Datetime
*/
public function getDataCadastro()
{
return $this->dataCadastro;
}
/**
* @param \Datetime $dataCadastro
*/
public function setDataCadastro($dataCadastro)
{
$this->dataCadastro = $dataCadastro;
}
/**
* @return string
*/
public function getContrato()
{
return $this->contrato;
}
/**
* @param string $contrato
*/
public function setContrato($contrato)
{
$this->contrato = $contrato;
}
/**
* @return string
*/
public function getUnimedOrigem()
{
return $this->unimedOrigem;
}
/**
* @param string $unimedOrigem
*/
public function setUnimedOrigem($unimedOrigem)
{
$this->unimedOrigem = $unimedOrigem;
}
/**
* @return string
*/
public function getCooperado()
{
return $this->cooperado;
}
/**
* @param string $cooperado
*/
public function setCooperado($cooperado)
{
$this->cooperado = $cooperado;
}
/**
* @return string
*/
public function getMedicoSolicitante()
{
return $this->medicoSolicitante;
}
/**
* @param string $medicoSolicitante
*/
public function setMedicoSolicitante($medicoSolicitante)
{
$this->medicoSolicitante = $medicoSolicitante;
}
/**
* @return string
*/
public function getHospital()
{
return $this->hospital;
}
/**
* @param string $hospital
*/
public function setHospital($hospital)
{
$this->hospital = $hospital;
}
/**
* @return string
*/
public function getSemValor()
{
return $this->semValor;
}
/**
* @param string $semValor
*/
public function setSemValor($semValor)
{
$this->semValor = $semValor;
}
/**
* @return float
*/
public function getValor()
{
return $this->valor;
}
/**
* @param float $valor
*/
public function setValor($valor)
{
$this->valor = $valor;
}
/**
* @return string
*/
public function getCumprimento()
{
return $this->cumprimento;
}
/**
* @param string $cumprimento
*/
public function setCumprimento($cumprimento)
{
$this->cumprimento = $cumprimento;
}
/**
* @return float
*/
public function getMulta()
{
return $this->multa;
}
/**
* @param float $multa
*/
public function setMulta($multa)
{
$this->multa = $multa;
}
/**
* @return string
*/
public function getMotivoObservacao()
{
return $this->motivoObservacao;
}
/**
* @param string $motivoObservacao
*/
public function setMotivoObservacao($motivoObservacao)
{
$this->motivoObservacao = $motivoObservacao;
}
/**
* @return string
*/
public function getCodigoMotivoAcao()
{
return $this->codigoMotivoAcao;
}
/**
* @param string $codigoMotivoAcao
*/
public function setCodigoMotivoAcao($codigoMotivoAcao)
{
$this->codigoMotivoAcao = $codigoMotivoAcao;
}
/**
* @return string
*/
public function getNomeCliente2()
{
return $this->nomeCliente2;
}
/**
* @param string $nomeCliente2
*/
public function setNomeCliente2($nomeCliente2)
{
$this->nomeCliente2 = $nomeCliente2;
}
/**
* @return string
*/
public function getCodigoCliente2()
{
return $this->codigoCliente2;
}
/**
* @param string $codigoCliente2
*/
public function setCodigoCliente2($codigoCliente2)
{
$this->codigoCliente2 = $codigoCliente2;
}
/**
* @return string
*/
public function getNomeCliente()
{
return $this->nomeCliente;
}
/**
* @param string $nomeCliente
*/
public function setNomeCliente($nomeCliente)
{
$this->nomeCliente = $nomeCliente;
}
/**
* @return string
*/
public function getCodigoCliente()
{
return $this->codigoCliente;
}
/**
* @param string $codigoCliente
*/
public function setCodigoCliente($codigoCliente)
{
$this->codigoCliente = $codigoCliente;
}
/**
* @return \Datetime
*/
public function getDataRecebimento()
{
return $this->dataRecebimento;
}
/**
* @param \Datetime $dataRecebimento
*/
public function setDataRecebimento($dataRecebimento)
{
$this->dataRecebimento = $dataRecebimento;
}
/**
* @return string
*/
public function getCdprocesso()
{
return $this->cdprocesso;
}
/**
* @param string $cdprocesso
*/
public function setCdprocesso($cdprocesso)
{
$this->cdprocesso = $cdprocesso;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
}
任何人都可以提供帮助吗?
这是我的控制器
<?php
namespace JuridicoBundle\Controller;
use JuridicoBundle\Entity\Liminar;
use JuridicoBundle\Form\LiminarDetalheType;
use JuridicoBundle\Form\LiminarType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class LiminarController extends Controller
{
/**
* Realiza busca de autor do sistema através do nome
* @param Request $request
* @return JsonResponse
*
* @Route("/busca-nome-liminar", name="busca-nome-liminar")
*
*/
public function consultaNomeAutor(Request $request){
$response = new JsonResponse();
$nome = $request->query->get("term");
$processos = array();
$resultado = array();
$processos = $this
->getDoctrine()
->getRepository("JuridicoBundle:Liminar")
->consultaNome($nome);
foreach ($processos as $processo) {
$resultado[] = array(
'label' => $processo["nomeCliente"],
'value' => $processo["nomeCliente"],
'id' => $processo["id"]
);
}
$response->setData($resultado);
return $response;
}
/**
* @Route("/salvar", name="salvar")
* @Template()
*/
public function salvarAction(Request $request) {
$liminar = new Liminar();
$form = $this->createForm(new LiminarDetalheType(),$liminar);
$form->handleRequest($request);
if ($form->isValid()) {
$liminar = $form->getData();
$liminarRepository = $this->getDoctrine()->getRepository('JuridicoBundle:Liminar');
$liminarRepository->salvar($liminar);
$this->addFlash('success', 'Liminar salva com sucesso');
}
return $this->render("JuridicoBundle:Liminar:nova.html.twig",
array('formLiminar' => $form->createView()));
}
/**
* @Route("/editar-liminar/", name="editar-liminar")
* @Template()
*/
public function alterarAction(Request $request) {
$id = $_GET['id'];
$liminarRepository = $this->getDoctrine()->getRepository('JuridicoBundle:Liminar');
$liminar = $liminarRepository->find($id);
if(!$liminar){
$this->createNotFoundException("Nenhuma Liminar disponível para edição.");
}
$form = $this->createForm(new LiminarDetalheType(),$liminar);
$form->handleRequest($request);
if($form->isValid()){
$liminar = $form->getData();
try{
$liminarRepository->alterar($liminar);
$this->get('session')->getFlashBag()
->add('success', 'Atualizado com sucesso!');
}catch (\Exception $e){
$this->get('session')->getFlashBag()->add(
'danger', $e->getMessage());
}
}
return $this->render("JuridicoBundle:Liminar:liminar.html.twig",
array('formLiminar' =>
$form->createView()));
}
/**
* @Route("/excluir", name="excluir")
* @Template()
*/
public function excluirAction(Request $request, Liminar $liminar) {
$liminarRepository = $this->getDoctrine()
->getRepository("JuridicoBundle:Liminar");
$liminar = $liminarRepository->find($liminar);
if (!$liminar) {
$this->createNotFoundException("Não existe essa Liminar");
}
try {
$liminarRepository->excluir($liminar);
$this->get('session')->getFlashBag()
->add('success', 'Removido com sucesso!');
return $this->redirect($this->generateUrl(''));
} catch (\Exception $e) {
$this->get('session')
->getFlashBag()
->add('danger', $e->getMessage());
}
}
}
我的打字格式
<?php
namespace JuridicoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AnexoType extends AbstractType
{
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(array(
'data_class' => 'JuridicoBundle\Entity\Anexo',
'csrf_protection' => false,
'csrf_field_name' => '_csrf_token',
// a unique key to help generate the secret token
'intention' => 'anexo',
));
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file','file',array(
'label' => false));
}
/**
* @return string
*/
public function getName()
{
return 'anexo';
}
}