更新实体文件字段

时间:2016-01-28 09:34:19

标签: php symfony sql-update entity

我在更新带有文件字段的实体时遇到了一些问题。我不知道它是什么,因为我花了很多时间,但今天它不会起作用。 所以这就是实体:

    <?php

namespace AppBundle\Entity;

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

/**
 * Consigli
 * 
 * @ORM\Table()
 * @ORM\HasLifecycleCallbacks
 *  @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\ConsigliRepository")
 */
class Consigli
{

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

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

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


    /**
     * @var string $image
     * @Assert\File( maxSize = "60000000", mimeTypesMessage = "Perfavore inserisci un'immagine valida!")
     * @ORM\Column(name="image", type="string", length=255, nullable=true)
     */
    private $image;

    /**
     * @ORM\ManyToOne(targetEntity="Categoria", inversedBy="categoria")
     * @ORM\JoinColumn(name="categoria_id", referencedColumnName="id")
     */
    protected $categoria;

     /**
     * @var date
     *
     * @ORM\Column(name="data", type="date")
     */
    public $data;


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

    /**
     * Set titolo
     *
     * @param string $titolo
     *
     * @return Consigli
     */
    public function setTitolo($titolo)
    {
        $this->titolo = $titolo;

        return $this;
    }

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

 /**
     * Set testo
     *
     * @param string $testo
     *
     * @return Consigli
     */
    public function setTesto($testo)
    {
        $this->testo = $testo;

        return $this;
    }

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

    /**
     * Set image
     *
     * @param string $image
     */
    public function setImage($image)
    {
        $this->image = $image;
    }

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

     public function getFullImagePath() {
        return null === $this->image ? null : $this->getUploadRootDir(). $this->image;
    }

    protected function getUploadRootDir() {
        // the absolute directory path where uploaded documents should be saved
        return $this->getTmpUploadRootDir().$this->getId()."/";
    }

    protected function getTmpUploadRootDir() {
        // the absolute directory path where uploaded documents should be saved
        return __DIR__ . '/../../../web/immaginiConsigli/';
    }

/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function uploadImage() {
    // the file property can be empty if the field is not required
    if (null === $this->image) {
        return;
    }
    if(!$this->id){
        $this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
    }else{
        return null;
}
$this->setImage($this->image->getClientOriginalName());
}

    /**
     * @ORM\PostPersist()
     */
    public function moveImage()
    {
        if (null === $this->image)
        {
            return;
        }
        if (!is_dir($this->getUploadRootDir()))
        {
            mkdir($this->getUploadRootDir());
        }
        copy($this->getTmpUploadRootDir() . $this->image, $this->getFullImagePath());
        unlink($this->getTmpUploadRootDir() . $this->image);
    }

    /**
     * Set data
     *
     * @param \DateTime $data
     *
     * @return Consigli
     */
    public function setData($data)
    {
        $this->data = $data;

        return $this;
    }

    /**
     * Get data
     *
     * @return \DateTime
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * Set categoria
     *
     * @param \AppBundle\Entity\Categoria $categoria
     *
     * @return Consigli
     */
    public function setCategoria(\AppBundle\Entity\Categoria $categoria = null)
    {
        $this->categoria = $categoria;

        return $this;
    }

    /**
     * Get categoria
     *
     * @return \AppBundle\Entity\Categoria
     */
    public function getCategoria()
    {
        return $this->categoria;
    }
}

该文件存储在一个文件夹中,就像您可以看到“immaginiConsigli”一样,在数据库的表格中我有“图像”字段,用于存储图像的名称。

控制器中的更新操作是:

public function modificaconsiglioAction(Request $request, $id)
    {

        $em = $this->getDoctrine()->getManager();
        $consiglio = $em->getRepository('AppBundle:Consigli')->find($id);
        $form = $this->createForm(new ConsiglioType($consiglio), $consiglio);
        $form->handleRequest($request);
        if ($form->isValid())
        {
            $em = $this->getDoctrine()->getManager();
            try
            {
                $em->persist($consiglio);
                $em->flush();

                return $this->redirect($this->generateUrl('successconsigliomodificato'));
            } catch (\Exception $e)
            {

                $form->addError(new FormError('errore nel database: ' . $e->getMessage()));
            }

            if ($form->isValid())
            {
                $var = $consiglio;
                $em->persit($var);
                $em->flush();

                return $this->redirect($this->generateUrl('successconsigliomodificato'));
            } else
            {

            }
        }
        return $this->render('adminarea/modificaconsiglio.html.twig', array(
                    'consiglio' => $consiglio,
                    'form' => $form->createView()));
    }

所以会发生什么:我想更新已经存在的记录,当然已经有了该文件。更新似乎有效,但是当我渲染新的和更新的记录时,图像没有显示,在数据库中我总是得到这样的东西:

  

的/ tmp / php1QyeYr

这不是图像的名称。 而且,新的文件/图像,它没有插入文件夹中。 所以,谁知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

再看一遍,我想我发现了问题。

您的查询将返回匹配实体的数组,而不是匹配实体。您需要拨打findOneBy

public function modificaconsiglioAction( Request $request, $id ) {
    $em = $this->getDoctrine()
               ->getManager();
    $consiglio = $em->getRepository( 'AppBundle:Consigli' )
                    ->findOneBy( [ 'id' => $id ] );

    if ( null !== $consiglio ) {
        $form = $this->createForm( new ConsiglioType( $consiglio ), $consiglio );
        $form->handleRequest( $request );
        if ( $form->isSubmitted() && $form->isValid() ) {
            $em->persist( $consiglio );
            $em->flush();

            return $this->redirect( $this->generateUrl( 'successconsigliomodificato' ) );
        }
    } else {
         // do something about letting the user know the id matched nothing
    }

    return $this->render( 'adminarea/modificaconsiglio.html.twig', [
        'consiglio' => $consiglio,
        'form'      => $form->createView(),
    ] );
}

值得注意的是,如果不对数据库进行自己的查询,就可以逃脱。如果您将方法签名更改为:

public function modificaconsiglioAction( Request $request, Consigli $consigli ) {

Symfony将根据发送给路由中控制器的$id自动为您查询数据库。