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
));
}
Related
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;
i have an error :
Catchable Fatal Error: Object of class ParcAutoBundle\Entity\Car could not be converted to string
my class of maintenance is :
<?php
namespace AutoEcole\ParcAutoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Maintenance
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AutoEcole\ParcAutoBundle\Entity\MaintenanceRepository")
*/
class Maintenance {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="datemaintenance", type="string", length=255)
*/
private $datemaintenance;
/**
* #var integer
*
* #ORM\Column(name="mileage", type="bigint")
*/
private $mileage;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set datemaintenance
*
* #param string $datemaintenance
* #return Maintenance
*/
public function setDatemaintenance($datemaintenance) {
$this->datemaintenance = $datemaintenance;
return $this;
}
/**
* Get datemaintenance
*
* #return string
*/
public function getDatemaintenance() {
return $this->datemaintenance;
}
/**
* Set mileage
*
* #param integer $mileage
* #return Maintenance
*/
public function setMileage($mileage) {
$this->mileage = $mileage;
return $this;
}
/**
* Get mileage
*
* #return integer
*/
public function getMileage() {
return $this->mileage;
}
/**
* Set description
*
* #param string $description
* #return Maintenance
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
/**
* #ORM\ManyToOne(targetEntity="\AutoEcole\ParcAutoBundle\Entity\Car")
* #ORM\JoinColumn(nullable=false)
*/
private $car;
/**
* Set car
*
* #param \AutoEcole\ParcAutoBundle\Entity\Car $car
* #return Maintenance
*/
public function setCar(\AutoEcole\ParcAutoBundle\Entity\Car $car = null) {
$this->car = $car;
return $this;
}
/**
* Get car
*
* #return \AutoEcole\ParcAutoBundle\Entity\Car
*/
public function getCar() {
return $this->car;
}
}
my function in controller is :
if you want the MaintenanceType tell me
public function addcarmaintenanceAction($id, Request $request) {
//User connecté
$user = $this->getUser();
$maintenance = new Maintenance();
$car = $this->getDoctrine()->getManager()->getRepository('ParcAutoBundle:Car')->find($id);
//dump($car);
//die();
//Création du formulaire
$form = $this->createForm(new MaintenanceType());
$form->handleRequest($request);
if ($form->isValid()) {
//Récupération des données du formulaire de l'ajout du voiture
$datemaintenance = $form['datemaintenance']->getData();
$mileage = $form['mileage']->getData();
$description = $form['description']->getData();
//Préparation de l'objet pour le persister et faire flush() ensuite
$maintenance->setDatemaintenance($datemaintenance);
$maintenance->setMileage($mileage);
$maintenance->setDescription($description);
$maintenance->setCar($id);
//Entity Manager
$em = $this->getDoctrine()->getManager();
$em->persist($maintenance);
$em->flush();
$message = "style=display:block;";
return $this->render('ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig', array(
'form' => $form->createView(),
'user' => $user,
'message' => $message,
'car' => $car
));
}
$message = "style=display:none;";
return $this->render('ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig', array(
'user' => $user,
'form' => $form->createView(),
'message' => $message,
'car' => $car
));
}
the problem is solved , i putted the __toString() in the Car Class
public function __toString() {
return (string) $this->getRegistrationnumber();
}
In you ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig template, try to display a property of car, not car directly:
{{ car.model }} // it's an exemple property
// instead of
{{ car }}
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 have created a form based on an entity field. This form is composed of checkboxes that allow user to choose an entity (here 'car').
This works fine but I need to customize the rendering to get extra informations. Currently, the only information that is displayed is the 'id' attribute.
In my case, I would like to display extra entity informations in the form such as color, brand etc ...
Does anyone know how to proceed ?
The controller :
public function chooserAction() {
//symfony.com/doc/current/reference/forms/types/entity.html
$cars = $this->getDoctrine()
->getRepository('CarBundle:Car')
->find(1);
$formBuilder = $this->createFormBuilder();
/*
foreach ($cars as $car) {
$formBuilder->add($car->getId() ,'checkbox')->getForm();
}
*/
$formBuilder->add('cars', 'entity', array(
'class' => 'CarBundle:Car',
'property' => 'id',
'expanded' => 'true',
'multiple' => 'true',
));
$formBuilder->add('save', 'submit');
$form = $formBuilder->getForm();
$request = $this->get('request');
$form->handleRequest($request);
if ($form->isValid()) {
echo "ok";
// return $this->redirect($this->generateUrl('car_show', array('id' => $car->getId())));
}
return $this->render('CarBundle:Car:chooser.html.twig', array('form' => $form->createView()));
}
The entity :
<?php
namespace Foobar\CarBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Car
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Foobar\CarBundle\Entity\CarRepository")
*/
class Car
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="brand", type="string", length=255)
*/
private $brand;
/**
* #var string
*
* #ORM\Column(name="color", type="string", length=255)
*/
private $color;
/**
* #var integer
*
* #ORM\Column(name="power", type="integer")
*/
private $power;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Car
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set brand
*
* #param string $brand
* #return Car
*/
public function setBrand($brand)
{
$this->brand = $brand;
return $this;
}
/**
* Get brand
*
* #return string
*/
public function getBrand()
{
return $this->brand;
}
/**
* Set color
*
* #param string $color
* #return Car
*/
public function setColor($color)
{
$this->color = $color;
return $this;
}
/**
* Get color
*
* #return string
*/
public function getColor()
{
return $this->color;
}
/**
* Set power
*
* #param integer $power
* #return Car
*/
public function setPower($power)
{
$this->power = $power;
return $this;
}
/**
* Get power
*
* #return integer
*/
public function getPower()
{
return $this->power;
}
}
The view :
car chooser
{{ form(form) }}
You could create a toString() method in your Car entity.
public function __toString()
{
return '' . $this->getName();
}
If you want more thinks like pictures you could follow that http://symfony.com/doc/current/cookbook/form/form_customization.html
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();