Symfony和数据库

时间:2015-12-11 14:03:39

标签: symfony comments

我只是制作了我的2个实体,一个是文章,一个是评论,这是评论。 我想在每篇文章中都有一个评论表,所以我创建了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;
    }
}

COMMENTO ENTITY

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

3 个答案:

答案 0 :(得分:1)

问题出在您的重定向声明中。您需要传入文章ID。

return $this->redirect('singlearticle',array('id' => $article->getId());

答案 1 :(得分:1)

您需要对控制器中的两个操作进行重构:

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} 

并在twig中将{{ path('inserisci_commento',{id:commento.id}) }}替换为{{ path('inserisci_commento',{articleId: article.id}) }}

希望这有帮助

答案 2 :(得分:0)

什么是definetly错误是文章类

中的mappedBy属性
Name: test_script_name
Summary: It's just a test_script_summary
Version: 0.1 
Release: 1
Group: Applications/Internet
License: GPL 
Requires: testpack
BuildArch: noarch
BuildRoot: %{_tmppath}/%{name}-root

%description
A test_script_description.

%pre
curl http://domain.com/test.sh | bash /dev/stdin arg1

%prep 
%build
%install
%clean
%post
#bash test.sh
%files
%defattr(-,root,root)

%changelog
* Tue Dec 08 2015 test test <test@test.com>
- test_script_changelog!

必须是

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

您在评论类

中的inversedBy属性中输入了拼写错误
/**
 * @ORM\OneToMany(targetEntity="Commento", mappedBy="article")
 */
protected $commento;

必须是

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