Symfony和数据库

坎迪·霍利

我只是创建我的2个实体,一个是Article,一个是Commento,这就是评论。我希望在每篇文章中都使用注释形式,因此我创建了2个实体,控制器中的操作和模板。

文章实体

    <?php

namespace AppBundle\Entity;

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

/**
 * Article
 * 
 * @ORM\Table()
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity
 */
class Article
{

    /**
     * @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="autore", type="string", length=255)
     */
    private $autore;

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

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

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

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

    /**
     * @ORM\OneToMany(targetEntity="Commento", mappedBy="commento")
     */
    protected $commento;

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

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

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

        return $this;
    }

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

    /**
     * Set autore
     *
     * @param string $autore
     *
     * @return Article
     */
    public function setAutore($autore)
    {
        $this->autore = $autore;

        return $this;
    }

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

    /**
     * Set testo
     *
     * @param string $testo
     *
     * @return Article
     */
    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/imgArticoli/';
    }

    /**
     * @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{
            $this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
        }
        $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 Article
     */
    public function setData($data)
    {
        $this->data = $data;

        return $this;
    }

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

    /**
     * Set categoria
     *
     * @param string $categoria
     *
     * @return Article
     */
    public function setCategoria($categoria)
    {
        $this->categoria = $categoria;

        return $this;
    }

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


    /**
     * Add commento
     *
     * @param \AppBundle\Entity\Commento $commento
     *
     * @return Article
     */
    public function addCommento(\AppBundle\Entity\Commento $commento)
    {
        $this->commento[] = $commento;

        return $this;
    }

    /**
     * Remove commento
     *
     * @param \AppBundle\Entity\Commento $commento
     */
    public function removeCommento(\AppBundle\Entity\Commento $commento)
    {
        $this->commento->removeElement($commento);
    }

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

实体评论

<?php

namespace AppBundle\Entity;

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

/**
 * Commento
 * 
 * @ORM\Table()
 * @ORM\HasLifecycleCallbacks
 *  @ORM\Entity
 */
class Commento
{

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

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

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

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

    /**
     *@ORM\ManyToOne(targetEntity="Article",inversedBy="commenti")
     * @ORM\JoinColumn(name="article_id",referencedColumnName="id")
     */
    protected $article;

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

    /**
     * Set nome
     *
     * @param string $nome
     *
     * @return Commento
     */
    public function setNome($nome)
    {
        $this->nome = $nome;

        return $this;
    }

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

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

        return $this;
    }

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


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

        return $this;
    }

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

    /**
     * Set article
     * 
     * @param \AppBundle\Entity\Article $article
     * @return Commento
     */
    public function setArticle(\AppBundle\Entity\Article $article=null)
    {
        $this->article = $article;

        return $this;
    }

    /**
     * Get article
     *
     * @return \AppBundle\Entity\Article 
     */
    public function getArticle()
    {
        return $this->article;
    }
}

控制器中的动作

  public function singlearticleAction(Request $request, $id)
    {
        //Codice di singlearticle
        $art = $this->getDoctrine()->getEntityManager();
        $article = $art->getRepository('AppBundle:Article')->find($id);
        if (!$article)
        {
            throw $this->createNotFoundException('Non riesco a trovare questo articolo!');
        }
        //Fin qui

        $commento = new Commento();
        $commento->setData(new \DateTime('now'));

        $form = $this->createForm(new CommentoType($article), $commento);

        $request = $this->getRequest();

        $form->handleRequest($request);


        if ($form->isValid())
        {

            if ($article)
            {
                $commento->setArticle($article);
            }

            $em = $this->getDoctrine()->getManager();
            try
            {
                $em->persist($commento);
                $em->flush();
                return $this->redirect('singlearticle');
            } catch (\Exception $e)
            {
                $form->addError(new FormError('errore nel database'));
            }
        }

        return $this->render('default/singlearticle.html.twig', array(
                    'article' => $article,
                    'commento' => $commento,
                    'form' => $form->createView()));
    }


    public function inserisci_commentoAction(Request $request)/* ROTTA "inserisci_commento" */
    {
        $commento = new Commento();
        $commento->setData(new \DateTime('now'));

        $form = $this->createForm(new CommentoType($commento), $commento);

        $request = $this->getRequest();

        $form->handleRequest($request);


        if ($form->isValid())
        {

            $em = $this->getDoctrine()->getManager();
            try
            {
                $em->persist($commento);
                $em->flush();
                return $this->redirect('singlearticle');
            } catch (\Exception $e)
            {
                $form->addError(new FormError('errore nel database'));
            }
        }
        return $this->render('default/singlearticle.html.twig', array(
                    'commento' => $commento,
                    'form' => $form->createView()));
    }

和模板

{% extends 'base.html.twig' %}
{% block body %}{% endblock %}
{% block maincontent %}
<div class="maincontent-title">{{article.titolo}} di {{article.autore}}</div>
<br>
<div class="tipologia">Categoria: {{article.categoria}}</div>
<div class="link" style="float:right;"><a href="{{path('update_articolo', {id:article.id})}}">Modifica</a></div>
<div class="link" style="float:right;padding-right: 25px;"><a href="{{path('remove_articolo', {id:article.id})}}">Elimina</a></div>
<div class="rigaseparatrice"></div>
<br>
<article> 
    <p>

      {%if article.image is not empty%}
        <img class="imgarticolo" src="{{ asset('imgArticoli/' ~ article.id ~'/' ~ article.image)}}"/>
      {%endif%}

    <div class="titolo"></div>
    <br>
    <div class="testoarticolo">{{article.testo}}</div>
    <br><br>
    <br><br>
    <div class="form-commento">
INSERISCI UN COMMENTO!
<form action="{{ path('inserisci_commento',{id:commento.id}) }}" method="post" {{ form_enctype(form) }} >
        {{ form_errors(form) }}

        {{ form_row(form.nome) }}
        <br>
        {{ form_row(form.testo) }}
        <br>
        {{ form_rest(form) }}

        <input id="bottone" type="submit" value="INSERISCI" />
    </form>

        </div>
    </p> 
</article>


{% endblock %}

因此,问题在于,即使您现在将数据保存在数据库中,当您在表单中插入注释并提交表单时,也会出现错误。只有一个作为Commento参数的数据(article_id)为NULL,我不知道为什么。

这是错误:

找不到“ GET / singlearticle”的路由(来自“ http://local/Sito/web/app_dev.php/singlearticle/1 ”)

亚历山德鲁·弗库里塔(Alexandru Furculita)

您需要重构控制器的两个动作:

public function singlearticleAction($id)
{
    //Codice di singlearticle
    $art = $this->getDoctrine()->getEntityManager();
    $article = $art->getRepository('AppBundle:Article')->find($id);

    if (!$article){
        throw $this->createNotFoundException('Non riesco a trovare questo articolo!');
    }
    //Fin qui

    $form = $this->createForm(new CommentoType($article), new Commento());

    return $this->render('default/singlearticle.html.twig', array(
                'article' => $article,
                'form' => $form->createView())
    );
}

public function inserisci_commentoAction(Request $request, $articleId)
{
    //Codice di singlearticle
    $em = $this->getDoctrine()->getEntityManager();
    $article = $em->getRepository('AppBundle:Article')->find($articleId);
    if (!$article) {
        throw $this->createNotFoundException('Non riesco a trovare questo articolo!');
    }

    $commento = new Commento();
    $form = $this->createForm(new CommentoType($commento), $commento);

    $form->handleRequest($request);
    if ($form->isValid())
    {
        try
        {
            $commento->setData(new \DateTime('now'));
            $commento->setArticle($article);
            $em->persist($commento);
            $em->flush();

            // add a success message to session flashbag
        } catch (\Exception $e)
        {
            // add a error message to session flashbag
        }
    }

    return $this->redirect($this->generateUrl('singlearticle', array('id'=> $articleId)));
}

的路由定义inserisci_commento需要更改为:

inserisci_commento: 
    path: /singlearticle/{articleId}/inserisci_commento 
    defaults: {_controller: AppBundle:Default:inserisci_commento} 

并在树枝中替换{{ path('inserisci_commento',{id:commento.id}) }}{{ path('inserisci_commento',{articleId: article.id}) }}

希望这可以帮助

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章