Symfony2 forms collection - php

I have, two entities, Topic and TopicContent are relation by topic_id.
topic_id in topic table is autoincremet , in topic_content it's not autoincrement.
Because, i need to get topic_id from Topic entity when query it's ok, and then insert data in topic_content table. Help me please, how to do this in symfony with orm. thanks.
TopicContent
namespace Socialist\ClubBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="topic_content")
*/
class TopicContent
{
/**
*
* #ORM\Column(name="topic_id", type="integer")
* #ORM\Id
*
*/
protected $topic_id;
/**
*
* #ORM\Column(name="topic_text", type="text", nullable=false)
*/
protected $topic_text;
/**
* #ORM\OneToOne(targetEntity="Topic", inversedBy="topicContent", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="topic_id", referencedColumnName="topic_id", onDelete="CASCADE")
*/
private $topic;
/**
* Set topic_id
*
* #param integer $topicId
* #return TopicContent
*/
public function setTopicId($topicId)
{
$this->topic_id = $topicId;
return $this;
}
/**
* Get topic_id
*
* #return integer
*/
public function getTopicId()
{
return $this->topic_id;
}
/**
* Set topic_text
*
* #param string $topicText
* #return TopicContent
*/
public function setTopicText($topicText)
{
$this->topic_text = $topicText;
return $this;
}
/**
* Get topic_text
*
* #return string
*/
public function getTopicText()
{
return $this->topic_text;
}
/**
* Set topic
*
* #param \Socialist\ClubBundle\Entity\Topic $topic
* #return TopicContent
*/
public function setTopic(\Socialist\ClubBundle\Entity\Topic $topic = null)
{
$this->topic = $topic;
return $this;
}
/**
* Get topic
*
* #return \Socialist\ClubBundle\Entity\Topic
*/
public function getTopic()
{
return $this->topic;
}
}
Topic
namespace Socialist\ClubBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="topic")
* #ORM\HasLifecycleCallbacks
*/
class Topic
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $topic_id;
/**
* #ORM\Column(type="string", length=200)
*/
protected $topic_title;
/**
* #ORM\Column(type="datetime")
*/
protected $topic_date_add;
/**
* #ORM\Column(type="datetime")
*/
protected $topic_date_edit;
/**
* Get topic_id
*
* #return integer
*/
public function getTopicId()
{
return $this->topic_id;
}
/**
* Set topic_title
*
* #param string $topicTitle
* #return Topic
*/
public function setTopicTitle($topicTitle)
{
$this->topic_title = $topicTitle;
return $this;
}
/**
* Get topic_title
*
* #return string
*/
public function getTopicTitle()
{
return $this->topic_title;
}
/**
* Set topic_date_add
*
* #param \DateTime $topicDateAdd
* #return Topic
*/
public function setTopicDateAdd($topicDateAdd)
{
$this->topic_date_add = $topicDateAdd;
return $this;
}
/**
* Get topic_date_add
*
* #return \DateTime
*/
public function getTopicDateAdd()
{
return $this->topic_date_add;
}
/**
* Set topic_date_edit
*
* #param \DateTime $topicDateEdit
* #return Topic
*/
public function setTopicDateEdit($topicDateEdit)
{
$this->topic_date_edit = $topicDateEdit;
return $this;
}
/**
* Get topic_date_edit
*
* #return \DateTime
*/
public function getTopicDateEdit()
{
return $this->topic_date_edit;
}
/**
* #ORM\PrePersist
*/
public function setTopicDateAddValue() {
if (!$this->getTopicDateAdd())
{
$this->topic_date_add = new \DateTime();
}
}
/**
* #ORM\PreUpdate
*/
public function setTopicDateEditValue()
{
$this->topic_date_edit = new \DateTime();
}
public function __construct()
{
$this->setTopicDateAdd(new \DateTime());
$this->setTopicDateEdit(new \DateTime());
}
/**
* #ORM\OneToOne(targetEntity="TopicContent", mappedBy="topic", cascade={"persist", "remove"})
*/
private $topicContent;
/**
* Set topicContent
*
* #param \Socialist\ClubBundle\Entity\TopicContent $topicContent
* #return Topic
*/
public function setTopicContent(\Socialist\ClubBundle\Entity\TopicContent $topicContent = null)
{
$this->topicContent = $topicContent;
return $this;
}
/**
* Get topicContent
*
* #return \Socialist\ClubBundle\Entity\TopicContent
*/
public function getTopicContent()
{
return $this->topicContent;
}
}
Topic Entity
public function __construct()
{
$this->topicContent = new \Doctrine\Common\Collections\ArrayCollection();
$this->setTopicDateAdd(new \DateTime());
$this->setTopicDateEdit(new \DateTime());
}
/**
* Set topicContent
*
* #param \Socialist\ClubBundle\Entity\TopicContent $topicContent
* #return Topic
*/
public function setTopicContent(\Socialist\ClubBundle\Entity\TopicContent $topicContent = null)
{
$this->topicContent = $topicContent;
return $this;
}
Topic Controller
public function createAction(Request $request)
{
$entity = new Topic();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('topic_show', array('id' => $entity->getTopicId())));
}
return $this->render('SocialistClubBundle:Topic:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}

After persisting your Topic Entity, you will get LastInserted topic id from your Topic entity
for example,
$em = $this->getDoctrine()->getManager();
$topic = new \Acme\TestBundle\Entity\Topic();
$topic->setTopicTitle('Your Title');
$em->persist($topic);
$em->flush(); //insert data into table
If insertion is ok $topic entity hold new row object inserted
You can get new topic id by getting
$newTopicId= $topic->getTopicId();
For Topic content Entity,
$topicContent= new new \Acme\TestBundle\Entity\TopicContent();
$topicContent->setTopicId($newTopicId);
$topicContent->setTopicText('Your topic text');
For avoid more confusion Please change your Topic Content Entity as follows,
namespace Socialist\ClubBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="topic_content")
*/
class TopicContent
{
/**
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*
*/
protected $id;
/**
*
* #ORM\Column(name="topic_text", type="text", nullable=false)
*/
protected $topic_text;
/**
* #ORM\OneToOne(targetEntity="Topic", inversedBy="topicContent", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="topic_id", referencedColumnName="topic_id", onDelete="CASCADE")
*/
private $topic;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set topic_text
*
* #param string $topicText
* #return TopicContent
*/
public function setTopicText($topicText)
{
$this->topic_text = $topicText;
return $this;
}
/**
* Get topic_text
*
* #return string
*/
public function getTopicText()
{
return $this->topic_text;
}
/**
* Set topic
*
* #param \Socialist\ClubBundle\Entity\Topic $topic
* #return TopicContent
*/
public function setTopic(\Socialist\ClubBundle\Entity\Topic $topic = null)
{
$this->topic = $topic;
return $this;
}
/**
* Get topic
*
* #return \Socialist\ClubBundle\Entity\Topic
*/
public function getTopic()
{
return $this->topic;
}
}`
The id should be primary key and autoincrement
this will resolve your all 'topic_id' burdens

Related

How to use getQuery()->getOneOrNullresult() return

in my test project I have 2 entities :
- endUser (extend of FOSUserBundle)
- Rezo (will containt approved relation between two members)
the both entities have been defined as :
EndUser Entity :
<?php
namespace Core\CustomerBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* EndUser
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Core\CustomerBundle\Entity\EndUserRepository")
*/
class EndUser extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="firstname", type="string", length=255)
*/
private $firstname;
/**
* #var string
* #ORM\Column(name="lastname", type="string", length=255)
*/
private $lastname;
/**
* #var \DateTime
*
* #ORM\Column(name="DateNaissance", type="datetime", nullable=true)
*/
private $DateNaissance;
/**
* #ORM\OneToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"persist", "merge", "remove"})
* #ORM\JoinColumn(name="adressbook_id", referencedColumnName="id", nullable=true)
*/
private $adressbook;
/**
* #ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Discipline", mappedBy="endusers")
*/
private $disciplines;
/**
* #ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Experiences", mappedBy="endusers")
*/
private $experiences;
/**
* #var string
* #ORM\Column(name="avatar", type="string", length=255, nullable=true)
*/
private $avatar;
/**
* #var string
* #ORM\Column(name="repository", type="string", length=255, nullable=true)
*/
private $repository;
/**
* #ORM\OneToMany(targetEntity="Core\MyEquiBookBundle\Entity\NiveauEndUser", mappedBy="enduser", cascade={"remove", "persist"})
*/
protected $niveaux;
/**
* #ORM\OneToMany(targetEntity="Core\GeneralBundle\Entity\Rezo", mappedBy="enduser", cascade={"remove", "persist"})
*/
protected $friends;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->disciplines = new \Doctrine\Common\Collections\ArrayCollection();
$this->niveaux = new \Doctrine\Common\Collections\ArrayCollection();
$this->experiences = new \Doctrine\Common\Collections\ArrayCollection();
$this->friends = new \Doctrine\Common\Collections\ArrayCollection();
$this->expiresAt = new \DateTime("+1 year");
$this->credentialsExpireAt = new \DateTime("+1 year");
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set avatar
*
* #param string $avatar
* #return EndUser
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* Get avatar
*
* #return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* Set repository
*
* #param string $repository
* #return EndUser
*/
public function setRepository($repository)
{
$this->repository = $repository;
return $this;
}
/**
* Get repository
*
* #return string
*/
public function getRepository()
{
return $this->repository;
}
/**
* Set adressbook
*
* #param \Core\CustomerBundle\Entity\EndUser $adressbook
* #return EndUser
*/
public function setAdressbook(\Core\CustomerBundle\Entity\EndUser $adressbook = null)
{
$this->adressbook = $adressbook;
return $this;
}
/**
* Get adressbook
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getAdressbook()
{
return $this->adressbook;
}
/**
* Add disciplines
*
* #param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
* #return EndUser
*/
public function addDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
{
$this->disciplines[] = $disciplines;
return $this;
}
/**
* Remove disciplines
*
* #param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
*/
public function removeDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
{
$this->disciplines->removeElement($disciplines);
}
/**
* Get disciplines
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDisciplines()
{
return $this->disciplines;
}
/**
* Add niveaux
*
* #param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
* #return EndUser
*/
public function addNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
{
$this->niveaux[] = $niveaux;
return $this;
}
/**
* Remove niveaux
*
* #param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
*/
public function removeNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
{
$this->niveaux->removeElement($niveaux);
}
/**
* Get niveaux
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getNiveaux()
{
return $this->niveaux;
}
/**
* Add experiences
*
* #param \Core\MyEquiBookBundle\Entity\Experiences $experiences
* #return EndUser
*/
public function addExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
{
$this->experiences[] = $experiences;
return $this;
}
/**
* Remove experiences
*
* #param \Core\MyEquiBookBundle\Entity\Experiences $experiences
*/
public function removeExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
{
$this->experiences->removeElement($experiences);
}
/**
* Get experiences
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getExperiences()
{
return $this->experiences;
}
/**
* Add friends
*
* #param \Core\GeneralBundle\Entity\Rezo $friends
* #return EndUser
*/
public function addFriend(\Core\GeneralBundle\Entity\Rezo $friends )
{
$this->friends[] = $friends;
return $this;
}
/**
* Remove friends
*
* #param \Core\GeneralBundle\Entity\Rezo $friends
*/
public function removeFriend(\Core\GeneralBundle\Entity\Rezo $friends)
{
$this->friends->removeElement($friends);
}
/**
* Get friends
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFriends()
{
return $this->friends;
}
/**
* Set firstname
*
* #param string $firstname
* #return EndUser
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
* #return EndUser
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set DateNaissance
*
* #param \DateTime $dateNaissance
* #return EndUser
*/
public function setDateNaissance($dateNaissance)
{
$this->DateNaissance = $dateNaissance;
return $this;
}
/**
* Get DateNaissance
*
* #return \DateTime
*/
public function getDateNaissance()
{
return $this->DateNaissance;
}
}
Rezo Entity :
<?php
namespace Core\GeneralBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Rezo
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Core\GeneralBundle\Entity\RezoRepository")
*/
class Rezo
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="RequestedDate", type="datetime")
*/
private $requestedDate;
/**
* #var \DateTime
*
* #ORM\Column(name="AcceptedDate", type="datetime", nullable=true)
*/
private $acceptedDate;
/**
* #ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\Enduser", inversedBy="friends", cascade={"refresh"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $enduser;
/**
* #ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"refresh"})
* #ORM\JoinColumn(name="friendwith", referencedColumnName="id")
*/
protected $friendwith;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set requestedDate
*
* #param \DateTime $requestedDate
* #return Rezo
*/
public function setRequestedDate($requestedDate)
{
$this->requestedDate = $requestedDate;
return $this;
}
/**
* Get requestedDate
*
* #return \DateTime
*/
public function getRequestedDate()
{
return $this->requestedDate;
}
/**
* Set acceptedDate
*
* #param \DateTime $acceptedDate
* #return Rezo
*/
public function setAcceptedDate($acceptedDate)
{
$this->acceptedDate = $acceptedDate;
return $this;
}
/**
* Get acceptedDate
*
* #return \DateTime
*/
public function getAcceptedDate()
{
return $this->acceptedDate;
}
/**
* Set enduser
*
* #param \Core\CustomerBundle\Entity\EndUser $enduser
* #return Rezo
*/
public function setEnduser(\Core\CustomerBundle\Entity\EndUser $enduser = null)
{
$this->enduser = $enduser;
return $this;
}
/**
* Get enduser
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getEnduser()
{
return $this->enduser;
}
/**
* Set friendwith
*
* #param \Core\CustomerBundle\Entity\EndUser $friendwith
* #return Rezo
*/
public function setFriendwith(\Core\CustomerBundle\Entity\EndUser $friendwith = null)
{
$this->friendwith = $friendwith;
return $this;
}
/**
* Get friendwith
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getFriendwith()
{
return $this->friendwith;
}
when I run :
app/console doctrine:schema:update --force
The following MySQL table has been created :
CREATE TABLE IF NOT EXISTS `Rezo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`friendwith` int(11) DEFAULT NULL,
`RequestedDate` datetime NOT NULL,
`AcceptedDate` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_681FC4BA76ED395` (`user_id`),
KEY `IDX_681FC4B1094AD75` (`friendwith`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
In the RezoController.php controller I would like to give to endUser opportunity to accept a contact request fot this I have created a function named : acceptnewrequestAction($id)
public function acceptnewrequestAction($id){
$em = $this->getDoctrine()->getManager();
$rezo = $em->getRepository('CoreGeneralBundle:Rezo')->find($id);
$user1 = $rezo->getEnduser();
$user2 = $rezo->getFriendwith();
$dateRequest = $rezo->getRequestedDate();
$rezo->setAcceptedDate(new \DateTime('now'));
$em->persist($rezo);
$em->flush();
/* check if inverse relation exist */
$query = $em->CreateQuerybuilder();
$query->select('t0.id');
$query->from('CoreGeneralBundle:Rezo','t0');
$query->where('t0.acceptedDate IS NULL');
$query->andWhere('t0.enduser = :userId');
$query->andWhere('t0.friendwith =:userId2');
$query->SetParameters(array('userId'=> $user2, 'userId2'=>$user1));
$result = $query->getQuery()->getOneOrNullResult();
if ( is_object($result))
{
$rezo = $em->getRepository('CoreGeneralBundle:Rezo')->findById($result->getId());
$rezo->setAcceptedDate(new \DateTime('now'));
} else {
$rezo = new Rezo();
$rezo->setRequestedDate(new \Datetime('now'));
$rezo->setAcceptedDate(new \DateTime('now'));
$rezo->Setenduser($user2);
$rezo->setFriendwith($user1);
}
$em->persist($rezo);
$em->flush();
return $this->render(controller('CoreGeneralBundle:Rezo:RezoList'));
}
I would like to know how I can use results to know if one object if found or return is Null and in case it exists update it or create a new one.
thank you for your help
getOneOrNullResult method tells you if any record in database is found, or not.
If it return null, it means that you have some results, and in your case you have to insert new one.
But when it exists some records, this method will return object instance of your entity. That means in your case you have to update existing record.
Please remember, that getOneOrNullResult method throws exception, when result set is not unique.

symfony2 doctrine exception insert

In symfony2 when I insert data into to database I receive an exception:
An exception occurred while executing 'INSERT INTO practice_user (user_id, practice_id, practice_text, type_id) VALUES (?, ?, ?, ?)' with params [null, "1", "test", 2]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null
PracticeUser.php:
<?php
namespace fl\PracticeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="practice_user")
*/
class PracticeUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $submit_practice_id;
/**
* #ORM\Column(type="integer")
*/
protected $user_id;
/**
* #ORM\Column(type="integer")
*/
protected $practice_id;
/**
* #ORM\Column(type="text")
*/
protected $practice_text;
/**
* #ORM\Column(type="integer")
*/
protected $type_id;
//many-to-one fos_user
/**
* #ORM\ManyToOne(targetEntity="fl\UserBundle\Entity\User", inversedBy="practices")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE", nullable=false))
*/
protected $user;
/**
* Get submit_practice_id
*
* #return integer
*/
public function getSubmitPracticeId()
{
return $this->submit_practice_id;
}
/**
* Set user_id
*
* #param integer $userId
* #return PracticeUser
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get user_id
*
* #return integer
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set practice_id
*
* #param integer $practiceId
* #return PracticeUser
*/
public function setPracticeId($practiceId)
{
$this->practice_id = $practiceId;
return $this;
}
/**
* Get practice_id
*
* #return integer
*/
public function getPracticeId()
{
return $this->practice_id;
}
/**
* Set practice_text
*
* #param string $practiceText
* #return PracticeUser
*/
public function setPracticeText($practiceText)
{
$this->practice_text = $practiceText;
return $this;
}
/**
* Get practice_text
*
* #return string
*/
public function getPracticeText()
{
return $this->practice_text;
}
/**
* Set type_id
*
* #param integer $typeId
* #return PracticeUser
*/
public function setTypeId($typeId)
{
$this->type_id = $typeId;
return $this;
}
/**
* Get type_id
*
* #return integer
*/
public function getTypeId()
{
return $this->type_id;
}
/**
* Set user
*
* #param \fl\UserBundle\Entity\User $user
* #return PracticeUser
*/
public function setUser(\fl\UserBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \fl\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
User.php
<?php
namespace fl\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
//one-to-one user_detail
/**
* #ORM\OneToOne(targetEntity="fl\UserBundle\Entity\UserDetail", mappedBy="user")
*/
protected $user_detail;
//one-to-one account
/**
* #ORM\OneToOne(targetEntity="fl\UserBundle\Entity\Account", mappedBy="user")
*/
protected $account;
//one-to-many language_user
/**
* #ORM\OneToMany(targetEntity="fl\UserBundle\Entity\LanguageUser", mappedBy="user")
*/
protected $languageusers;
//one-to-many practice_user
/**
* #ORM\OneToMany(targetEntity="fl\PracticeBundle\Entity\PracticeUser", mappedBy="user")
*/
protected $practices;
//one-to-many practice_review
/**
* #ORM\OneToMany(targetEntity="fl\PracticeBundle\Entity\PracticeReview", mappedBy="user")
*/
protected $reviews;
public function __construct()
{
parent::__construct();
// your own logic
//one to many with language_user table
$this->languageusers = new ArrayCollection();
//one-to-many practice_user
$this->practices = new ArrayCollection();
//one-to-many practice_review
$this->reviews = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set user_detail
*
* #param \fl\UserBundle\Entity\UserDetail $userDetail
* #return User
*/
public function setUserDetail(\fl\UserBundle\Entity\UserDetail $userDetail = null)
{
$this->user_detail = $userDetail;
return $this;
}
/**
* Get user_detail
*
* #return \fl\UserBundle\Entity\UserDetail
*/
public function getUserDetail()
{
return $this->user_detail;
}
/**
* Set account
*
* #param \fl\UserBundle\Entity\Account $account
* #return User
*/
public function setAccount(\fl\UserBundle\Entity\Account $account = null)
{
$this->account = $account;
return $this;
}
/**
* Get account
*
* #return \fl\UserBundle\Entity\Account
*/
public function getAccount()
{
return $this->account;
}
/**
* Add languageusers
*
* #param \fl\UserBundle\Entity\LanguageUser $languageusers
* #return User
*/
public function addLanguageuser(\fl\UserBundle\Entity\LanguageUser $languageusers)
{
$this->languageusers[] = $languageusers;
return $this;
}
/**
* Remove languageusers
*
* #param \fl\UserBundle\Entity\LanguageUser $languageusers
*/
public function removeLanguageuser(\fl\UserBundle\Entity\LanguageUser $languageusers)
{
$this->languageusers->removeElement($languageusers);
}
/**
* Get languageusers
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLanguageusers()
{
return $this->languageusers;
}
/**
* Add practices
*
* #param \fl\PracticeBundle\Entity\PracticeUser $practices
* #return User
*/
public function addPractice(\fl\PracticeBundle\Entity\PracticeUser $practices)
{
$this->practices[] = $practices;
return $this;
}
/**
* Remove practices
*
* #param \fl\PracticeBundle\Entity\PracticeUser $practices
*/
public function removePractice(\fl\PracticeBundle\Entity\PracticeUser $practices)
{
$this->practices->removeElement($practices);
}
/**
* Get practices
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPractices()
{
return $this->practices;
}
/**
* Add reviews
*
* #param \fl\PracticeBundle\Entity\PracticeReview $reviews
* #return User
*/
public function addReview(\fl\PracticeBundle\Entity\PracticeReview $reviews)
{
$this->reviews[] = $reviews;
return $this;
}
/**
* Remove reviews
*
* #param \fl\PracticeBundle\Entity\PracticeReview $reviews
*/
public function removeReview(\fl\PracticeBundle\Entity\PracticeReview $reviews)
{
$this->reviews->removeElement($reviews);
}
/**
* Get reviews
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getReviews()
{
return $this->reviews;
}
}
code when I try insert to the DataBase:
$user_id = $user->getId();
$submit_dictation = new PracticeUser();
$submit_dictation->setUserId($user_id);
$submit_dictation->setPracticeId($dictation_id);
$submit_dictation->setPracticeText($get_user_answer);
$submit_dictation->setTypeId(self::PRACTICE_DICTATION);
$em = $this->getDoctrine()->getManager();
$em->persist($submit_dictation);
$em->flush();
I also checked(with var_dump)the variable $user_id but is not null, I receive the user id.
Thanks in advance
You don't need $user_id, as FuzzyTree told you, but you need to fill the $user attribute by adding $submit_dictation->setUser($user) instead of $submit_dictation->setUserId($user->getId()) when you insert in the database.
This is why, among other things, Doctrine is useful, you don't need to understant how relations work : you don't need to give an id but just the entity itself.

Symfony2 - Doctrine exception: class used in the discriminator map does not exist

I am using Symfony2 with Doctrine and when I query from my controller the next error appears(it appears in the navigator when I call for the page):
Entity class 'Bdreamers\SuenoBundle\Entity\Sueno_video' used in the discriminator map of class 'Bdreamers\SuenoBundle\Entity\Sueno' does not exist.
I have one entity(superclass) called "Sueno" and two entities that extend from it(subclasses): Sueno_foto and Sueno_video.
When I load the fixtures, Doctrine works perfectly and fills the database without any issue, filling correctly the discriminator field "tipo" in the "Sueno" table. It also fills correctly the inherited entity table "Sueno_video" introducing the ID of "Sueno" and the exclusive fields of "Sueno_video"
This is the code of the entity file for "Sueno":
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="tipo", type="string")
* #ORM\DiscriminatorMap({"sueno" = "Sueno", "video" = "Sueno_video", "foto" = "Sueno_foto"})
*/
class Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario")
**/
private $usuario;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\SuenoBundle\Entity\Tag", inversedBy="suenos")
* #ORM\JoinTable(name="suenos_tags")
**/
private $tags;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_sigue")
* #ORM\JoinTable(name="usuarios_siguen")
**/
private $usuariosSeguidores;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_colabora")
* #ORM\JoinTable(name="usuarios_colaboran")
**/
private $usuariosColaboradores;
/**
* #var \DateTime
*
* #ORM\Column(name="fecha_subida", type="datetime")
*/
private $fechaSubida;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=40)
*/
private $titulo;
/**
* #var string
*
* #ORM\Column(name="que_pido", type="string", length=140)
*/
private $quePido;
/**
* #var string
*
* #ORM\Column(name="texto", type="string", length=540)
*/
private $texto;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set usuario
*
* #param string $usuario
* #return Sueno
*/
public function setUsuario($usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario()
{
return $this->usuario;
}
public function getTags()
{
return $this->tags;
}
/**
* Set usuariosSeguidores
*
* #param string $usuariosSeguidores
* #return Sueno
*/
public function setUsuariosSeguidores($usuariosSeguidores)
{
$this->usuariosSeguidores = $usuariosSeguidores;
return $this;
}
/**
* Get usuariosSeguidores
*
* #return string
*/
public function getUsuariosSeguidores()
{
return $this->usuariosSeguidores;
}
/**
* Set usuariosColaboradores
*
* #param string $usuariosColaboradores
* #return Sueno
*/
public function setUsuariosColaboradores($usuariosColaboradores)
{
$this->usuariosColaboradores = $usuariosColaboradores;
return $this;
}
/**
* Get usuariosColaboradores
*
* #return string
*/
public function getUsuariosColaboradores()
{
return $this->usuariosColaboradores;
}
/**
* Set fechaSubida
*
* #param \DateTime $fechaSubida
* #return Sueno
*/
public function setFechaSubida($fechaSubida)
{
$this->fechaSubida = $fechaSubida;
return $this;
}
/**
* Get fechaSubida
*
* #return \DateTime
*/
public function getFechaSubida()
{
return $this->fechaSubida;
}
/**
* Set titulo
*
* #param string $titulo
* #return Sueno
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set quePido
*
* #param string $quePido
* #return Sueno
*/
public function setQuePido($quePido)
{
$this->quePido = $quePido;
return $this;
}
/**
* Get quePido
*
* #return string
*/
public function getQuePido()
{
return $this->quePido;
}
/**
* Set texto
*
* #param string $texto
* #return Sueno
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
public function __construct() {
$this->usuariosColaboradores = new \Doctrine\Common\Collections\ArrayCollection();
$this->usuariosSeguidores = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return $this->getTitulo();
}
}
And this is the code for the entity Sueno_video:
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
*/
class Sueno_video extends Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="link_video", type="string", length=255)
*/
private $linkVideo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set linkVideo
*
* #param string $linkVideo
* #return Sueno_video
*/
public function setLinkVideo($linkVideo)
{
$this->linkVideo = $linkVideo;
return $this;
}
/**
* Get linkVideo
*
* #return string
*/
public function getLinkVideo()
{
return $this->linkVideo;
}
}
And finally the code in the controller:
public function homeAction()
{
$em = $this->getDoctrine()->getManager();
$suenos = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array(
'fechaSubida' => new \DateTime('now -2 days')
));
return $this->render('EstructuraBundle:Home:home_registrado.html.twig');
}
The autoloader won't be able to resolve those class names to file paths, hence why it can't find your classes.
Changing the file and class names to SuenoVideo and SuenoFoto.

Symfony2 FosRestBundle Expose Properties at runtime

I have following entity class and controller class. I have exposed selected properties.
In my "getAlbumsAction()" the output is the way i want.
But in "getAlbumAction($id)" i want to expose all the properties of the album class. How can i achive it? Have been searching around for a while but can't get it.
<?php
namespace MyBundle\RestApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
/**
* Album
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyBundle\RestApiBundle\Entity\AlbumRepository")
* #ExclusionPolicy("all")
*/
class Album
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #expose
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #expose
*/
private $name;
/**
*
* #ORM\OneToMany(targetEntity="Track", mappedBy="album")
*
*/
private $tracks;
/**
*
* #ORM\Column(name="likes", type="integer")
*
*
*/
private $likes;
/**
* #var \DateTime
*
* #ORM\Column(name="released", type="date")
*
*
*/
private $released;
/**
* #var \DateTime
*
* #ORM\Column(name="updated", type="date")
*/
private $updated;
/**
* #ORM\ManyToOne(targetEntity="Language", inversedBy="albums")
* #ORM\JoinColumn(name="language_id", referencedColumnName="id")
*
*
*/
private $language;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Album
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set released
*
* #param \DateTime $released
* #return Album
*/
public function setReleased($released)
{
$this->released = $released;
return $this;
}
/**
* Get released
*
* #return \DateTime
*/
public function getReleased()
{
return $this->released;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Album
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set language
*
* #param integer $language
* #return Album
*/
public function setLanguage($language)
{
$this->language = $language;
return $this;
}
/**
* Get language
*
* #return integer
*/
public function getLanguage()
{
return $this->language;
}
/**
* Constructor
*/
public function __construct()
{
$this->tracks = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tracks
*
* #param \MyBundle\RestApiBundle\Entity\Track $tracks
* #return Album
*/
public function addTrack(\MyBundle\RestApiBundle\Entity\Track $tracks)
{
$this->tracks[] = $tracks;
return $this;
}
/**
* Remove tracks
*
* #param \MyBundle\RestApiBundle\Entity\Track $tracks
*/
public function removeTrack(\MyBundle\RestApiBundle\Entity\Track $tracks)
{
$this->tracks->removeElement($tracks);
}
/**
* Get tracks
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTracks()
{
return $this->tracks;
}
/**
* Set likes
*
* #param integer $likes
* #return Album
*/
public function setLikes($likes)
{
$this->likes = $likes;
return $this;
}
/**
* Get likes
*
* #return integer
*/
public function getLikes()
{
return $this->likes;
}
}
<?php
namespace MyBundle\RestApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
class AlbumController extends Controller {
public function getAlbumsAction() {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MyBundleRestApiBundle:Album')->findAll();
return array(
'albums' => $entities,
);
}
private function getEntity($id) {
$entityName = 'MyBundleRestApiBundle:Album';
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($entityName)->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find organisation entity');
}
return $entity;
}
public function getAlbumAction($id) {
$entity = $this->getEntity($id);
return array(
'album' => $entity,
);
}
}
you have a typo:
'album' => $entities but must be 'album' => $entity
also if you want to return different fields/formats for one object check this out
http://jmsyst.com/libs/serializer/master/reference/annotations#groups

error upon flushing an object with array of objects in association

i'm receiving the following error message upon persisting and flushing an object with its associations:
Catchable Fatal Error: Argument 1 passed to
Doctrine\Common\Collections\ArrayCollection::__construct() must be of
the type array, object given, called in
.../vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 519 and defined in
.../vendor/doctrine/common/lib/Doctrine/Common/Collections/ArrayCollection.php line 48
what i have is a single table inheritance with this as the base object:
use Doctrine\ORM\Mapping as ORM;
/**
* ObjectData
*
* #ORM\Table(name="object_data")
* #ORM\Entity(repositoryClass="Edexp\CoreBundle\Entity\ObjectDataRepository")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="entity_name", type="string")
* #ORM\DiscriminatorMap({
* "request" = "Edexp\MessageBundle\Entity\RequestData"
* })
* #ORM\HasLifecycleCallbacks
*/
class ObjectData
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var User
*
* #ORM\OneToMany(targetEntity="User", mappedBy="data")
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="`key`", type="string", length=255)
*/
private $key;
/**
* #var string
*
* #ORM\Column(name="data", type="blob")
*/
private $data;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return ObjectData
*/
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 User $user
* #return ObjectData
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return User
*/
public function getUser()
{
return $this->user;
}
/**
* Set key
*
* #param string $key
* #return ObjectData
*/
public function setKey($key)
{
$this->key = $key;
return $this;
}
/**
* Get key
*
* #return string
*/
public function getKey()
{
return $this->key;
}
/**
* Set data
*
* #param string $data
* #return ObjectData
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* #return string
*/
public function getData()
{
return $this->data;
}
/**
* #ORM\PrePersist
*/
public function prepareForPersist()
{
$this->created_at = new \DateTime();
}
}
and an additional object that inherits from ObjectData:
use Doctrine\ORM\Mapping as ORM;
use MyProject\CoreBundle\Entity\ObjectData;
/**
* RequestData
*
* #ORM\Entity()
*/
class RequestData extends ObjectData
{
/**
* var Request $request
*
* #ORM\ManyToOne(targetEntity="Request", inversedBy="data")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id")
*/
private $request;
/**
* Set request
*
* #param Request $request
* #return RequestData
*/
public function setRequest($request)
{
$this->request = $request;
return $this;
}
/**
* Get request
*
* #return Request
*/
public function getRequest()
{
return $this->request;
}
}
and here's the object that utilizes the RequestData entity:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Request
*
* #ORM\Table(name="requests")
* #ORM\Entity(repositoryClass="RequestRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Request
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Message $message
*
* #ORM\ManyToOne(targetEntity="Message", inversedBy="requests")
*/
private $message;
/**
* #var RequestType $type
*
* #ORM\ManyToOne(targetEntity="RequestType")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
*/
private $type;
/**
* #var ArrayCollection $data
*
* #ORM\OneToMany(
* targetEntity="RequestData",
* mappedBy="request",
* cascade={"persist","remove"}
* )
*/
private $data;
/**
* #var datetime $created_at
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var text $comment
*
* #ORM\Column(name="comment", type="text")
*/
private $comment;
/**
* #var ArrayCollection $responses
*
* #ORM\OneToMany(
* targetEntity="Response",
* mappedBy="request",
* cascade={"persist","remove"}
* )
*/
private $responses;
public function __construct()
{
$this->data = new ArrayCollection();
$this->responses = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set message
*
* #param Message $message
*/
public function setMessage($message)
{
$this->message = $message;
}
/**
* Get message
*
* #return Message
*/
public function getMessage()
{
return $this->message;
}
/**
* Set type
*
* #param RequestType $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* #return RequestType
*/
public function getType()
{
return $this->type;
}
/**
* Set created_at
*
* #param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
}
/**
* Get created_at
*
* #return datetime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set comment
*
* #param text $comment
*/
public function setComment($comment)
{
$this->comment = $comment;
}
/**
* Get comment
*
* #return text
*/
public function getComment()
{
return $this->comment;
}
/**
* Add response
*
* #param Response $response
*/
public function addResponse($response)
{
foreach ( $this->responses as $r ) {
if ( $r->getUser() == $response->getUser() )
return;
}
$this->responses->add($response);
}
/**
* Get responses
*
* #return ArrayCollection
*/
public function getResponses()
{
return $this->responses;
}
public function hasResponse($user)
{
foreach ( $this->responses as $r ) {
if ( $r->getUser() == $user )
return $r;
}
return null;
}
public function addData($data)
{
$data->setRequest($this);
$this->data->add($data);
}
public function getData()
{
return $this->data;
}
/**
* #ORM\PrePersist
*/
public function prePersist()
{
$this->created_at = new \DateTime();
}
}
and finally the code that results in an error:
use MyProject\MessageBundle\Entity\Request as MyRequest;
$data = new RequestData();
$data->setUser($user);
$data->setKey('user_id');
$data->setData(6);
$req = new MyRequest();
$req->setMessage($message);
$req->setComment('bla');
$req->setType($doctrine->getRepository('MessageBundle:RequestType')->find(1));
$req->addData($data);
$em->persist($req);
$em->flush();
any suggestions as to what might be wrong here?
cheers
so here's what i had to do in order to make it work.
i had to change the association in ObjectData from:
#ORM\OneToMany(targetEntity="User", mappedBy="data")
to
#ORM\ManyToOne(targetEntity="User", inversedBy="data")
added the data field to the User entity accordingly.
/**
* #var ArrayCollection $data
*
* #ORM\OneToMany(targetEntity="ObjectData", mappedBy="user")
*/
private $data;
and voila, it worked.
Try:
$req->addData(array($data));
Explanation:
arrayCollection constructor type hints an array as its parameter, so you need to always pass it an array.

Categories