I just make my 2 entity, one is Article and one is Commento, that are comments.
I want a comment form in every single article, so I created the 2 entity, the action in the controller, and the template.
ARTICLE ENTITY
<?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;
}
}
ACTIONS IN THE CONTROLLER
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()));
}
AND THE TEMPLATE
{% 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;">Modifica</div>
<div class="link" style="float:right;padding-right: 25px;">Elimina</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 %}
So, the problem is that when you insert a comment in the form, and I submit the form, I get an error, even if the data are now saved in the db.
Only one data (article_id) that is a Commento's parameter, is NULL, and I don't know why.
This is the error:
No route found for "GET /singlearticle" (from
"http://local/Sito/web/app_dev.php/singlearticle/1")
You need a refactor to the two actions from controller:
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)));
}
The route definition for inserisci_commento needs to be changed to:
inserisci_commento:
path: /singlearticle/{articleId}/inserisci_commento
defaults: {_controller: AppBundle:Default:inserisci_commento}
And in twig replace {{ path('inserisci_commento',{id:commento.id}) }} with {{ path('inserisci_commento',{articleId: article.id}) }}
Hope this helps
The problem is in your redirect statement. You need to pass in the article id.
return $this->redirect('singlearticle',array('id' => $article->getId());
whats definetly wrong is the mappedBy attribute in article class
/**
* #ORM\OneToMany(targetEntity="Commento", mappedBy="commento")
*/
protected $commento;
must be
/**
* #ORM\OneToMany(targetEntity="Commento", mappedBy="article")
*/
protected $commento;
and you have a typo in inversedBy attribute in comment class
/**
*#ORM\ManyToOne(targetEntity="Article",inversedBy="commenti")
* #ORM\JoinColumn(name="article_id",referencedColumnName="id")
*/
protected $article;
must be
/**
*#ORM\ManyToOne(targetEntity="Article",inversedBy="commento")
* #ORM\JoinColumn(name="article_id",referencedColumnName="id")
*/
protected $article;
Related
When i'm viewing www.example.com/product/10 this product is link to a User Id. Now i would like to show only Comment that is link to the User id of the product a i'm viewing.
The table Comment is link to the table User, so each comment have is user id. The table Product (Post) is also link to the table user , each product have is user id.
For now the table Comment and Product are not yet link , i think they should be so i can perform a query, but i'm not sure.
I'm using FosCommentBundle for the comment.
Controller:
public function productAction($id, Request $request)
{
$session = $this->getRequest()->getSession();
$em = $this->getDoctrine()->getManager();
$findEntities = $em->getRepository('FLYBookingsBundle:Post')->findBy(array('id' => $id));
$entities = $this->get('knp_paginator')->paginate($findEntities, $this->get('request')->query->get('page', 1), 9
);
if ($session->has('cart'))
$cart = $session->get('cart');
else
$cart = false;
if (!$entities) {
throw $this->createNotFoundException('Unable to find Post entity.');
}
$id = 'thread_id';
$thread = $this->container->get('fos_comment.manager.thread')->findThreadById($id);
if (null === $thread) {
$thread = $this->container->get('fos_comment.manager.thread')->createThread();
$thread->setId($id);
$thread->setPermalink($request->getUri());
// Add the thread
$this->container->get('fos_comment.manager.thread')->saveThread($thread);
}
$comments = $this->container->get('fos_comment.manager.comment')->findCommentTreeByThread($thread);
return $this->render('FLYBookingsBundle:Post:product.html.twig', array('entity' => $entities,
'cart' => $cart,'comments' => $comments,
'thread' => $thread));
}
Product.html.twig
<div id="fos_comment_thread" data-thread="{{ thread.id }}">
{% include 'FOSCommentBundle:Thread:async.html.twig' with {
'comments': comments,
'thread': thread
} %}
Comment.php
<?php
namespace Application\Sonata\CommentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\CommentBundle\Entity\Comment as BaseComment;
use FOS\CommentBundle\Model\SignedCommentInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Application\Sonata\UserBundle\Entity\User;
/**
* #ORM\Entity
* #ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
*/
class Comment extends BaseComment implements SignedCommentInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\generatedValue(strategy="AUTO")
*/
protected $id;
/**
* Thread of this comment
*
* #var Thread
* #ORM\ManyToOne(targetEntity="Application\Sonata\CommentBundle\Entity\Thread")
*/
protected $thread;
/**
* Author of the comment
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
* #var User
*/
protected $author;
/**
* Sets the author of the Comment
*
* #param UserInterface $user
*/
public function setAuthor(UserInterface $author)
{
$this->author = $author;
}
/**
* Gets the author of the Comment
*
* #return UserInterface
*/
public function getAuthor()
{
return $this->author;
}
public function getAuthorName()
{
if (null === $this->getAuthor()) {
return 'Anonymous';
}
return $this->getAuthor()->getUsername();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
Post.php
<?php
namespace FLY\BookingsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Application\Sonata\UserBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Form\Type\VichImageType;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Form\Extension\Core\Type\FileType;
/**
* Post
*
* #ORM\Table(name="post")
* #ORM\Entity(repositoryClass="FLY\BookingsBundle\Entity\PostRepository")
* #Vich\Uploadable
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Assert\Length(min=2, max=20)
*
* #ORM\Column(name="username", type="string", length=45, nullable=true)
*/
private $username;
/**
* #var string
*
* #Assert\Regex("/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/")
*
* #ORM\Column(name="email", type="string", length=45, nullable=false)
*/
private $email;
/**
* #ORM\ManyToOne(targetEntity="FLY\BookingsBundle\Entity\Tva")
* #ORM\joinColumn(onDelete="SET NULL")
*/
private $tva;
/**
* #ORM\ManyToOne(targetEntity="FLY\BookingsBundle\Entity\Media")
* #ORM\joinColumn(onDelete="SET NULL")
*/
private $image;
/**
* #var string
*
* #Assert\Length(max=350)
*
* #ORM\Column(name="description", type="text" , length=125, nullable=true)
*/
private $description;
/**
* #var float
*
* #Assert\NotBlank()
*
*
* #Assert\Regex(
* pattern= "/^[1-9]\d{0,7}(?:\.\d{1,4})?$/",
* message= "The First number can't start with 0"
* )
*
* #ORM\Column(name="price", type="float")
*/
private $price;
/**
*
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
* #ORM\JoinColumn(onDelete="CASCADE")
* #Security("user.getId() == post.getUser()")
*/
private $user;
/**
* #ORM\OneToOne(targetEntity="Quantity", cascade={"remove"})
* #ORM\JoinColumn(name="sold_id", referencedColumnName="id")
*/
protected $sold;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
*
* #return Post
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set email
*
* #param string $email
*
* #return Post
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set price
*
* #param float $price
* #return Post
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return float
*/
public function getPrice()
{
return $this->price;
}
/**
* #return User
*/
public function getUser()
{
return $this->user;
}
/*
* #param User $user
*/
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* Set tva
*
* #param \FLY\BookingsBundle\Entity\Tva $tva
* #return Post
*/
public function setTva(\FLY\BookingsBundle\Entity\Tva $tva)
{
$this->tva = $tva;
return $this;
}
/**
* Get tva
*
* #return \FLY\BookingsBundle\Entity\Tva
*/
public function getTva()
{
return $this->tva;
}
/**
* Set image
*
* #param \FLY\BookingsBundle\Entity\Media $image
* #return Post
*/
public function setImage(\FLY\BookingsBundle\Entity\Media $image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return \FLY\BookingsBundle\Entity\Media
*/
public function getImage()
{
return $this->image;
}
/**
* Set description
*
* #param string $description
* #return Post
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set sold
*
* #param integer $sold
* #return Post
*/
public function setSold($sold)
{
$this->sold = $sold;
return $this;
}
/**
* Get sold
*
* #return integer
*/
public function getSold()
{
return $this->sold;
}
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
*
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $imageName;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*
* #return User
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTime('now');
}
return $this;
}
/**
* #return File
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* #param string $imageName
*
* #return User
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
}
ADD:
<?php
namespace Application\Sonata\CommentBundle\Entity;
use FLY\BookingsBundle\Entity\Post;
use Application\Sonata\UserBundle\Entity\User;
use Doctrine\ORM\EntityRepository;
class CommentRepository extends EntityRepository
{
/**
* Get Comments for a single Product.
* #param Post $post
* #return mixed
*/
public function getCommentsForSinglePost(Post $post)
{
$qb = $this->createQueryBuilder('c')
->where('c.post = :postId')
->setParameter('postId', $post->getId());
$query = $qb->getQuery();
return $query->execute();
}
}
Relation from Comment to Post(Product):
/**
* #ORM\ManyToOne(targetEntity="FLY\BookingsBundle\Entity\Post")
* #ORM\JoinColumn(nullable=true)
*/
private $post;
/**
* Set post
*
* #param \FLY\BookingsBundle\Entity\Post $post
* #return Comment
*/
public function setUser(\FLY\BookingsBundle\Entity\Post $post = null)
{
$this->post = $post;
return $this;
}
/**
* Get post
*
* #return \FLY\BookingsBundle\Entity\Post
*/
public function getPost()
{
return $this->post;
}
modication in controller:
public function productAction($id, Request $request, $post)
{
$session = $this->getRequest()->getSession();
$em = $this->getDoctrine()->getManager();
$findEntities = $em->getRepository('FLYBookingsBundle:Post')->findBy(array('id' => $id));
$entities = $this->get('knp_paginator')->paginate($findEntities, $this->get('request')->query->get('page', 1), 9
);
if ($session->has('cart'))
$cart = $session->get('cart');
else
$cart = false;
if (!$entities) {
throw $this->createNotFoundException('Unable to find Post entity.');
}
$post = 'thread_id';
$thread = $em->getRepository('ApplicationSonataCommentBundle:Comment')->getCommentsForSinglePost($post);
if (null === $thread) {
$thread = $this->container->get('fos_comment.manager.thread')->createThread();
$thread->setId($post);
$thread->setPermalink($request->getUri());
// Add the thread
$this->container->get('fos_comment.manager.thread')->saveThread($thread);
}
$comments = $this->container->get('fos_comment.manager.comment')->findCommentTreeByThread($thread);
return $this->render('FLYBookingsBundle:Post:product.html.twig', array('entity' => $entities,
'cart' => $cart,'comments' => $comments,'post' => $post,
'thread' => $thread));
}
Error:
Controller
"FLY\BookingsBundle\Controller\PostController::productAction()"
requires that you provide a value for the "$post" argument (because
there is no default value or because there is a non optional argument
after this one).
Considering you have Many-To-One association from Comment to Product. Here is how you should write a new method in CommentRepository to get list of comments for a single product.
/**
* Get Comments for a single Product.
* #param Product $product
* #return mixed
*/
public function getCommentsForSingleProduct(Product $product)
{
$qb = $this->createQueryBuilder('c')
->where('c.product = :productId')
->setParameter('productId', $product->getId());
$query = $qb->getQuery();
return $query->execute();
}
You can add any other condition as per your requirement. or add sort, or pagination etc..
Note : I haven't added user association. Let me know if you need anything else.
I have 2 entities with one to many relationship project and prototype And I've been looking for a way to list the prototypes that belong to a project in the show action .
here is my project entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Projet
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\ProjetRepository")
*/
class Projet
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreation", type="date")
*/
private $dateCreation;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Prototype", mappedBy="projet",cascade={"persist"} , orphanRemoval=true)
* #ORM\OrderBy({"id"="ASC"})
*/
protected $prototypes;
public function __construct()
{
$this->prototypes = new \Doctrine\Common\Collections\ArrayCollection();
$this->dateCreation = new \DateTime("now");
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
* #return Projet
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
public function __toString()
{
return $this->getNom();
}
/**
* Set description
*
* #param string $description
* #return Projet
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Projet
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
public function setPrototypes($prototypes)
{
if (count($prototypes) > 0) {
foreach ($prototypes as $i) {
$this->addPrototypes($i);
}
}
return $this;
}
/**
* Add prototypes
*
* #param \AppBundle\Entity\Prototype $prototypes
* #return Projet
*/
public function addPrototypes(\AppBundle\Entity\Prototype $prototypes)
{
$this->prototypes[]= $prototypes;
return $this;
}
public function addPrototype(\AppBundle\Entity\Prototype $prototype)
{
$prototype->setProjet($this);
$this->prototypes->add($prototype);
}
/**
* Remove prototypes
*
* #param \AppBunble\Entity\Prototype $prototypes
*/
public function removePrototypes(\AppBundle\Entity\Prototype $prototypes)
{
$this->prototypes->removeElement($prototypes);
}
/**
* Get prototypes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPrototypes()
{
return $this->prototypes;
}
}
and here is my prototype entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Prototype
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\PrototypeRepository")
*/
class Prototype
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreation", type="date")
*/
private $dateCreation;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Projet", inversedBy="prototypes")
* #ORM\joinColumn(name="projet_id", referencedColumnName="id")
*/
private $projet;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
public function __toString()
{
return $this->getNom();
}
/**
* Set nom
*
* #param string $nom
* #return Prototype
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Set description
*
* #param string $description
* #return Prototype
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Prototype
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set projet
*
* #param \AppBundle\Entity\Projet $projet
* #return Prototype
*/
public function setProjet(\AppBundle\Entity\Projet $projet = null)
{
$this->projet = $projet;
return $this;
}
/**
* Get projet
*
* #return \AppBundle\Entity\Projet
*/
public function getProjet()
{
return $this->projet;
}
}
In my projetAdmin I can show in the ShowAction the prototypes :
here is projetAdmin :
<?php
namespace AppBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Route\RouteCollection;
class ProjetAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('nom', 'text', array('label' => 'Nom'))
->add('description','text',array('label'=>'Description'))
->add('dateCreation', 'date', array('label' => 'Date de création'))
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('nom')
->add('dateCreation')
;
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('nom')
->add('description')
->add('dateCreation')
->add('_action', 'actions', array(
'actions' => array(
'show' => array(),
'edit' => array(),
'delete' => array(),
)
)
)
;
}
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('prototypes')
;
}
}
I get the prototypes ( names )
But I would like to "list" the prototypes that belong to the project like the list view ( name , description of the prototype...)
How can I do that ?
One way is to define the template for your prototypes field in showMapper
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper ->add('prototypes',null, array('template' => 'NamespaceYourBundle::Admin/prototypes.html.twig'));
}
Create Admin folder in your bundle's resources folder and create prototypes.html.twig file ,extend your twig template with sonata's base_show_field.html.twig template and in {% block field %} define your own markup looping through all related prototypes
{% extends 'SonataAdminBundle:CRUD:base_show_field.html.twig' %}
{% block field %}
{% spaceless %}
{% if object.getPrototypes() is not empty %}
<table class="table table-bordered table-striped">
<thead>
<tr class="sonata-ba-list-field-header">
<th class="sonata-ba-list-field-header-text">Nom</th>
<th class="sonata-ba-list-field-header-text">Description</th>
...
...
...
</tr>
</thead>
<tbody>
{% for prototype in object.getPrototypes() %}
<tr>
<td class="sonata-ba-list-field sonata-ba-list-field-text">{{ prototype.getNom() }}</td>
<td class="sonata-ba-list-field sonata-ba-list-field-text">{{ prototype.getDescription() }}</td>
...
...
...
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% endspaceless %}
{% endblock %}
I found a way to resolve the problem but still I feel it's not the better way
I created a controller and overrided the showAction
<?php
namespace AppBundle\Controller;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class CRUDController extends Controller
{
public function showAction($id = null)
{
return $this->redirect($this->generateUrl('admin_app_prototype_list', array(
'filter[projet__id][value]'=>$id
)));
}
}
Then I get a list of prototypes that belong to a project.
I grab this kind of array.
This is a var_dump of my $tags variable.
array(2) { [0]=> string(1) "3" [1]=> string(1) "4" }
My entity
<?php
namespace Lan\CrmBundle\Entity;
use Doctrine\ORM\Mapping AS ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
*/
class Link
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=false)
* #Assert\NotBlank()
*/
private $url;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $created_at;
/**
* #ORM\ManyToOne(targetEntity="Lan\SecurityBundle\Entity\User", inversedBy="links")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/**
* #ORM\ManyToMany(targetEntity="Lan\CrmBundle\Entity\LinkTag", inversedBy="links")
* #ORM\JoinTable(
* name="LinkTagToLink",
* joinColumns={#ORM\JoinColumn(name="link_id", referencedColumnName="id", nullable=false)},
* inverseJoinColumns={#ORM\JoinColumn(name="link_tag_id", referencedColumnName="id", nullable=false)}
* )
*/
private $tags;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set url
*
* #param string $url
* #return Link
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set description
*
* #param string $description
* #return Link
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return Link
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set user
*
* #param \Lan\SecurityBundle\Entity\User $user
* #return Link
*/
public function setUser(\Lan\SecurityBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \Lan\SecurityBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Constructor
*/
public function __construct()
{
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tags
*
* #param \Lan\CrmBundle\Entity\LinkTag $tags
* #return Link
*/
public function addTag(\Lan\CrmBundle\Entity\LinkTag $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* Remove tags
*
* #param \Lan\CrmBundle\Entity\LinkTag $tags
*/
public function removeTag(\Lan\CrmBundle\Entity\LinkTag $tags)
{
$this->tags->removeElement($tags);
}
/**
* Get tags
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
}
My entire controller:
namespace Lan\CrmBundle\Controller;
use Lan\CrmBundle\Entity\Link;
use Lan\CrmBundle\Form\LinkType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class LinkController extends Controller {
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$tags = $em->getRepository('LanCrmBundle:LinkTag')->findAll();
if($request->query->has('tags')) {
$tags = $request->query->get('tags');
//var_dump($tags); die();
$links = $em->getRepository('LanCrmBundle:Link')->findByTags($tags);
var_dump($links); die();
} else {
$links = $em->getRepository('LanCrmBundle:Link')->findBy(
array(),
array('id' => 'desc')
);
}
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$links,
$this->get('request')->query->get('page', 1),
4
);
return $this->render('LanCrmBundle:Link:index.html.twig', compact('pagination', 'tags'));
}
}
But I got this error:
ContextErrorException: Notice: Undefined index: joinColumns in ...
I think I can't use ->findByTags() like I want...
Thanks in advance!
I don't think you can findByTags because SF2 won't know if you want AND or OR for tags.
The only solution I can suggest you is that you need to query from link_tag table (use repository LanCrmBundle:LinkTag) manually to get all link.id then continue to retrieve link data using LanCrmBundle:Link.
I found a way but not really what I want :
public function findByUsersAndTags($users, $tags)
{
$queryBuilder = $this->createQueryBuilder('l')
->leftJoin('l.tags', 't')->addSelect('t')
->leftJoin('l.user', 'u')->addSelect('u')
->orderBy('l.id', 'desc');
if($users) {
foreach($users as $user_id) {
$queryBuilder->orHaving('u.id = :id')->setParameter('id', $user_id);
}
}
if($tags) {
foreach($tags as $tag_id) {
$queryBuilder->orHaving('t.id = :id')->setParameter('id', $tag_id);
}
}
return $queryBuilder->getQuery()->getResult();
}
I have that Entity TwitterPost.php
<?php
namespace FEB\TwitterBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Twitterpost
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="FEB\TwitterBundle\Entity\TwitterpostRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Twitterpost
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=50)
* #Assert\NotNull(message="Debe escribir un titulo")
*/
private $titulo;
/**
* #var string
*
* #ORM\Column(name="tweet", type="string", length=145)
* #Assert\NotNull(message="Debe escribir un tweet")
*/
private $tweet;
/**
* Many-To-Many, Unidirectional
*
* #var ArrayCollection $tags
*
* #ORM\ManyToMany(targetEntity="\FEB\TagsBundle\Entity\Tag")
* #ORM\JoinTable(name="twitterpost_tags",
* joinColumns={#ORM\JoinColumn(name="twitterpost_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="tag", referencedColumnName="id")}
* )
*/
private $tags;
/**
* #var string
*
* #ORM\Column(name="photo", type="string", length=255, nullable=true)
*/
private $photo;
/**
* #var string
*
* #ORM\Column(name="idpost", type="string", length=100)
*/
private $idpost;
/**
* #var string
*
* #ORM\Column(name="autor", type="string", length=50)
*/
private $autor;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
public function __construct()
{
$this->setCreated(new \DateTime());
$this->tags = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titulo
*
* #param string $titulo
* #return Twitterpost
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set tweet
*
* #param string $tweet
* #return Twitterpost
*/
public function setTweet($tweet)
{
$this->tweet = $tweet;
return $this;
}
/**
* Get tweet
*
* #return string
*/
public function getTweet()
{
return $this->tweet;
}
/**
* Set tags
*
* #param string $tags
* #return Twitterpost
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set photo
*
* #param string $photo
* #return Twitterpost
*/
public function setPhoto($photo)
{
$this->photo = $photo;
return $this;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto()
{
return $this->photo;
}
/**
* Set idpost
*
* #param string $idpost
* #return Twitterpost
*/
public function setIdPost($idpost)
{
$this->idpost = $idpost;
return $this;
}
/**
* Get idpost
*
* #return string
*/
public function getIdPost()
{
return $this->idpost;
}
/**
* Set autor
*
* #param string $autor
* #return Twitterpost
*/
public function setAutor($autor)
{
$this->autor = $autor;
return $this;
}
/**
* Get autor
*
* #return string
*/
public function getAutor()
{
return $this->autor;
}
/**
* Set created
*
* #param \DateTime $created
* #return Tag
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
And this one
/**
* Tag
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="FEB\TagsBundle\Entity\TagRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Tag
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="tag", type="string", length=255)
*/
private $tag;
/**
* #var string
*
* #ORM\Column(name="autor", type="string", length=50)
*/
private $autor;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
public function __construct()
{
$this->setCreated(new \DateTime());
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set tag
*
* #param string $tag
* #return Tag
*/
public function setTag($tag)
{
$this->tag = $tag;
return $this;
}
/**
* Get tag
*
* #return string
*/
public function getTag()
{
return $this->tag;
}
/**
* Set autor
*
* #param string $autor
* #return Tag
*/
public function setAutor($autor)
{
$this->autor = $autor;
return $this;
}
/**
* Get autor
*
* #return string
*/
public function getAutor()
{
return $this->autor;
}
/**
* Set created
*
* #param \DateTime $created
* #return Tag
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
It's a Manytomany relationship between TwitterPost and Tags. And in my form has a select field which is a Entity class Tag.
<?php
namespace FEB\TwitterBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class TwitterpostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('titulo')
->add('tweet', 'textarea')
->add('photo', 'file', array('required' => false))
->add('tags', 'entity', array(
'class' => 'FEBTagsBundle:tag',
'property' => 'tag',
'empty_value' => 'Selecciona tags',
'multiple' => true));
}
public function getName()
{
return 'twitter_form';
}
}
When I submit the data form, in the "twitterpost" table the data is saved correctly and in the aux table "twitterpost_tags" too.
For example:
twitterpost_id tag_id
1-----------1
1-----------2
2-----------1
2-----------3
The tag table:
id---------tag
1----------tagA
2----------tagB
3----------tagC
When I want show all data of Twitterpost, what is the best approached to show the tag name and not the tag id?
Than you in advanced.
I'm not sure if I get you right. To show All tags in the twitterpost form you are already doing the right thing:
->add('tags', 'entity', array(
'class' => 'FEBTagsBundle:tag',
'property' => 'tag',
'empty_value' => 'Selecciona tags',
'multiple' => true
));
This will create a multiple select box where you can select from all the tags. From the docs:
property
type: string
This is the property that should be used for displaying the entities as text in the HTML element. If left blank, the entity object will be cast into a string and so must have a __toString() method.
If you don't want a multi-select but checkboxes or radiobuttons instead, checkout this part of the documentation.
In case you are asking on how to output the data when not inside the TwitterpostType, you can just treat them as objects in a Controller:
$repository = $this->getDoctrine()->getRepository('TwitterBundle:Twitterpost');
$post = $repository->findOne($id);
// to get all _tags_ of a post just call the getter:
$tags = $post->getTags();
The same goes for twig templates:
{# imagine you have all posts in a variable called 'posts' #}
{% for post in posts %}
<h1>{{ post.titulo }}</h1>
<div class="tags">
{% for tag in posts.tags %}
{{ tag.tag }}
{% endfor %}
</div>
{% endfor %}
Edit:
For a native SQL / DQL query you need a custom repository class. There you can store your own queries:
class TwitterpostRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM TwitterBundle:Twitterpost p ORDER BY p.name ASC'
)
->getResult();
}
}
Then you can use it like this in the controller:
$repository = $this->getDoctrine()->getRepository('TwitterBundle:Twitterpost');
$post = $repository->findAllOrderedByName();
i have a problem with customize the texarea field in my twig file
The validation of the form dont work if i customize the textarea
When i customize the other fields excepting the textarea and use {{form_rest(form)}} the validation works fine.
if i remove the expression if($form->isvalid()) the persistance works fine.
please help me
here is my code
The controller:
public function addAction()
{
$produit = new Produit();
$formBuilder = $this->createFormBuilder($produit);
$formBuilder->add('nom','text',array('required'=>false))
->add('prix','text')
->add('marque','text')
->add('description','textarea');
$form = $formBuilder->getForm();
return $this->render('zmsite1Bundle:Produit:add.html.twig', array( 'form' => $form->createView() ));
}
public function createAction()
{
$produit = new Produit();
$formBuilder = $this->createFormBuilder($produit);
$formBuilder->add('nom','text')
->add('prix','text')
->add('marque','text')
->add('description','textarea');
$form = $formBuilder->getForm();
$request = $this->getRequest();
if($request->getMethod() == 'POST'){
$form->bind($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$em->persist($produit);
$em->flush();
return $this->redirect($this->generateUrl('produit_show',array('id' => $produit->getId())));
}
return $this->render("zmsite1Bundle:Produit:add.html.twig",array('form'=>$form->createView()));
}
}
The file add.html.twig
<form method="post" {{ form_enctype(form) }} action="{{path('produit_create')}}">
<table>
<tr>
<td>{{form_label(form.nom,"Nom du produit")}}</td>
<td>{{form_widget(form.nom)}}</td>
<td>{{form_errors(form.nom)}}</td>
</tr>
<tr>
<td>{{form_label(form.marque,"Marque du produit")}}</td>
<td>{{form_widget(form.marque)}}</td>
<td>{{form_errors(form.marque)}}</td>
</tr>
<tr>
<td>{{form_label(form.prix,"Prix du produit")}}</td>
<td>{{form_widget(form.prix)}}</td>
<td>{{form_errors(form.prix)}}</td>
</tr>
<tr>
<td>{{textarea_label(form.description,"Description du produit")}}</td>
<td>{{textarea_widget(form.description)}}</td>
<td>{{textarea_errors(form.description)}}</td>
</tr>
</table>
<input type="submit" name="Valider" />
Entity produit
<?php
namespace zm\site1Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* produit
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="zm\site1Bundle\Entity\produitRepository")
*/
class produit
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="marque", type="string", length=255)
*/
private $marque;
/**
* #var float
*
* #ORM\Column(name="prix", type="decimal")
*/
private $prix;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
* #return produit
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set marque
*
* #param string $marque
* #return produit
*/
public function setMarque($marque)
{
$this->marque = $marque;
return $this;
}
/**
* Get marque
*
* #return string
*/
public function getMarque()
{
return $this->marque;
}
/**
* Set prix
*
* #param float $prix
* #return produit
*/
public function setPrix($prix)
{
$this->prix = $prix;
return $this;
}
/**
* Get prix
*
* #return float
*/
public function getPrix()
{
return $this->prix;
}
/**
* Set description
*
* #param string $description
* #return produit
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
Your form may have csrf protection that is not being rendered adn so it causing the form to not be fully validated.
Either use {{ form_rest(form) }} like you have done before (to render the hidden csrf token). Or turn it off in your form ( I'm not at all sure this is possible in an inline form ) otherwise it would be in your form type (from: http://symfony.com/doc/2.1/book/forms.html#csrf-protection)...
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\TaskBundle\Entity\Task',
'csrf_protection' => true,
'csrf_field_name' => '_token',
// a unique key to help generate the secret token
));
}