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();
}
Related
I need your help on my problem for saving my data in table.
I use fosUserBundle and have different user types (Admin, Pro, Client) that are classes extending a base User entity.
I also have a Language entity linked to the User with a one-to-many association.
To subscribe, a userClient needs to check by checkbox the language(s) that he speaks.
The form page is ok, it displays the UserClient form (+ the parent User form) with the list of languages as checkboxes.
The problem is the data saved in table.
I have the same values in the language column:
O:43:"Doctrine\Common\Collections\ArrayCollection":1:{s:53:"Doctrine\Common\Collections\ArrayCollectionelements";a:2:{i:0;O:32:"LanguagesBundle\Entity\Languages":10:{s:36:"LanguagesBundle\Entity\Languagesid";i:2;s:38:"LanguagesBundle\Entity\Languagesname";s:7:"English";s:44:"LanguagesBundle\Entity\Languagesshort_slug";s:2:"en";s:43:"LanguagesBundle\Entity\Languageslong_slug";s:5:"en_EN";s:43:"LanguagesBundle\Entity\LanguagesisDefault";b:0;s:43:"LanguagesBundle\Entity\LanguagesupdatedAt";O:8:"DateTime":3:{s:4:"date";s:26:"2018-04-20 22:46:48.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:12:"Europe/Paris";}s:43:"LanguagesBundle\Entity\LanguagesimageFile";N;s:39:"LanguagesBundle\Entity\Languagesimage";s:39:"Flag_of_United_Kingdom_-_Circle-512.png";s:43:"LanguagesBundle\Entity\LanguagesimageSize";i:37621;s:44:"LanguagesBundle\Entity\LanguagesuserClient";N;}i:1;O:32:"LanguagesBundle\Entity\Languages":10:{s:36:"LanguagesBundle\Entity\Languagesid";i:1;s:38:"LanguagesBundle\Entity\Languagesname";s:9:"Français";s:44:"LanguagesBundle\Entity\Languagesshort_slug";s:2:"fr";s:43:"LanguagesBundle\Entity\Languageslong_slug";s:5:"fr_FR";s:43:"LanguagesBundle\Entity\LanguagesisDefault";b:1;s:43:"LanguagesBundle\Entity\LanguagesupdatedAt";O:8:"DateTime":3:{s:4:"date";s:26:"2018-04-20 22:45:50.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:12:"Europe/Paris";}s:43:"LanguagesBundle\Entity\LanguagesimageFile";N;s:39:"LanguagesBundle\Entity\Languagesimage";s:31:"Flag_of_France_-_Circle-512.png";s:43:"LanguagesBundle\Entity\LanguagesimageSize";i:23352;s:44:"LanguagesBundle\Entity\LanguagesuserClient";N;}}}
Here's my code:
User.php
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use UserBundle\Entity\UserAdmin;
use UserBundle\Entity\UserProfessional;
use UserBundle\Entity\UserClient;
use UserBundle\Entity\Adress;
/**
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({"client" = "UserClient", "professional"="UserProfessional", "admin"="UserAdmin"})
*/
abstract class User extends BaseUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*/
protected $firstname;
//[...] getters and setters
Entity: UserClient.php
<?php
// src/UserBundle/Entity/UserGuest.php
namespace UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
*/
class UserClient extends User {
/**
* #ORM\Column(type="array")
* #ORM\OneToMany(targetEntity="LanguagesBundle\Entity\Languages", mappedBy="userClient")
*/
private $languages;
public function __construct() {
parent::__construct();
$this->languages = new ArrayCollection();
}
/**
* Set languages
*
* #param array $languages
*
* #return UserClient
*/
public function setLanguages($languages)
{
$this->languages = $languages;
}
/**
* Get languages
*
* #return array
*/
public function getLanguages()
{
return $this->languages;
}
/**
* Add language
*
* #param \LanguagesBundle\Entity\Languages $language
*
* #return UserClient
*/
public function addLanguage(LanguagesBundle\Entity\Languages $language)
{
$this->languages[] = $language;
return $this;
}
/**
* Remove language
*
* #param \LanguagesBundle\Entity\Languages $language
*/
public function removeLanguage(\LanguagesBundle\Entity\Languages $language)
{
$this->languages->removeElement($language);
}
}
Entity Languages.php
<?php
namespace LanguagesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity
*
* #Vich\Uploadable
*/
class Languages
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
* #Assert\NotBlank()
*/
private $name;
/**
* #ORM\Column(type="string", length=2, unique=true)
*/
private $short_slug;
/**
* #var string
*
* #ORM\Column(type="string", length=5, unique=true)
* #Assert\NotBlank()
*/
private $long_slug;
/**
* #var string
*
* #ORM\Column(type="boolean", nullable=true)
*/
private $isDefault;
/**
* #ORM\Column(type="datetime")
* #var \DateTime
*/
private $updatedAt;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Assert\File(
* maxSize="1M",
* mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
* )
* #Vich\UploadableField(mapping="language_images", fileNameProperty="image", size="imageSize")
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255, nullable = true)
* #var string
*/
private $image;
/**
* #ORM\Column(type="integer")
*
* #var integer
*/
private $imageSize;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\UserClient", inversedBy="languages")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $userClient;
/**
* 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
*/
public function setImageFile(?File $image = null): void
{
$this->imageFile = $image;
if (null !== $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 \DateTimeImmutable();
}
}
public function getImageFile()
{
return $this->imageFile;
}
/**
* Constructor
*/
public function __construct()
{
$this->updatedAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Languages
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set shortSlug
*
* #param string $shortSlug
*
* #return Languages
*/
public function setShortSlug($shortSlug)
{
$this->short_slug = $shortSlug;
return $this;
}
/**
* Get shortSlug
*
* #return string
*/
public function getShortSlug()
{
return $this->short_slug;
}
/**
* Set longSlug
*
* #param string $longSlug
*
* #return Languages
*/
public function setLongSlug($longSlug)
{
$this->long_slug = $longSlug;
return $this;
}
/**
* Get longSlug
*
* #return string
*/
public function getLongSlug()
{
return $this->long_slug;
}
/**
* Set isDefault
*
* #param boolean $isDefault
*
* #return Languages
*/
public function setIsDefault($isDefault)
{
$this->isDefault = $isDefault;
return $this;
}
/**
* Get isDefault
*
* #return boolean
*/
public function getIsDefault()
{
return $this->isDefault;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
*
* #return Languages
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set image
*
* #param string $image
*
* #return Languages
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set imageSize
*
* #param integer $imageSize
*
* #return Languages
*/
public function setImageSize($imageSize)
{
$this->imageSize = $imageSize;
return $this;
}
/**
* Get imageSize
*
* #return integer
*/
public function getImageSize()
{
return $this->imageSize;
}
/**
* Set userClient
*
* #param \UserBundle\Entity\UserClient $userClient
*
* #return Languages
*/
public function setUserClient(\UserBundle\Entity\UserClient $userClient = null)
{
$this->userClient = $userClient;
return $this;
}
/**
* Get userClient
*
* #return \UserBundle\Entity\UserClient
*/
public function getUserClient()
{
return $this->userClient;
}
/**
* {#inheritdoc}
*/
public function __toString()
{
return $this->getName() ?: '-';
}
}
My FormType: RegistrationTypeClient.php
<?php
// src/UserBundle/Form/UserContactFormType.php
namespace UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use LanguagesBundle\Services\LanguagesService;
use LanguagesBundle\Entity\Languages ;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
class RegistrationClientType extends AbstractType {
protected $service;
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
$builder
->add('languages', EntityType::class, [
'class' => 'LanguagesBundle:Languages',
'choice_label' => 'name',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.name', 'ASC');
},
'label' => 'Langues',
'expanded' => true,
'multiple' => true,
])
;
}
public function getParent() {
// on inclut le formulaire de base d'inscription utilisateur
return 'UserBundle\Form\RegistrationType';
}
public function getBlockPrefix() {
return 'app_user_registration_client';
}
// For Symfony 2.x
public function getName() {
return $this->getBlockPrefix();
}
public function configureOptions(OptionsResolver $resolver) {
$resolver
->setDefaults(array(
'data_class' => \UserBundle\Entity\UserClient::class,
))
//->setRequired('service_languages');
;
}
}
And my Controller:
public function registerClientAction(Request $request) {
/** #var $formFactory FactoryInterface */
//$formFactory = $this->get('fos_user.registration_pro.form.factory');
/** #var $userManager UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = new UserClient();
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $this->createForm(RegistrationClientType::class, $user);
$form->setData($user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
if (null !== $response = $event->getResponse()) {
return $response;
}
}
return $this->render('UserBundle\Registration\register_client.html.twig', array(
'form' => $form->createView(),
));
}
Here's a picture showing the data saved in the table
I need the languages to be stored in the database as an array for userClient.
Could you help me please.
Thank's for re-edit my question Philip-B-
Thank's for your reading also.
I have resolve my problem by adding a foreach to transform my object to array:
The code is in my controller:
if ($form->isValid()) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
foreach ($user->getLanguages() as $value) {
$langue[] = $value->getShortSlug();
}
$user->setLanguages($langue);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
I trying make relation in symphony through this http://symfony.com/doc/current/doctrine/associations.html
problemm is that when i get post and wont get related entitie (rss) i get null
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Post
* #ORM\Entity
* #ORM\Table(name="post")
*/
class Post
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $title;
/**
* #var string
*/
private $text;
/**
* #ORM\ManyToOne(targetEntity="Rss", inversedBy="posts")
* #ORM\JoinColumn(name="link", referencedColumnName="id")
*/
private $rss;
/**
* #var \DateTime
*/
private $createdAt;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set text
*
* #param string $text
*
* #return Post
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set link
*
* #param string $link
*
* #return Post
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Post
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #var integer
*/
private $user_id;
/**
* Set userId
*
* #param integer $userId
*
* #return Post
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->user_id;
}
/**
* #var integer
*/
private $link;
public function setRss($rss){
$this->rss = $rss;
}
public function getRss(){
return $this->rss;
}
}
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* rss
*
* #ORM\Entity
* #ORM\Table(name="rss")
*/
class Rss
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #var string
*/
private $address;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return rss
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set address
*
* #param string $address
*
* #return rss
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* #var \DateTime
*/
private $lastUpdate;
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="Rss")
*/
private $posts;
public function __construct()
{
$this->posts = new ArrayCollection();
}
public function getPosts(){
return $this->posts;
}
public function setPosts($posts){
$this->posts[] = $posts;
}
/**
* Set lastUpdate
*
* #param \DateTime $lastUpdate
*
* #return rss
*/
public function setLastUpdate($lastUpdate)
{
$this->lastUpdate = $lastUpdate;
return $this;
}
/**
* Get lastUpdate
*
* #return \DateTime
*/
public function getLastUpdate()
{
return $this->lastUpdate;
}
/**
* #var string
*/
private $pageaddress;
/**
* Set pageaddress
*
* #param string $pageaddress
*
* #return rss
*/
public function setPageaddress($pageaddress)
{
$this->pageaddress = $pageaddress;
return $this;
}
/**
* Get pageaddress
*
* #return string
*/
public function getPageaddress()
{
return $this->pageaddress;
}
}
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository('AppBundle:Post')->findAll();
$post = $this->getDoctrine()
->getRepository('AppBundle:Post')
->find(1);
$post->getRss();
This can help you:
https://knpuniversity.com/screencast/doctrine-relations/many-to-one-relation
also you can try modifying the variable $id
private $id
for
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
To create a primary key.
Entity
class Post
/**
* #ORM\ManyToOne(targetEntity="Rss", inversedBy="post")
* #ORM\JoinColumn(nullable=false)
*/
private $rss;
class Rss
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="rss")
* #ORM\OrderBy({"createdAt"="DESC"})
*/
private $post;
and the class Post you will need to create a constructor like this
public function __construct()
{
$this->posts = new ArrayCollection();
}
/**
* #return ArrayCollection|GenusNote[]
*/
public function getPosts()
{
return $this->notes;
}
I hope it can help you
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'm implementing a search on a website and for simplicity i've decided to create a class that does the hard work.
Basically my class takes the EntityManager and the Entities in which i want to search and creates the DQL and executes the query. For normal entities this works totally fine but when i pass the User entity (Extended from fos user bundle entity) i get this error :
[Semantical Error] line 0, col 139 near 'last_login LIKE': Error: Class Soundmerger\UserBundle\Entity\User has no field or association named last_login
The dql query generated seems fine and as it works for the other entities i doubt it comes form there.
Here is my Search class :
use Doctrine\Common\Util\Debug;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Query;
class Search {
private $em;
private $searchables;
public function __construct(EntityManager $em, ArrayCollection $searchables){
$this->em = $em;
$this->searchables = $searchables;
}
public function search($query){
$words = explode("+", $query);
$qb = array();
$results = array();
foreach($this->searchables as $qNumber => $searchable){
$qb[$qNumber] = "SELECT s FROM $searchable s ";
$columns = $this->em->getClassMetadata($searchable)->getColumnNames();
foreach($words as $i => $word){
foreach($columns as $k => $column){
$string = "s.$column LIKE '%$word%'";
if($i == 0 && $k == 0){
$qb[$qNumber] .= "WHERE $string";
} else {
$qb[$qNumber] .= "OR $string";
}
}
}
$res[] = $this->em->createQuery($qb[$qNumber])->getResult(Query::HYDRATE_SIMPLEOBJECT);
}
return $this->formatSearch($res);
}
private function formatSearch($results){
$formatedResult = array();
foreach($results as $k => $result){
if(!empty($result)){
$formatedResult[$k]["type"] = get_class($result[0]);
$formatedResult[$k]["data"] = $result[0];
}
}
return $formatedResult;
}
}
And my Controller for the search :
/**
* #Route("/search/{query}")
* #Template()
*/
public function indexAction($query)
{
$em = $this->getDoctrine()->getManager();
$searchables = new ArrayCollection(
array(
"SoundmergerUserBundle:Professional",
"SoundmergerFaqBundle:Faq",
"SoundmergerUserBundle:User",
));
$search = new Search($em, $searchables);
return array('search' => $search->search($query));
}
And finally my user entity :
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
* #AttributeOverrides({
* #AttributeOverride(name="emailCanonical",
* column=#ORM\Column(
* name = "emailCanonical",
* type = "string",
* length = 255,
* nullable = true
* )
* ),
* #AttributeOverride(name="email",
* column=#ORM\Column(
* name = "email",
* type = "string",
* length = 255,
* nullable = true
* )
* ),
* #AttributeOverride(name="username",
* column=#ORM\Column(
* name = "username",
* type = "string",
* length = 255,
* unique = false
* )
* ),
* #AttributeOverride(name="usernameCanonical",
* column=#ORM\Column(
* name = "usernameCanonical",
* type = "string",
* length = 255,
* unique = false
* )
* ),
* })
*/
class User extends BaseUser
{
const STRUCTURE_SOLO = "solo";
const STRUCTURE_GROUP = "group";
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", nullable=true)
* #var string
*/
protected $nomProfile = null;
/**
* #ORM\Column(type="text", nullable=true)
* #var string
*/
protected $description = null;
/**
* #ORM\Column(type="string", nullable=true)
* #var string
*/
protected $type = null;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $structure = self::STRUCTURE_SOLO;
/**
* #ORM\Column(type="string", nullable=true)
* #var string
*/
protected $tel = null;
/**
* #ORM\Column(type="string", nullable=true)
* #var string
*/
protected $site = null;
/**
* #ORM\Column(type="boolean")
* #var bool
*/
protected $firstLogin = true;
/**
* #ORM\OneToOne(targetEntity="Soundmerger\MainBundle\Entity\Address", cascade={"persist"})
*/
protected $address;
/**
* #ORM\OneToMany(targetEntity="Soundmerger\MainBundle\Entity\Style", mappedBy="user", cascade={"persist"})
*/
protected $styles;
/**
* #ORM\OneToMany(targetEntity="Soundmerger\UserBundle\Entity\Member", mappedBy="user")
* #ORM\JoinColumn(nullable=true)
*/
protected $members;
/** #ORM\Column(name="discogs_id", type="string", length=255, nullable=true) */
protected $discogs_id;
/** #ORM\Column(name="discogs_access_token", type="string", length=255, nullable=true) */
protected $discogs_access_token;
public function __construct()
{
parent::__construct();
$this->members = new ArrayCollection();
$this->styles = new ArrayCollection();
}
/**
* Get id
* #return string
*/
public function getId()
{
return $this->id;
}
/**
* Get NomProfile
* #return string
*/
public function getNomProfile()
{
return $this->nomProfile;
}
/**
* Get type
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Get structure
* #return string
*/
public function getStructure()
{
return $this->structure;
}
/**
* Get tel
* #return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Get site
* #return string
*/
public function getSite()
{
return $this->site;
}
/**
* Get description
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set nomProfile
* #param string $nomProfile
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setNomProfile($nomProfile)
{
$this->nomProfile = $nomProfile;
return $this;
}
/**
* Set type
* #param string $type
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Set structure
* #param string $structure
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setStructure($structure)
{
if (!in_array($structure, array(self::STRUCTURE_SOLO, self::STRUCTURE_GROUP))) {
throw new \InvalidArgumentException("Invalid structure");
}
$this->structure = $structure;
return $this;
}
/**
* Set tel
* #param string $tel
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Set site
* #param string $site
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setSite($site)
{
$this->site = $site;
return $this;
}
/**
* Set description
* #param type $description
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Set the first login
* #param bool $firstLogin
* #return \Soundmerger\UserBundle\Entity\Utilisateur
*/
public function setFirstLogin($firstLogin)
{
$this->firstLogin = $firstLogin;
return $this;
}
/**
* Is it the first login
* #return bool returns true if its the first login, false otherwise
*/
public function isFirstLogin()
{
return $this->firstLogin;
}
/**
* Set address
*
* #param Address $address
* #return $this
*/
public function setAddress(Address $address)
{
$this->address = $address;
return $this;
}
/**
* Get adress
*
* #return mixed
*/
public function getAddress()
{
return $this->address;
}
/**
* #return Style
*/
public function getStyles()
{
return $this->styles;
}
/**
* #param Style $style
* #return $this
*/
public function addStyle(Style $style)
{
if (!$this->styles->contains($style)) {
$style->setUser($this);
$this->styles->add($style);
}
return $this;
}
public function setStyles(PersistentCollection $styles)
{
foreach ($styles as $style) {
$this->addStyle($style);
}
}
/**
* #return ArrayCollection
*/
public function getMembers()
{
return $this->members;
}
/**
* #param Member $members
*/
public function addMember(Member $member)
{
if (!$this->members->contains($member)) {
$this->members->add($member);
}
return $this;
}
public function setDiscogsId($discogs_id)
{
$this->discogs_id = $discogs_id;
return $this;
}
public function getDiscogsId()
{
return $this->discogs_id;
}
public function setDiscogsAccessToken($discogs_access_token)
{
$this->discogs_access_token = $discogs_access_token;
return $this;
}
public function getDiscogsAccessToken()
{
return $this->discogs_access_token;
}
public function isRegisteredWithDiscogs(){
return $this->discogs_id != null;
}
}
Any ideas on why this is only happening with the user entity (it must be due to the inheritance but i can't seem to find a way round it)
btw : its a university project so the idea of using an external bundle for the search is not really possible.
Thanks for any help
Dan
I'm trying to create a form to insert "questions" that can have one or more "answers". So I want to add an embed form for the Answer entity.
It seems to work because I see the Question form, but only the string "Answers" is displayed at the bottom of my form, not the fields.
Here is my controller action :
public function addQuestionAction(Category $category)
{
$question = new Question();
$form = $this->createForm(new QuestionType(), $question);
$request = $this->get('request');
if ($request->getMethod() === 'POST') {
$form->bind($request);
$question->setCategory($category);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($question);
$em->flush();
return $this->redirect($this->generateUrl('mycategory_questiondisplay',
array('id' => $question->getId())));
}
}
return $this->render('MyCategoryBundle:Question:add.html.twig',
array(
'form' => $form->createView(),
));
}
My QuestionType form :
<?php
namespace My\CategoryBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class QuestionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('description')
->add('answers', 'collection', array(
'type' => new AnswerType(),
'allow_add' => true)
);
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Iel\CategoryBundle\Entity\Question'
));
}
/**
* #return string
*/
public function getName()
{
return 'my_categorybundle_question';
}
}
My Question Entity :
<?php
namespace My\CategoryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Question
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\CategoryBundle\Entity\QuestionRepository")
*/
class Question
{
/**
* #ORM\OneToMany(targetEntity="My\CategoryBundle\Entity\Answer",
mappedBy="question", cascade={"persist", "remove"})
*/
private $answers;
public function __construct()
{
$this->answers = new
\Doctrine\Common\Collections\ArrayCollection();
}
public function addAnswer(\My\CategoryBundle\Entity\Answer
$answer)
{
$this->answers[] = $answer;
$answers->setQuestion($this);
return $this;
}
public function removeAnswer(\My\CategoryBundle\Entity\Answer $answer)
{
$this->answers->removeElement($answer);
}
public function getAnswers()
{
return $this->answers;
}
public function setAnswers($answer)
{
$this->answer = $answer;
return $this;
}
/**
* #ORM\ManyToOne(targetEntity="My\CategoryBundle\Entity\Category",
inversedBy="question")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* Set category
*
#param My\CategoryBundle\Entity\Category $category
*/
public function setCategory(\My\CategoryBundle\Entity\Category $category)
{
$this->category = $category;
}
/**
* Get category
*
#return My\CategoryBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Remove categories
**
#param My\CategoryBundle\Entity\Category $categories
*/
public function removeCategory(\My\CategoryBundle\Entity\Category $category)
{
$this->categories->removeElement($category);
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* #param string $titre
* #return Question
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set description
*
* #param string $description
* #return Question
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
And finally, the Answer entity :
<?php
namespace My\CategoryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Answer
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\CategoryBundle\Entity\AnswerRepository")
*/
class Answer
{
/**
* #ORM\ManyToOne(targetEntity="My\CategoryBundle\Entity\Question",
inversedBy="answer")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="question_id", referencedColumnName="id")
* })
*/
private $question;
/**
* Set question
*
#param My\CategoryBundle\Entity\Question $question
*/
public function setQuestion(\My\CategoryBundle\Entity\Question $question)
{
$this->question = $question;
}
/**
* Get question
*
#return My\CategoryBundle\Entity\Question
*/
public function getQuestion()
{
return $this->question;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="answer", type="text", nullable=true)
*/
private $answer;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set answer
*
* #param string $answer
* #return Answer
*/
public function setAnswer($answer)
{
$this->answer = $answer;
return $this;
}
/**
* Get answer
*
* #return string
*/
public function getAnswer()
{
return $this->answer;
}
}
I'm really not able to find what's wrong in my form...
The problem is that your question does not have any answers yet. Hence no forms. Try
$question = new Question();
$question->addAnswer(new Answer());
That will show an empty answer form.
Look in the cookbook to see how to use javascript to add answers dynamically from within the browser.