TYPO3 extbase Column value NULL - typo3

TYPO3 10.4.16
I have created a table with a column year int(11) DEFAULT NULL . But if I try to use the repository with $track->setYear(null), I always get the error message Incorrect integer value: '' for column 'year' at row 1.
Does extbase not allow an empty value or do I have to change something?
Edit:
/**
* year
*
* #var int
*/
protected $year = null;
/**
* Returns the year
*
* #return int $year
*/
public function getYear()
{
return $this->year;
}
/**
* Sets the year
*
* #param int $year
* #return void
*/
public function setYear($year)
{
$this->year = $year;
}

Related

TYPO3 TCA own evaluation (validation) for a combination of three fields

I read the documentation on the eval property for type=input and tried my own evaluations.
It should evaluate a combination of three fields with this logic:
start_date AND end_date required (not empty) OR date_on_request required.
Class is loaded and function evaluateFieldValue() works, but I miss the feedback in form.
<?php
namespace Vendor\Extension\Evaluation;
class StartDateAndEndDateOrDateOnRequestEvaluation {
/**
* JavaScript code for client side validation/evaluation
*
* #return string JavaScript code for client side validation/evaluation
*/
public function returnFieldJS() {
return 'return value;';
}
/**
* Server-side validation/evaluation on saving the record
*
* #param string $value The field value to be evaluated
* #param string $is_in The "is_in" value of the field configuration from TCA
* #param bool $set Boolean defining if the value is written to the database or not.
* #return string Evaluated field value
*/
public function evaluateFieldValue($value, $is_in, &$set) {
foreach($_POST['data']['tx_extension_domain_model_course'] as $id => $course) {
if ( (!empty($course['start_date']) && !empty($course['start_date'])) || !empty($course['date_on_request']) ) {
$set = true;
} else {
$set = false;
}
}
return $value;
}
/**
* Server-side validation/evaluation on opening the record
*
* #param array $parameters Array with key 'value' containing the field value from the database
* #return string Evaluated field value
*/
public function deevaluateFieldValue(array $parameters) {
return $parameters['value'];
}
}
Im looking for examples, how I can do validation in JavaScript (returnFieldJS):
How I get the three fields?
How can set error classes?
And what should I check in evaluateFieldValue()?
The methods returnFieldJS() and deevaluateFieldValue(array $parameters) are not called for datetime fields. That is why I guess there is no clean way to add JavaScript validation to datetime fields.
To get an error message in the backend you can however use the FlashMessageService. I implemented an example to check that the course_end date is after the course_start date:
<?php
namespace Vendor\Extension\Evaluation;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
class StartDateAndEndDateOrDateOnRequestEvaluation {
/**
* JavaScript code for client side validation/evaluation
*
* #return string JavaScript code for client side validation/evaluation
*/
public function returnFieldJS()
{
return 'return value;';
}
/**
* Server-side validation/evaluation on saving the record
*
* #param string $value The field value to be evaluated
* #param string $is_in The "is_in" value of the field configuration from TCA
* #param bool $set Boolean defining if the value is written to the database or not.
* #return string Evaluated field value
*/
public function evaluateFieldValue($value, $is_in, &$set)
{
$formData = GeneralUtility::_GP('data');
$courseId = key($formData['tx_extension_domain_model_course']);
$course = $formData['tx_extension_domain_model_course'][$courseId];
$courseStart = new \DateTime($course['course_start']);
$courseEnd = new \DateTime($course['course_end']);
if ($courseStart > $courseEnd) {
$this->flashMessage('Invalid field value', 'Course end date can not be before course start date!', FlashMessage::ERROR);
$set = false; //do not save value
}
return $value;
}
/**
* Server-side validation/evaluation on opening the record
*
* #param array $parameters Array with key 'value' containing the field value from the database
* #return string Evaluated field value
*/
public function deevaluateFieldValue(array $parameters)
{
return $parameters['value'];
}
/**
* #param string $messageTitle
* #param string $messageText
* #param int $severity
*/
protected function flashMessage($messageTitle, $messageText, $severity = FlashMessage::ERROR)
{
$message = GeneralUtility::makeInstance(
FlashMessage::class,
$messageText,
$messageTitle,
$severity,
true
);
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$flashMessageService = $objectManager->get(FlashMessageService::class);
$messageQueue = $flashMessageService->getMessageQueueByIdentifier();
$messageQueue->addMessage($message);
}
}

TYPO3 Extbase - Query only records within a certain uid range

How can I render only records within a certain uid range? Let's say I want to render only records where it's uid is e.g. higher than 100 and lower than 200
/**
* action list
*
* #return void
*/
public function listAction() {
$this->view->assign('records', $this->testRepository->findAll());
}
Do I need to use the MathUtility and it's isIntegerInRange ... but how?
Use your own function in repository.
Controller
/**
* action list
*
* #param integer $minUid
* #param integer $maxUid
* #return void
*/
public function listAction() {
$this->view->assign('records', $this->testRepository->findUidRange($minUid,$maxUid));
}
Repository
/**
* Find records filtered by uid from to
*
* #param integer $minUid
* #param integer $maxUid
* #return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface|array The query result
*/
public function findUidRange($minUid = NULL, $maxUid = NULL) {
$query = $this->createQuery();
return $query->matching(
$query->logicalAnd(
$query->greaterThan('uid', $minUid),
$query->lessThan('uid', $maxUid),
$query->equals('deleted', 0)
))->execute();
}

FOSRestbundle: Serialize public method as field

I have an entity with a standard datetimetz field, with standard getter and setter:
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetimetz")
*/
private $date;
/**
* Get date
*
* #return \DateTime
*/
public function getDate() {
return $this->date;
}
/**
* Set date
*
* #param \DateTime $date
* #return ConsultationForm
*/
public function setDate($date) {
$this->date = $date;
return $this;
}
Serializing this works just fine, and the resulting JSON has a field with a string representing the date:
date: "2014-07-05T09:53:45+0200"
However, I would like to add a second method to my entity, which returns a Unix timestamp corresponding to my date object:
/**
* Get date as millis
*
* #return int
*/
public function getDateAsMillis() {
return $this->date->getTimestamp();
}
I would like the output of this method to also be encoded as a JSON field in the resulting object:
dateAsMillis: 3423435252345232
How can I instruct the FOSRestbundle or the serialiser to do this automatically?
You can use the VirtualPropery annotation (http://jmsyst.com/libs/serializer/master/reference/annotations#virtualproperty)
/**
* #JMS\VirtualProperty
* #JMS\SerializedName("dateAsMillis")
*/
public function getDateAsMillis() {
return $this->date->getTimestamp();
}

Doctrine2 drive me crazy with OneToMany and ManyToOne relationship

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.

Entity Not Found error in symfony2 Form

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',