I try to work Doctrine2 Mapping out but after 8 hours of problems I really need your help, please.
I have 3 PostgreSQL table, The first one is house
Column | Type | Modifiers
---------+----------------+----------------------------------------------------
id | integer | not null default nextval('house_id_seq'::regclass)
name | character(255) | not null
address | character(255) |
rooms | integer | not null
Indexes:
"house_pkey" PRIMARY KEY, btree (id)
Referenced by:
TABLE "room" CONSTRAINT "room_house_id_fkey" FOREIGN KEY (house_id) REFERENCES house(id) ON UPDATE CASCADE ON DELETE CASCADE
and the second one is
Table "public.room"
Column | Type | Modifiers
-----------+------------------------+---------------------------------------------------
id | integer | not null default nextval('room_id_seq'::regclass)
name | character varying(255) |
room_type | integer |
vacant | boolean |
house_id | integer |
Indexes:
"room_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"room_house_id_fkey" FOREIGN KEY (house_id) REFERENCES house(id) ON UPDATE CASCADE ON DELETE CASCADE
and the last one is
Table "public.category"
Column | Type | Modifiers
------------+----------------+-------------------------------------------------------
id | integer | not null default nextval('category_id_seq'::regclass)
name | character(255) | not null
min_person | integer | not null
max_person | integer | not null
Indexes:
"category_pkey" PRIMARY KEY, btree (id)
I insert a FK on room_house_id that references house.id on House table .
In my Zend Framework2 I have my entities declare as
namespace Structures\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Structures\Entity\House
*
* #ORM\Table(name="house")
* #ORM\Entity(repositoryClass="Structures\Entity\Repository\HouseRepository")
*/
class House
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="house_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #var string $address
*
* #ORM\Column(name="address", type="string", length=255)
*/
private $address;
/**
* #var string $rooms
*
* #ORM\Column(name="rooms", type="integer", nullable=false)
*/
private $rooms;
/**
*
* #ORM\OneToMany(targetEntity="Structures\Entity\Room", mappedBy="house", cascade={"remove", "persist"})
*/
protected $house_room;
}
/**
* Structures\Entity\Room
*
* #ORM\Table(name="room")
* #ORM\Entity(repositoryClass="Structures\Entity\Repository\RoomRepository")
*/
class Room {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255,nullable=false)
*/
private $name;
/**
* #var boolean $vacant
*
* #ORM\Column(name="vacant", type="boolean", nullable=false)
*/
private $vacant;
/**
* #var Structures\Entity\Category
*
* #ORM\ManyToOne(targetEntity="Structures\Entity\Category" , cascade={"persist", "remove"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="room_type", referencedColumnName="id")
* })
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="Structures\Entity\House", inversedBy="house_room", cascade={"remove", "persist"})
*
*/
private $house;
}
/**
* Structures\Entity\Category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="Structures\Entity\Repository\CategoryRepository")
*
*/
class Category {
/**
* #var integer $id
*
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id
*
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*
*/
private $name;
/**
* #var integer $min_person
* #ORM\Column(name="min_person", type="integer" , nullable=false)
*/
private $min_person;
/**
* #var integer $max_person
* #ORM\Column(name="max_person", type="integer", nullable=false)
*/
private $max_person;
}
The relationship with Room and Category works as well.
The one concerns Room and House Table doesn't work at all. I cannot succeed in mapping the FK house_id with the id column on House table. All edit / save operation fails and the house_id is alway sets to NULL.
Please let me understand where I've made mistakes, I'm driving crazy
UPDATE :
I try to change the relationship between House and Room.
I delete the OneToMany on the House's side and change the ManyToOne in
/**
* #var Structure\Entity\Structure
*
* #ORM\ManyToOne(targetEntity="Structures\Entity\House")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="house_id", referencedColumnName="id", nullable=FALSE)
* })
*/
private $house;
When I fetch a room with
$room = $this->roomService->getRoom($id);
var_dump($room);
I have
object(Structures\Entity\Room)#383 (4)
{
["id":"Structures\Entity\Room":private]=> int(77)
["name":"Structures\Entity\Room":private]=> string(33) "my room"
["structure":"Structures\Entity\Room":private]=> object(Structures\Entity\House)#339 (4) {
["id":"Structures\Entity\House":private]=> int(3)
["name":"Structures\Entity\House":private]=> string(255) "hotel2b "
["address":"Structures\Entity\House":private]=> string(255) "hotel2b avenue"
["number_of_rooms":"Structures\Entity\House":private]=> int(20) }
["house_id":"Structures\Entity\Room":private]=> int(3)
}
If I use the OneToMany relationship var_dump($room) returns me a full page of I don't know what it means dump !
Still, when Edit a room, the column house_is is alway sets to NULL.
Still working on
UPDATE : 09 March
After a couple of hours spend reading tutorial, I write everything from start.
House Entity does not exits anymore. Structure Entity is the new one.
My problem : Use Doctrine2 to add and edit data with OneToMany and ManyToOne relationship.
My solution :
My Entities are
namespace Structures\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Structures\Entity\Structure
*
* #ORM\Table(name="room")
* #ORM\Entity(repositoryClass="Structures\Entity\Repository\RoomRepository")
*/
class Room {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255,nullable=false)
*
*/
private $name;
/**
* #var integer structure_id
* #ORM\Column(name="structure_id", type="integer", nullable=false)
*/
private $structure_id;
/**
* #var Structure\Entity\Structure
*
* #ORM\ManyToOne(targetEntity="Structure", inversedBy="rooms")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="structure_id", referencedColumnName="id")
* })
*/
private $structure;
public function __construct()
{
// $this->structure = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #param $data
*/
public function exchangeArray($data)
{
$this->fillWith($data);
}
/**
* #param $data
* #return Room
*/
public static function createFromArray($data)
{
$room = new Room();
$room->fillWith($data);
return $room;
}
public function updateFromArray($room)
{
$structure_id = $room->getStructureId();
$structure = $this->getStructure($structure_id);
$room->setStructure($structure);
return $room;
}
/**
* Sets id
* #param $i_id
*/
private function set_Id($i_id) {
$this->id = $i_id;
}
/**
* Gets id
* #return integer
*
*/
public function getId() {
return $this->id;
}
/**
* Set name
* #param string name
*
*/
public function setName($name) {
$this->name = $name;
}
/**
* Get name
* #return string
*
*/
public function getName() {
return $this->name;
}
public function getStructureId()
{
return $this->structure_id;
}
/**
*
* #return \Doctrine\Common\Collections\ArrayCollection|Structure\Entity\Structure
*/
public function getStructure() {
return $this->structure;
}
public function setStructure($structure) {
$this->structure = $structure;
}
And Structure
namespace Structures\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Structures\Entity\Structure
*
* #ORM\Table(name="structure")
* #ORM\Entity(repositoryClass="Structures\Entity\Repository\StructureRepository")
*/
class Structure {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="structure_id_seq", allocationSize=1, initialValue=1)
*
*/
private $id;
/**
* #var string address
*
* #ORM\Column(name="name", type="string", length=255,nullable=false)
*/
private $name;
/**
* #var string address
*
* #ORM\Column(name="address", type="string", length=255,nullable=false)
*
*/
private $address;
/**
* #var integer $rooms
*
* #ORM\Column(name="number_of_rooms", type="integer", nullable=false)
*/
private $number_of_rooms;
/**
* #ORM\OneToMany(targetEntity="Room", mappedBy="structure")
*/
private $rooms;
public function __construct() {
$this->rooms = new \Doctrine\Common\Collections\ArrayCollection();
}
public function exchangeArray($data) {
$this->fillWith($data);
}
public static function createFromArray($data)
{
$structure = new Structure();
$structure->fillWith($data);
return $structure;
}
private function set_Id($i_id) {
$this->id = $i_id;
}
/**
* Get id
* #return integer
*
*/
public function getId() {
return $this->id;
}
/**
* Set name
* #param string name
*
*/
public function setName($name) {
$this->name = $name;
}
/**
* Get name
* #return string
*
*/
public function getName() {
return $this->name;
}
/**
* Set address
* #param string address
*
*/
public function setAddress($address) {
$this->address = $address;
}
/**
* Get address
* #return string
*
*/
public function getAddress() {
return $this->address;
}
/**
* Set rooms
* #params integer rooms
*
*/
public function setRoom($room) {
$this->rooms = $room;
}
/**
* Get rooms
* #return integer
*
*/
public function getRoom() {
return $this->rooms;
}
/**
* #param $rooms
*/
public function setNumberOfRooms($number_of_rooms) {
$this->number_of_rooms = $number_of_rooms;
}
/**
* #return int
*/
public function getNumberOfRooms() {
return $this->number_of_rooms;
}
When I create a new Room I call a function to process my Zend\Form\Form data
public function processForm() {
if ($this->request->isPost()) {
// get the post data
$post = $this->request->getPost()->toArray();
// fill form
$this->form->setData($post);
// check if form is valid
if (!$this->form->isValid()) {
//prepare view
$view = new ViewModel(array('form' => $this->form,
'title' => 'Process Form :
Some errors during rooms processing'));
$view->setTemplate('structures/rooms/create');
return $view;
}
/* here I set the structure's Id from $structure obj gets from
$this->params('id')
*/
$structure = $this->getStructureFromQuerystring();
$post['structure_id'] = $structure->getId();
/* here I call a service method to create a Room instance and fills it
with data from $this->form
*/
$return = $this->roomService->insertRoomFromArray($post);
if ($return ) {
$this->flashMessenger()->setNamespace('rooms')->addMessage
('Operation executed correctly');
return $this->redirect()->toRoute('rooms/index');
}
}
Service Method does
public function insertRoomFromArray(array $am_formData) {
/* here I get the structure with the id stores in $am_formData*/
$structure = $this->getStructure($am_formData['structure_id']);
/* here I copy the $structure obj in $am_formData array */
$am_formData['structure'] = $structure;
/* here I call the Room Entity method createFromArray to create the Room */
$I_event = Room::createFromArray($am_formData);
/* here I call the mapper method to persist data */
$this->I_mapper->saveRoom($I_event);
return $I_event;
}
Room Entity
public static function createFromArray($data)
{
/* create new Room obj */
$room = new Room();
/* fill with data */
$room->fillWith($data);
return $room;
}
public function fillWith($data) {
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->name = (isset($data['name'])) ? $data['name'] : null;
/* here I copy the structure obj for relationship */
$this->structure = (isset($data['structure'])) ? $data['structure'] : null;
}
Mapper Entity
public function saveRoom(\Structures\Entity\Room $room)
{
$this->entityManager->persist($room);
$this->entityManager->flush();
}
It works and the new room has the correct structure's id sets.
What when I have to edit a room ? My solution
From the controller
public function editAction() {
/* Gets the room obj by $this->params('id') */
$room = $this->getRoomFromQueryString();
$this->form->bind($room);
$view = $this->processEditForm($room);
if (!$view instanceof ViewModel) {
$view = new ViewModel(array('form' => $this->form,
'title' => 'Edit Room: ' . $room->getName() ,
'structure' => $room->getStructure()));
$view->setTemplate('structures/rooms/create');
}
return $view;
}
private function processEditForm(Room $room)
{
if ($this->request->isPost()) {
$post = $this->request->getPost()->toArray();
/* here I put structure_id in $post array. */
$post['structure_id'] = $room->getStructure()->getId();
/* After this , my previous room obj is update with the data come from the
From, but the $structure entity is NULL. I don't know why. I will use the id
stores in $post['structure_id'] to fetch the Structure obj*/
$this->form->setData($post);
if (!$this->form->isValid()) {
$view = new ViewModel(array('form' => $this->form,
'title' => 'Some erros during rooms processing'));
$view->setTemplate('structures/rooms/create');
return $view;
}
$return = $this->roomService->updateRoomFromArray($room);
if ($return ) {
$this->flashMessenger()->setNamespace('rooms')->addMessage('Operation executed correctly');
return $this->redirect()->toRoute('rooms/index');
}
else {
echo "Errore durante Editing della room";
}
}
}
The Service Method to update data
public function updateRoomFromArray(Room $room) {
/* I call the Room Entity method to update my room /
$I_event = Room::updateFromArray($room);
/ persist data */
$this->I_mapper->updateRoom($room);
}
public function updateFromArray($room)
{
/* here I fetch the Structure's relationship my Room obj belongs to */
$structure_id = $room->getStructureId();
$structure = $this->getStructure($structure_id);
/* here I set the link*/
$room->setStructure($structure);
return $room;
}
public function updateRoom(\Structures\Entity\Room $room)
{
$this->entityManager->merge($room);
$this->entityManager->flush();
}
I'd like to know your opinion about my code, please. Is the right way to work with Doctrine2 ? thanks in advance
The syntax of your annotation is not correct.
Your ManyToOne association must have this following simple format:
#ManyToOne(targetEntity="Structures\Entity\House", inversedBy="features")
#JoinColumn(name="house_id", referencedColumnName="id")
Take a look at the documentation for more informations:
http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#one-to-many-bidirectional
Hope this helps.
Related
In Doctrine 2/Symfony 3 with Postgres as the database I am trying to create a table with following fields:
**actions-reviews**
id
action_id
action_task_id
document_id
review_to
review_date
review_description
review_by
is_effective
The table is either linked to a doc_id which is foreign key for an entity called Document or action_task_id for entity called ActionTask. In order to achieve this I am using inheritance mapping via the use of discriminator. In skipper the entity relationship look like this:
As you can see both the ActionTask and ActionReview are sub-set of Action entity.
My issue is when create the entities and run php bin/console doctrine:schema:update --force I get the following error:
[Doctrine\ORM\Mapping\MappingException]
No identifier/primary key specified for Entity "AppBundle\Entity\ActionTask
Review". Every Entity must have an identifier/primary key.
Reading the forums I add #ORM/Id to ActionTaskReview entity and then it updates the DB without any errors. However when I look at the postgres table only the document_id field is there not the action_task_id field. What I am doing wrong as the document_id does not throw the same error when I exclude #ORM/Id?
My Doctrine entities look like:
ActionReview.php
/**
* #ORM\Entity
* #ORM\Table(name="actions_reviews")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="owner", type="string")
* #ORM\DiscriminatorMap({"document":"AppBundle\Entity\DocumentActionReview","action_task":"AppBundle\Entity\ActionTaskReview"})
* #Discriminator(field = "owner", map = {"document": "AppBundle\Entity\DocumentActionReview", "action_task": "AppBundle\Entity\ActionTaskReview"})
*/
abstract class ActionReview
{
/**
* #ORM\Id
* #ORM\Column(type="guid")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $review_date;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $review_description;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $is_effective;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Action", inversedBy="action_review")
* #ORM\JoinColumn(name="action_id", referencedColumnName="id")
*/
private $action;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Employee")
* #ORM\JoinColumn(name="review_to", referencedColumnName="id")
*/
private $review_to;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Employee")
* #ORM\JoinColumn(name="review_by", referencedColumnName="id")
*/
private $review_by;
/**
* Get id
*
* #return guid
*/
public function getId()
{
return $this->id;
}
/**
* Set reviewDate
*
* #param \DateTime $reviewDate
*
* #return ActionReview
*/
public function setReviewDate($reviewDate)
{
$this->review_date = $reviewDate;
return $this;
}
/**
* Get reviewDate
*
* #return \DateTime
*/
public function getReviewDate()
{
return $this->review_date;
}
/**
* Set reviewDescription
*
* #param string $reviewDescription
*
* #return ActionReview
*/
public function setReviewDescription($reviewDescription)
{
$this->review_description = $reviewDescription;
return $this;
}
/**
* Get reviewDescription
*
* #return string
*/
public function getReviewDescription()
{
return $this->review_description;
}
/**
* Set isEffective
*
* #param boolean $isEffective
*
* #return ActionReview
*/
public function setIsEffective($isEffective)
{
$this->is_effective = $isEffective;
return $this;
}
/**
* Get isEffective
*
* #return boolean
*/
public function getIsEffective()
{
return $this->is_effective;
}
/**
* Set action
*
* #param \AppBundle\Entity\Action $action
*
* #return ActionReview
*/
public function setAction(\AppBundle\Entity\Action $action = null)
{
$this->action = $action;
return $this;
}
/**
* Get action
*
* #return \AppBundle\Entity\Action
*/
public function getAction()
{
return $this->action;
}
/**
* Set reviewTo
*
* #param \AppBundle\Entity\Employee $reviewTo
*
* #return ActionReview
*/
public function setReviewTo(\AppBundle\Entity\Employee $reviewTo = null)
{
$this->review_to = $reviewTo;
return $this;
}
/**
* Get reviewTo
*
* #return \AppBundle\Entity\Employee
*/
public function getReviewTo()
{
return $this->review_to;
}
/**
* Set reviewBy
*
* #param \AppBundle\Entity\Employee $reviewBy
*
* #return ActionReview
*/
public function setReviewBy(\AppBundle\Entity\Employee $reviewBy = null)
{
$this->review_by = $reviewBy;
return $this;
}
/**
* Get reviewBy
*
* #return \AppBundle\Entity\Employee
*/
public function getReviewBy()
{
return $this->review_by;
}
}
ActionTaskReview.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Exclude;
/**
* ActionTaskReview
* #ORM\Entity
*/
class ActionTaskReview
{
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\ActionTask", inversedBy="action_review")
* #ORM\JoinColumn(name="action_task_id", referencedColumnName="id") \AppBundle\Entity\ActionTask
*/
private $action_task;
/**
* Set actionTask
*
* #param \AppBundle\Entity\ActionTask $actionTask
*
* #return ActionTaskReview
*/
public function setActionTask(\AppBundle\Entity\ActionTask $actionTask = null)
{
$this->action_task = $actionTask;
return $this;
}
/**
* Get actionTask
*
* #return \AppBundle\Entity\ActionTask
*/
public function getActionTask()
{
return $this->action_task;
}
}
DocumentActionReview.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="documents_actions_reviews")
*/
class DocumentActionReview extends \AppBundle\Entity\ActionReview
{
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Document", inversedBy="action_review")
* #ORM\JoinColumn(name="document_id", referencedColumnName="id")
*/
private $document;
/**
* Set document
*
* #param \AppBundle\Entity\Document $document
*
* #return DocumentActionReview
*/
public function setDocument(\AppBundle\Entity\Document $document = null)
{
$this->document = $document;
return $this;
}
/**
* Get document
*
* #return \AppBundle\Entity\Document
*/
public function getDocument()
{
return $this->document;
}
}
First of all, your ActionTaskReview should extend ActionReview:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Exclude;
/**
* ActionTaskReview
* #ORM\Entity
*/
class ActionTaskReview extends ActionReview
{
...
}
Than I am not sure what you want to achieve, as you are using Single Table Inheritance but are setting the #ORM\Table(name="documents_actions_reviews") annotation on the DocumentActionReview class. Either switch to Class Table Inheritance if you need own tables for your inherited entities or remove the annotation.
Every entity class must have an identifier/primary key. You can select the field that serves as the identifier with the #Id annotation.
`/**
* #ORM\Column(type="integer")
* #ORM\Id
* #GeneratedValue
*/
private $id;`
I have a problem. I moved website to another hosting(so I exported DB and imported to new hosting).
But now, when I trying to add new record to database. I have an error stn like ID 1 already exist. But I have almost 500 records in the table.
What can I do to fix it?
Sorry I've should provide more information:
I exported and imported database through phppgadmin I didn't use migrations bundle.
Here is my entity:
class Products
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="serial_number", type="string", length=255, nullable=true)
*/
private $serial;
/**
* #var string
* #Expose
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
* #Expose
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
* #var string
* #ORM\Column(name="note", type="text", nullable=true)
*/
private $note;
/**
* #var int
*
* #ORM\Column(name="views", type="bigint", nullable=true)
*/
private $views;
/**
* #ORM\ManyToMany(targetEntity="Models")
* #ORM\JoinTable(name="products_models",
* joinColumns={#ORM\JoinColumn(name="product_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="model_id", referencedColumnName="id")}
* )
*/
private $models;
/**
* #ORM\OneToOne(targetEntity="ProductDetails", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="details_id", referencedColumnName="id")
*/
private $details;
/**
* #var File
* #Expose
* #ORM\OneToMany(targetEntity="ProductImages", mappedBy="product", cascade={"persist", "remove"})
* #ORM\OrderBy({"id" = "ASC"})
*
*/
private $images;
/**
* #var File
*
* #ORM\OneToMany(targetEntity="Cart", mappedBy="productId", cascade={"persist"})
*
*/
private $cart;
/**
* #var string
*
* #ORM\Column(name="price", type="integer", length=255, nullable=true)
*/
private $price;
/**
* #var string
*
* #ORM\Column(name="bought_price", type="integer", length=255, nullable=true)
*/
private $boughtPrice;
/**
* #var string
*
* #ORM\Column(name="old_price", type="integer", length=255, nullable=true)
*/
private $oldPrice;
/**
* #var bool
*
* #ORM\Column(name="is_active", type="boolean", nullable=true)
*/
private $isActive;
/**
* #var bool
*
* #ORM\Column(name="is_accessory", type="boolean", nullable=true)
*/
private $isAccessory;
/**
* #ORM\ManyToOne(targetEntity="AccessoryCategory")
* #ORM\JoinColumn(name="accessory_category_id", referencedColumnName="id")
*/
private $accessoryCategory;
/**
* #var bool
*
* #ORM\Column(name="is_special", type="boolean", nullable=true)
*/
private $isSpecial;
/**
* #var integer
*
* #ORM\Column(name="quantity", type="integer", nullable=true)
*/
private $quantity;
/**
* created Time/Date
*
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=false)
*/
protected $createdAt;
/**
* updated Time/Date
*
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime", nullable=false)
*/
protected $updatedAt;
/**
* #var boolean
*
* #ORM\Column(name="seller", type="boolean", length=255, nullable=true)
*/
private $seller;
/**
* Set createdAt
*
* #ORM\PrePersist
*/
public function setCreatedAt()
{
$this->createdAt = new \DateTime();
$this->updatedAt = new \DateTime();
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #ORM\PreUpdate
*/
public function setUpdatedAt()
{
$this->updatedAt = new \DateTime();
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Products
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set url
*
* #param string $url
*
* #return Products
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set note
*
* #param string $note
*
* #return Products
*/
public function setNote($note)
{
$this->note = $note;
return $this;
}
/**
* Get note
*
* #return string
*/
public function getNote()
{
return $this->note;
}
/**
* Set views
*
* #param integer $views
*
* #return Products
*/
public function setViews($views)
{
$this->views = $views;
return $this;
}
/**
* Get views
*
* #return integer
*/
public function getViews()
{
return $this->views;
}
/**
* Set price
*
* #param integer $price
*
* #return Products
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return integer
*/
public function getPrice()
{
return $this->price;
}
/**
* Set boughtPrice
*
* #param integer $boughtPrice
*
* #return Products
*/
public function setBoughtPrice($boughtPrice)
{
$this->boughtPrice = $boughtPrice;
return $this;
}
/**
* Get boughtPrice
*
* #return integer
*/
public function getBoughtPrice()
{
return $this->boughtPrice;
}
/**
* Set isActive
*
* #param boolean $isActive
*
* #return Products
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Set isAccessory
*
* #param boolean $isAccessory
*
* #return Products
*/
public function setIsAccessory($isAccessory)
{
$this->isAccessory = $isAccessory;
return $this;
}
/**
* Get isAccessory
*
* #return boolean
*/
public function getIsAccessory()
{
return $this->isAccessory;
}
/**
* Set quantity
*
* #param integer $quantity
*
* #return Products
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* #return integer
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* Set details
*
* #param \Web\AdminBundle\Entity\ProductDetails $details
*
* #return Products
*/
public function setDetails(\Web\AdminBundle\Entity\ProductDetails $details = null)
{
$this->details = $details;
return $this;
}
/**
* Get details
*
* #return \Web\AdminBundle\Entity\ProductDetails
*/
public function getDetails()
{
return $this->details;
}
/**
* Add image
*
* #param \Web\AdminBundle\Entity\ProductImages $image
*
* #return Products
*/
public function addImage(\Web\AdminBundle\Entity\ProductImages $image)
{
$this->images[] = $image;
return $this;
}
/**
* Remove image
*
* #param \Web\AdminBundle\Entity\ProductImages $image
*/
public function removeImage(\Web\AdminBundle\Entity\ProductImages $image)
{
$this->images->removeElement($image);
}
/**
* Get images
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getImages()
{
return $this->images;
}
/**
* Add cart
*
* #param \Web\AdminBundle\Entity\Cart $cart
*
* #return Products
*/
public function addCart(\Web\AdminBundle\Entity\Cart $cart)
{
$this->cart[] = $cart;
return $this;
}
/**
* Remove cart
*
* #param \Web\AdminBundle\Entity\Cart $cart
*/
public function removeCart(\Web\AdminBundle\Entity\Cart $cart)
{
$this->cart->removeElement($cart);
}
/**
* Get cart
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCart()
{
return $this->cart;
}
/**
* Set isSpecial
*
* #param boolean $isSpecial
*
* #return Products
*/
public function setIsSpecial($isSpecial)
{
$this->isSpecial = $isSpecial;
return $this;
}
/**
* Get isSpecial
*
* #return boolean
*/
public function getIsSpecial()
{
return $this->isSpecial;
}
/**
* Set accessoryCategory
*
* #param \Web\AdminBundle\Entity\AccessoryCategory $accessoryCategory
*
* #return Products
*/
public function setAccessoryCategory(\Web\AdminBundle\Entity\AccessoryCategory $accessoryCategory = null)
{
$this->accessoryCategory = $accessoryCategory;
return $this;
}
/**
* Get accessoryCategory
*
* #return \Web\AdminBundle\Entity\AccessoryCategory
*/
public function getAccessoryCategory()
{
return $this->accessoryCategory;
}
/**
* Set oldPrice
*
* #param integer $oldPrice
*
* #return Products
*/
public function setOldPrice($oldPrice)
{
$this->oldPrice = $oldPrice;
return $this;
}
/**
* Get oldPrice
*
* #return integer
*/
public function getOldPrice()
{
return $this->oldPrice;
}
/**
* Set serial
*
* #param string $serial
*
* #return Products
*/
public function setSerial($serial)
{
$this->serial = $serial;
return $this;
}
/**
* Get serial
*
* #return string
*/
public function getSerial()
{
return $this->serial;
}
/**
* Constructor
*/
public function __construct()
{
$this->models = new \Doctrine\Common\Collections\ArrayCollection();
$this->images = new \Doctrine\Common\Collections\ArrayCollection();
$this->cart = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add model
*
* #param \Web\AdminBundle\Entity\Models $model
*
* #return Products
*/
public function addModel(\Web\AdminBundle\Entity\Models $model)
{
$this->models[] = $model;
return $this;
}
/**
* Remove model
*
* #param \Web\AdminBundle\Entity\Models $model
*/
public function removeModel(\Web\AdminBundle\Entity\Models $model)
{
$this->models->removeElement($model);
}
/**
* Get models
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getModels()
{
return $this->models;
}
/**
* Set seller
*
* #param boolean $seller
*
* #return Products
*/
public function setSeller($seller)
{
$this->seller = $seller;
return $this;
}
/**
* Get seller
*
* #return boolean
*/
public function getSeller()
{
return $this->seller;
}
I'm adding new like this:
$em = $this->getDoctrine()->getManager();
$products = new Products();
$article->setTitle('here is the title');
....
$em->persist($products);
$em->flush();
this should set id to like 488 but it's trying to set it to 1. And I don't know why? Might be some cache? But php bin/console cache:clear doesn't change anything.
Doctrine use sequence with the auto strategy and Postgres.
Maybe sequence values has been lost when export/import db.
Identify the sequence used by your ID and try to execute :
ALTER SEQUENCE sequence_name RESTART WITH your_next_free_id;
hi i have got the same problem when i Import my database the probléme s like they say sequence.
But because i have more than 100 table i can't reset the sequence one by one So i Found this query it create for all your table an sql query to update the sequence by the max Id, you have just to copy the result and execute it
SELECT 'SELECT SETVAL(' ||
quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
pg_depend AS D,
pg_class AS T,
pg_attribute AS C,
pg_tables AS PGT
WHERE S.relkind = 'S'
AND S.oid = D.objid
AND D.refobjid = T.oid
AND D.refobjid = C.attrelid
AND D.refobjsubid = C.attnum
AND T.relname = PGT.tablename
ORDER BY S.relname;
I think as other have suggested its not the issue with symfony or doctrine , instead its postgresql common issue, you can check a solution here
Make sure you are using same version, I am not sure if this behavior differs from version to version.
You can change the current value of the auto increment manually like this :
ALTER TABLE products AUTO_INCREMENT=501;
My problem is this : I have an entity that contains user data , such as:
age
name
surname
address
phone
...
My goal is to make a form where using a query can bring all this data and fill my form with the data , so that the user can modify it if you ever change the cell for example, or changing the direction of his house.
The company and I have made the entity and the form, and consulting the table will do. My problem is how to fill the form fields with the data that I get from the table.
My entity (DatosEntity):
<?php
namespace Proyecto\LavocBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Datos
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Proyecto\LavocBundle\Entity\DatosRepository")
*/
class Datos
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="empresa", type="string", length=50)
*/
private $empresa;
/**
* #var integer
*
* #ORM\Column(name="cuit", type="integer")
*/
private $cuit;
/**
* #var string
*
* #ORM\Column(name="localidad", type="string", length=50)
*/
private $localidad;
/**
* #var string
*
* #ORM\Column(name="calle", type="string", length=40)
*/
private $calle;
/**
* #var integer
*
* #ORM\Column(name="altura", type="integer")
*/
private $altura;
/**
* #var integer
*
* #ORM\Column(name="areaTel", type="integer")
*/
private $areaTel;
/**
* #var integer
*
* #ORM\Column(name="telefono", type="integer")
*/
private $telefono;
/**
* #var integer
*
* #ORM\Column(name="areaCel", type="integer")
*/
private $areaCel;
/**
* #var integer
*
* #ORM\Column(name="celular", type="integer")
*/
private $celular;
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="datos")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $personales;
/**
* #var string
*
* #ORM\Column(name="email", type="string")
*/
private $email;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set empresa
*
* #param string $empresa
* #return Datos
*/
public function setEmpresa($empresa)
{
$this->empresa = $empresa;
return $this;
}
/**
* Get empresa
*
* #return string
*/
public function getEmpresa()
{
return $this->empresa;
}
/**
* Set cuit
*
* #param integer $cuit
* #return Datos
*/
public function setCuit($cuit)
{
$this->cuit = $cuit;
return $this;
}
/**
* Get cuit
*
* #return integer
*/
public function getCuit()
{
return $this->cuit;
}
/**
* Set localidad
*
* #param string $localidad
* #return Datos
*/
public function setLocalidad($localidad)
{
$this->localidad = $localidad;
return $this;
}
/**
* Get localidad
*
* #return string
*/
public function getLocalidad()
{
return $this->localidad;
}
/**
* Set calle
*
* #param string $calle
* #return Datos
*/
public function setCalle($calle)
{
$this->calle = $calle;
return $this;
}
/**
* Get calle
*
* #return string
*/
public function getCalle()
{
return $this->calle;
}
/**
* Set altura
*
* #param integer $altura
* #return Datos
*/
public function setAltura($altura)
{
$this->altura = $altura;
return $this;
}
/**
* Get altura
*
* #return integer
*/
public function getAltura()
{
return $this->altura;
}
/**
* Set telefono
*
* #param integer $telefono
* #return Datos
*/
public function setTelefono($telefono)
{
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* #return integer
*/
public function getTelefono()
{
return $this->telefono;
}
/**
* Set area
*
* #param integer $area
* #return Datos
*/
public function setAreaTel($areaTel)
{
$this->areaTel = $areaTel;
return $this;
}
/**
* Get area
*
* #return integer
*/
public function getAreaTel()
{
return $this->areaTel;
}
/**
* Set celular
*
* #param integer $celular
* #return Datos
*/
public function setCelular($celular)
{
$this->celular = $celular;
return $this;
}
/**
* Get celular
*
* #return integer
*/
public function getCelular()
{
return $this->celular;
}
/**
* Set areaCel
*
* #param integer $areaCel
* #return Datos
*/
public function setAreaCel($areaCel)
{
$this->areaCel = $areaCel;
return $this;
}
/**
* Get areaCel
*
* #return integer
*/
public function getAreaCel()
{
return $this->areaCel;
}
/**
* Set email
*
* #param integer $email
* #return Datos
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return integer
*/
public function getEmail()
{
return $this->email;
}
/**
* Set personales
*
* #param string $personales
* #return Datos
*/
public function setPersonales($personales)
{
$this->personales = $personales;
return $this;
}
/**
* Get personales
*
* #return string
*/
public function getPersonales()
{
return $this->personales;
}
}
My DatosType:
<?php
namespace Proyecto\LavocBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class DatosType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('empresa');
$builder->add('cuit');
$builder->add('localidad');
$builder->add('calle');
$builder->add('altura');
$builder->add('areaTel');
$builder->add('telefono');
$builder->add('areaCel');
$builder->add('celular');
}
public function getName()
{
return 'datos_form';
}
}
The consultation on the controller but did not know how to do it. Now , do not like taking the data I receive and dump them in the form.
Thank you very much and sorry for the trouble
I think what you want to do can be done by following these steps :
Start by collecting your User data in a variable we will call $user
Then, give this $userto be hydrated by your form, like this :
$form = $this->createForm(new UserType(), $user);
Treat your form like you would normaly do. The values found in the entity should be automaticaly filled in your form.
Hope this helps.
Your action could be something like this:
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('LavocBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createForm(new UserType(), $entity);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
);
}
I have a symfony2 Form CategoryType with a buildForm:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('language', 'entity', array(
'class' => 'Evr\HomeBundle\Entity\Language',
'property' => 'language'
)
)
->add('category', 'text', array('label' => 'category.category', 'required' => true));
}
As you can expect, I have two entities Category and Language, of which Category is a child of Language (One language can have many categories, and one category belongs to 1 or 0 language)
Category
<?php
namespace Evr\HomeBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*
* #ORM\Table(name="ev_category")
* #ORM\Entity
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="category_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #ORM\ManyToOne(targetEntity="Language",inversedBy="categories")
* #ORM\JoinColumn(name="language_id",referencedColumnName="language_id")
*/
private $language;
/**
* #var string
*
* #ORM\Column(name="category", type="string", length=255)
*/
private $category;
/**
* #ORM\OneToMany(targetEntity="Subcategory", mappedBy="category")
*/
protected $subcategories;
public function __construct(){
$this->subcategories=new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set language
*
* #param integer $language
* #return Category
*/
public function setLanguage($language) {
$this->language = $language;
return $this;
}
/**
* Get language
*
* #return integer
*/
public function getLanguage() {
return $this->language;
}
/**
* Set category
*
* #param \string $category
* #return Category
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \string
*/
public function getCategory()
{
return $this->category;
}
}
Language
<?php
namespace Evr\HomeBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Language
*
* #ORM\Table(name="ev_language")
* #ORM\Entity
*/
class Language
{
/**
* #var integer
*
* #ORM\Column(name="language_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="language", type="string", length=128)
*/
private $language;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=10)
*/
private $code;
/**
* #var boolean
*
* #ORM\Column(name="direction", type="boolean")
*/
private $direction;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="language")
*/
protected $categories;
/**
* #ORM\OneToMany(targetEntity="Country", mappedBy="language")
*/
protected $countries;
public function __construct(){
$this->categories=new ArrayCollection();
$this->countries=new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set language
*
* #param string $language
* #return Language
*/
public function setLanguage($language)
{
$this->language = $language;
return $this;
}
/**
* Get language
*
* #return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* Set code
*
* #param string $code
* #return Language
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set direction
*
* #param boolean $direction
* #return Language
*/
public function setDirection($direction)
{
$this->direction = $direction;
return $this;
}
/**
* Get direction
*
* #return boolean
*/
public function getDirection()
{
return $this->direction;
}
}
When editing a category, I need to display the current values in a form, so that the user can modify them and save.
Here I have a controller editAction(), whose mission is to display the edition form:
public function editAction($id) { //id of the category to modify
$category = $this->getDoctrine()->getRepository('EvrHomeBundle:Category')->find($id); //return the category with id
$categoryForm = $this->createForm(new CategoryType(),$category); //building the form
return $this->render('EvrAdminBundle:Categories:edit.html.twig', array('categoryForm' => $categoryForm->createView(), 'category' => $category));
}//render the form
Remember that the CategoryType has an element which type : entity, which loads the languages in A select box.
But when trying to populate the form CategoryType with the current data (Category and Language) , Symfony returns an Error : Entity Not Found
Symfony doesn't specify in which line the error occures, but I think it's around this line :
$categoryForm = $this->createForm(new CategoryType(),$category); //building the form
Because when I remove the second argument of createForm : $category, it displays an empty form (just like an add category form
Is there a solution for this issue? And how can I create a form with current data from the database, considering the fact that it contains an entity element.
Thank you
If you have a database without referential integrity enforced, then you can delete a record even though another record is pointing to it (they should be linked through a foreign key). Then when you try to grab the record it seem to work but when you want to access attributes of that entity (this is when the real access to the database occurs) it can't find the entity with that record_id and so "Entity not found".
Ex:
$user=new User();
$car=$user->getCar(); /*The user had a CAR record assigned with Id = 1 but the record was
deleted.
The record USER still has the id of 1.*/
/*No error up till here*/
$carName=$car->getName(); /*Error occurs because it tries to grab the record with id of 1
which was deleted*/
Try to use \ in front of entity namespace:
'class' => '\Evr\HomeBundle\Entity\Language',
I got 2 tables connected with a foreign key (user_id is in the table persons). I'm able to add data to both of the tables by executing 1 form.
but on the execute i expected that the foreign key would automatically be generated in the table persons.
Here are my enities
USERS
namespace Geo\CityTroopersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Geo\CityTroopersBundle\Entity\Users
*
* #ORM\Table(name="users")
* #ORM\Entity
*/
class Users
{
//Vanaf hier bijgevoegd
protected $adress;
protected $person;
//Einde zelf toegevoegde properties
/**
* #var integer $userId
*
* #ORM\Column(name="user_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $userId;
/**
* #var string $user
*
* #ORM\Column(name="user_password", type="string", length=128, nullable=true)
*/
private $userPassword;
/**
* #var string $userEmail
*
* #ORM\Column(name="user_email", type="string", length=128, nullable=true)
*/
private $userEmail;
/**
* #var string $userImage
*
* #ORM\Column(name="user_image", type="string", length=128, nullable=true)
*/
private $userImage;
/**
* #var string $userQuestion
*
* #ORM\Column(name="user_question", type="string", length=128, nullable=true)
*/
private $userQuestion;
/**
* #var string $userAnswer
*
* #ORM\Column(name="user_answer", type="string", length=128, nullable=true)
*/
private $userAnswer;
/**
* #var \DateTime $userCreateddate
*
* #ORM\Column(name="user_createddate", type="datetime", nullable=true)
*/
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->userId;
}
/**
* Set userPassword
*
* #param string $userPassword
* #return Users
*/
public function setUserPassword($userPassword)
{
$this->userPassword = $userPassword;
return $this;
}
/**
* Get userPassword
*
* #return string
*/
public function getUserPassword()
{
return $this->userPassword;
}
/**
* Set userEmail
*
* #param string $userEmail
* #return Users
*/
public function setUserEmail($userEmail)
{
$this->userEmail = $userEmail;
return $this;
}
/**
* Get userEmail
*
* #return string
*/
public function getUserEmail()
{
return $this->userEmail;
}
/**
* Set userImage
*
* #param string $userImage
* #return Users
*/
public function setUserImage($userImage)
{
$this->userImage = $userImage;
return $this;
}
/**
* Get userImage
*
* #return string
*/
public function getUserImage()
{
return $this->userImage;
}
/**
* Set userQuestion
*
* #param string $userQuestion
* #return Users
*/
public function setUserQuestion($userQuestion)
{
$this->userQuestion = $userQuestion;
return $this;
}
/**
* Get userQuestion
*
* #return string
*/
public function getUserQuestion()
{
return $this->userQuestion;
}
/**
* Set userAnswer
*
* #param string $userAnswer
* #return Users
*/
public function setUserAnswer($userAnswer)
{
$this->userAnswer = $userAnswer;
return $this;
}
/**
* Get userAnswer
*
* #return string
*/
public function getUserAnswer()
{
return $this->userAnswer;
}
//Zelf toegevoegde getters & setters
public function getPerson()
{
return $this->person;
}
public function setPerson(Persons $person = null)
{
$this->person = $person;
}
public function getAdress()
{
return $this->adress;
}
public function setAdress(Adresses $adress = null)
{
$this->adress = $adress;
}
}
PERSONS
namespace Geo\CityTroopersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Geo\CityTroopersBundle\Entity\Persons
*
* #ORM\Table(name="persons")
* #ORM\Entity
*/
class Persons
{
/**
* #var integer $personId
*
* #ORM\Column(name="person_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $personId;
/**
* #var integer $adressId
*
* #ORM\Column(name="adress_id", type="integer", nullable=false)
*/
private $adressId;
/**
* #var string $personFamilyname
*
* #ORM\Column(name="person_familyname", type="string", length=64, nullable=false)
*/
private $personFamilyname;
/**
* #var string $personFirstname
*
* #ORM\Column(name="person_firstname", type="string", length=64, nullable=false)
*/
private $personFirstname;
/**
* #var boolean $personGender
*
* #ORM\Column(name="person_gender", type="boolean", nullable=false)
*/
private $personGender;
/**
* #var string $personNationality
*
* #ORM\Column(name="person_nationality", type="string", length=45, nullable=false)
*/
private $personNationality;
/**
* #var Users
*
* #ORM\ManyToOne(targetEntity="Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
private $user;
/**
* Get personId
*
* #return integer
*/
public function getPersonId()
{
return $this->personId;
}
/**
* Set adressId
*
* #param integer $adressId
* #return Persons
*/
public function setAdressId($adressId)
{
$this->adressId = $adressId;
return $this;
}
/**
* Get adressId
*
* #return integer
*/
public function getAdressId()
{
return $this->adressId;
}
/**
* Set personFamilyname
*
* #param string $personFamilyname
* #return Persons
*/
public function setPersonFamilyname($personFamilyname)
{
$this->personFamilyname = $personFamilyname;
return $this;
}
/**
* Get personFamilyname
*
* #return string
*/
public function getPersonFamilyname()
{
return $this->personFamilyname;
}
/**
* Set personFirstname
*
* #param string $personFirstname
* #return Persons
*/
public function setPersonFirstname($personFirstname)
{
$this->personFirstname = $personFirstname;
return $this;
}
/**
* Get personFirstname
*
* #return string
*/
public function getPersonFirstname()
{
return $this->personFirstname;
}
/**
* Set personGender
*
* #param boolean $personGender
* #return Persons
*/
public function setPersonGender($personGender)
{
$this->personGender = $personGender;
return $this;
}
/**
* Get personGender
*
* #return boolean
*/
public function getPersonGender()
{
return $this->personGender;
}
/**
* Set personNationality
*
* #param string $personNationality
* #return Persons
*/
public function setPersonNationality($personNationality)
{
$this->personNationality = $personNationality;
return $this;
}
/**
* Get personNationality
*
* #return string
*/
public function getPersonNationality()
{
return $this->personNationality;
}
/**
* Set user
*
* #param Geo\CityTroopersBundle\Entity\Users $user
* #return Persons
*/
public function setUser(\Geo\CityTroopersBundle\Entity\Users $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return Geo\CityTroopersBundle\Entity\Users
*/
public function getUser()
{
return $this->user;
}
}
CONTROLLER
class UserController extends Controller
{
public function registerAction(Request $request)
{
$user = new Users();
$person = new Persons();
//$adress = new Adresses();
$form = $this->createForm(new UserType(), $user);
if ($request->getMethod() == 'POST'){
$form->bindRequest($request);
if($form->isValid()){
$person = $form->getData();
//$adress = $form->getData();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->persist($user->getPerson());
//$em->persist($user->getAdress());
$em->flush();
return $this->redirect($this->generateUrl('indexpage'));
}
}
return $this->render('GeoCityTroopersBundle:User:register.html.twig', array(
'form' => $form->createView(),
));
}
}
USERTYPE
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('person', new PersonType());
$builder->add('userEmail');
$builder->add('userPassword', 'password');
$builder->add('userImage');
$builder->add('userQuestion');
$builder->add('userAnswer');
//$builder->add('adress', new AdressType());
}
public function getName()
{
return 'user';
}
}
PERSONTYPE
class PersonType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('personFamilyname');
$builder->add('personFirstname');
$builder->add('personNationality');
$builder->add('personGender');
//$builder->add('adressId');
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Geo\CityTroopersBundle\Entity\Persons',
);
}
public function getName()
{
return 'person';
}
}
I have tried to add in the annotations of Users the following:
/**
* Bidirectional (INVERSE SIDE)
* #ORM\OneToOne(targetEntity="Persons",cascade={"persist"})
*
*/
But this didn't worked either.
I have a feeling there is something wrong with the setup of my database, the relation between persons and users is one to one.
update: Deleted unnecessary
Thanks in advance