【问题标题】:Update entity file field更新实体文件字段
【发布时间】:2016-01-28 09:34:18
【问题描述】:

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

    <?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

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

【问题讨论】:

  • 您没有在验证之前检查表单是否已提交(使用isSubmitted。并且您正在运行两次验证,但第二次再次保留相同的对象?很难从这里调试而不重新创建它,但你的控制器有点混乱。
  • 好的,我删除了第二个验证,我用的是isSubmitted,但还是有问题。
  • 尝试取出try/catch,看看有没有你遗漏的错误
  • 0 个错误.. 没有..

标签: php symfony sql-update entity


【解决方案1】:

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

您的查询将返回匹配实体的数组,而不是匹配项本身。您需要改为致电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 自动为您查询数据库。

【讨论】:

  • 好的!我尝试替换代码,但现在在 id 变量上出现错误。
  • 注意:未定义变量:id 这是因为我必须传递变量? public function modificaconsigliAction( Request $request, Consigli $consigli, $id ) 像这样?
  • 从签名中取出$id变量,然后取出查询行。如果您按照以前的方式进行操作,那就可以了。或者取出Consigli,让控制器保持原样。
  • 您是否按照我所说的完全尝试过?不改变方法sig?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多