FAQ Database Discussion Community


Symfony2 trouble passing data into form dropdown

php,symfony2,drop-down-menu,doctrine2,symfony-forms
I am learning symfony, I am stuck on this problem for hours now. I am trying to get userIDs from FOSuserbundle into my own form's Dropdown. but unable to succeed.. am doing something wrong with the __construct function I guess.. here's the code ShiftType.php: class ShiftType extends AbstractType { protected...

Doctrine persist entity with inverse relation not work

symfony2,doctrine2,entity
I'm trying to save two entities linked. Product entity may have any or many entities ProviderRate. When I try to save the product entity, it tells me that ProviderRate related entity has not assigned one of their required fields. I need to save a product with no need to assign...

Doctrine batch inserting uses 2GB of Ram

php,symfony2,doctrine2,doctrine,batch-insert
I am trying to insert approximately 200k of records with Symfony2 and Doctrine via Doctrine Fixtures Bundle. I am using flush and clear but at the end script uses 1.8 GB of RAM. This is the class that loads SmartMeter entities into database: <?php namespace HTEC\SmartMeteringAPIBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface;...

Manage translation fields in symfony form type generated with KnpLabs/DoctrineBehaviors and Translatable

php,symfony2,doctrine2,bundle,symfony-forms
I'm new to Symfony and I'm using version 2.6 I wanted to create a translation for my products following https://github.com/KnpLabs/DoctrineBehaviors#translatable I ended up with: <?php namespace KhaliBundle\Entity; use Gedmo\Mapping\Annotation as Gedmo; use Doctrine\ORM\Mapping as ORM; use Knp\DoctrineBehaviors\Model as ORMBehaviors; /** * Product * * @ORM\Table(name="products") * @ORM\Entity */ class Product...

RowAction in a Vector source APYDataGridBundle Symfony 2

symfony2,vector,datagrid,doctrine2
Im stuck with this issue for a few days, i currently have grid filled with results from a Stored Procedure, i run a nativequery with the SP, get the results in an Array and use the Vector class from ApyDataGrid to display the results. All of the above is working...

AppBundle's Best Practice and how-to go further

php,symfony2,doctrine2,entity
According to this page on the documentation website of symfony they explain how to address your application logic and the best practices. The one thing I am missing in this documentation is the way to store and use your entities. There is a small section that covers the usage of...

Infinite loop in Doctrine event listener when trying to save additional entity

php,symfony2,orm,doctrine2,doctrine
I want that every time a new Distance entity (from Place_A to Place_B) is saved, the reverse distance (from Place_B to Place_A) gets inserted too into the DB. My problem is the following listener loops infinitely (hence the counter): class Listener { public $count; public function prePersist(LifecycleEventArgs $eventArgs) { if...

Query Builder with join and condition in Many to many relation

php,symfony2,doctrine2,doctrine,symfony-2.3
I have a many to many relation with Employee and MembreFamille. And i want to get all MembreFamilles that have an Employee. This is my query : class MembreFamilleRepository extends EntityRepository { public function getMembres($emp) { $qb = $this->createQueryBuilder('a'); $qb ->leftJoin('a.employees', 'employees'); $qb ->where('employees.id = :id') ->setParameter('id', $emp); return $qb...

Symfony2 - Access of the Repository from Entity

php,symfony2,doctrine2
I'm trying to learn Symfony, and I found it don't access the doctrine from the entity. I created an Entity <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Facility * * @ORM\Table() * @ORM\Entity * @ORM\Entity(repositoryClass="AppBundle\Entity\FacilityRepository") */ class Facility { /** * @var integer * * @ORM\Column(name="id", type="integer") *...

How do I make this param converter work?

php,symfony2,doctrine2
Using Symfony2/Doctrine ORM I have an entity "ProductCategory". ProductCategory ( fields ) id (int) displayName (string) I'm wanting to create a route with param converters. This is what I have. According to the documentation here it should work. /** * @Route("/products/{category_name}") * @ParamConverter("c", class="AppBundle:ProductCategory", options={"mapping": { "displayName" = "category_name"}}) */...

Symfony time field not using the same date as the corresponding entity property

php,symfony2,datetime,doctrine2,doctrine
I've got an entity with a duration property, declared as time type: /* @ORM\Column(type="time") */ private $duration; In my Symfony form, this duration property maps to a time field: $builder->add( 'duration', 'time', [ 'input' => 'datetime', 'widget' => 'text' ] ) As the time type does not exist in PHP,...

Doctrine returning datetime object instead of date string, jqGrid jsonmap not working

jquery,json,symfony2,doctrine2,jqgrid
I'm trying to display date in my jqgrid. But doctrine is returning a datetime object instead of a normal string type value which jqgrid can display. I can think of two possible solutions: (1) Change doctrine's return type to somehow return a string so that jqgrid can display it without...

Symfony 2 - How to set relationship between three entities having many to many relationship among them

php,orm,doctrine2,symfony-2.3
I am using Symfony2 for my application and using Doctrine .orm.yml files for relation mapping. I have three entities as follows: user entity which contains id(integer primary key), user_name(varchar) portfolio entity which contains id(integer primary key), name(varchar), user_id (FK from user to identify who created the portfolio) progress entity which...

doctrine/migrations incompatible with symfony 2.2.*

php,symfony2,doctrine2,doctrine
long story short: Im using Symfony 2.2.* (yes, its old) and a DEV-Enviroment using a deploy script. This script runs "composer update". Every thing works fine until today. Now I recive this error: - Conclusion: remove symfony/symfony v2.2.11 - Conclusion: don't install symfony/symfony v2.2.11 - Conclusion: don't install symfony/symfony v2.2.10...

Store entity from session doesn't work => $em->persist()

php,symfony2,doctrine2
at first: Sorry for my poor english :-) A beginner need help! I have 3 entities/tables: Tables: contact_person id, title, firstname, surname, adress_id address id, street, zip, city, country_id country (fix values) id, name, code 1, Austria, AT 2, Germany, DE ... Entities: /** * ContactPerson * * @ORM\Table(name="contact_person") *...

typo3 flow persist updated relation

php,doctrine2,typo3,typo3-flow
I have an issue TYPO3 Flow updating my relations. Am I wrong, that Flow should update changed relations automatically, so I don't have to update the related entities with the respective repository? Example 1: I have a model "Project" with multiple "Job" childs on attribute "jobs". If I do: $project->setJobs($collectionOfJobs);...

How to set Symfony 2 slave database config in php

php,mysql,symfony2,configuration,doctrine2
I have a Symfony 2.7 application with Doctrine. I am trying to setup slave databases. We use lockerbox to manage our server configs. We use Constants to keep all database configuration, ex: <?php define('DB_MASTER_HOST', 'localhost'); define('DB_MASTER_USER', 'user'); define('DB_MASTER_PASS', 'password'); define('DB_MASTER_NAME', 'db_name'); define('DB_SLAVE_ENABLED', FALSE); define('DB_SLAVE_HOST', 'server-1,server-2'); define('DB_SLAVE_USER', 'username1,username2'); define('DB_SLAVE_PASS', 'password1,password2'); define('DB_SLAVE_NAME',...

doctrine does not hydration when select custom fields

doctrine2,doctrine,doctrine-query
i have tried select fields with doctrine query buidler. $queryBuilder = $entityManager->createQueryBuilder(); $queryBuilder->select('au.id, au.firstName') ->from('Api\V1\Entity\AgencyUser', 'au') ->orderBy('au.firstName', 'asc'); $queryBuilder->andWhere('au.agency = :agencyId') ->setParameter('agencyId', $agency->getId()); print_r($queryBuilder->getQuery()->getResult(Query::HYDRATE_OBJECT));exit; result : Array ( [0] => Array ( [id] => 1 [firstName] => agency ) ) why this is an array ? i want to hydrated...

Class inheritance in Symfony2

php,symfony2,doctrine2
I'm a bit confused about an error that I'm getting: Undefined method 'getAsArray'. The method name must start with either findBy or findOneBy! getAsArray() is a method in my repository class, it's called in PostsController.php like so: $categoriesList = $this->getDoctrine()->getRepository('AirBlogBundle:Category')->getAsArray(); CategoryRepository.php is defined like this: namespace Air\BlogBundle\Repository; class CategoryRepository extends...

JMS Deserialize ArrayCollection in Object

php,serialization,doctrine2,jms-serializer
I'm trying to use JMS serializer in my application (not Symfony) and would like to deserialize a JSON object to the Doctrine Entity. The plain properties are getting properly deserialized, but I can't get the ArrayCollections to work. This is an excerpt of my product JSON: { "id": 2, "name":...

Wrong datatype for referenced entity on Doctrine ObjectSelect

php,zend-framework,orm,doctrine2
I have a form which uses Doctrine's ObjectSelect to make a dropdown $this->add(array( 'name' => 'category', 'type' => 'DoctrineModule\Form\Element\ObjectSelect', 'options' => array( 'label' => 'Category', 'object_manager' => $em, 'target_class' => 'Blog\Entity\Category', 'property' => 'name' ), 'attributes' => array( 'required' => true ) )); the issue I have, is that this...

Jms serializer @JMS\Inline() annotation overrides an actual id

php,symfony2,doctrine2,jmsserializerbundle,jms-serializer
I have product and product_detail tables in database. Every product has a product detail. class Product { /** * @var ProductDetail * @JMS\ReadOnly() * @ORM\OneToOne(targetEntity="ApiBundle\Entity\ProductDetail", mappedBy="product", cascade={"persist"}) * @JMS\Inline() */ private $detail; } I use @JMS\Inline() annotation to show only detail information of product_detail table. But when I serialize a...

Cannot add having condition on undefined result variable in a non aggregated query

php,symfony2,doctrine2
I'm executing this query in an entity repository and keep getting Cannot add having condition on undefined result variable but the query has no aggregation at all. Why is this happening to me? public function getPersonalizableItemsByOwner(User $owner) { $qb = $this ->getEntityManager() ->createQuery('SELECT pi FROM '.$this->getEntityName().' pi WHERE order_id =...

Symfony Entity query builder that checks for free spots

php,mysql,symfony2,doctrine2,dql
First off all: I know the title isn't helping, but it's the best I can think of. So I've got two entities in Symfony one is called Team and the other one Slot the Slot entity has a name, a start and end date and all that stuff. Besides that...

“Unable to open database file” error when trying to load Doctrine Data Fixtures in Symfony

symfony2,doctrine2,behat
I'm using pdo_mysql for prod, stag and dev environments and pdo_sqlite for test environment. The problem is that loading Doctrine Data Fixtures generates unable to open database file error as shown below. I assigned the permissions to cache folder as defined in symfony website and also tried with 777 but...

Error while generating doctrine entities with FOSUser Bundle in Symfony2

symfony2,doctrine2,fosuserbundle
I'm using FOSUser bundle and everything went ok until I tried to create the database entities, I get this error: It has nothing to do with the bug in Symfony 2.5, I'm using version 2.7 Case mismatch between loaded and declared class names: App\UserBundle\Entity\user vs App\UserBundle\Entity\User This is my config...

A group of entities aren't updated (Symfony2 & Doctrine)

php,symfony2,doctrine2
I have a problem with this code: $elements = $em ->getRepository('AppBundle:MyElementsEntity') ->findByLinkType($linkType); // This returns SEVEN elements foreach ($elements as $e) { $beginDate = $e->getBeginDate(); $beginDate->setTime($begin->format('H'), $begin->format('i')); $endDate = $e->getEndDate(); $endDate->setTime($end->format('H'), $end->format('i')); $e->setEndDate($endDate); $e->setBeginDate($beginDate); $em->persist($e); $em->flush(); } As you can see, it fetches some elements from the...

Doctrine EntityManager clear method in nested entities

php,symfony2,doctrine2,batch-processing
I would like to use doctrine batch insert processing in order to optimize insert of a big amount of entities. The problem is with Clear method. It says that this method detach all entities that are managed by EntityManager. So what should I do in a situation where I have...

Controller - No access in class - Entity

symfony2,doctrine2,symfony-forms
I got this error message, but I don't really understand why. Neither the property "categories" nor one of the methods "addCategory()"/"removeCategory()", "setCategories()", "categories()", "__set()" or "__call()" exist and have public access in class "Checkout\Bundle\ItemBundle\Entity\Item". The thing is, in my entity "Item" I really have all of this stuff: /** *...

How to save additional entity while persisting another in Doctrine?

symfony2,orm,doctrine2,doctrine
I've got a Place entity and a Distance one, like so: class Place { /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** @ORM\Column(type="string", length=62, nullable=false) */ private $name; /** @ORM\OneToMany(targetEntity="Distance", mappedBy="origin") */ protected $distancesTo; /** @ORM\OneToMany(targetEntity="Distance", mappedBy="destination") */ protected $distancesFrom; } class Distance { /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ private...

Assign many items to one category - OneToMany Relation

symfony2,doctrine2,symfony-forms
I want to assign many items to one category. I'm using Symfony 2.6.7. I'm not at the owning side here. If I open this URI: /category/2/assign [x] Item 1 [x] Item 2 (Save Button) I have the possibility to chose many items with checkboxes. This is my db table "Item",...

Add brands through company, it's possible? How?

php,symfony2,doctrine2,mapping,symfony-2.6
I have this two tables (see pics below) mapped as follow: class Brand { ... /** * @var Company * * @ORM\ManyToOne(targetEntity="Company") * @ORM\JoinColumn(name="companies_id", referencedColumnName="id") */ protected $company; } class Company { ... } I need to add support for add a new Brand from Company but I have not...

Doctrine “A new entity was found through the relationship” error

php,symfony2,doctrine2,doctrine
First off I want to say I've read through all the docs and googled this plenty before posting this question. I know what that error means (unpersisted entity in a relationship) I'm getting this error where I think I shouldn't be getting it. I have a OneToMany bi-directional relationship as...

Symfony2 AnnotationException You have to enable OPCache or ZendOptimizer

symfony2,doctrine2,annotations,doctrine,opcache
I have application based on the Symfony2 framework. I have moved to the production environment, website was running fine (I was trying to adjust caching - on my hosting is xcache). But suddenly I has this error: Fatal error: Uncaught exception 'Doctrine\Common\Annotations\AnnotationException' with message 'You have to enable opcache.save_comments=1 or...

Symfony crud generated index view, where is not have references fields

php,symfony2,doctrine2,crud,symfony-forms
Symfony command doctrine:generate:crud generated controller< form and its views. But, index does not contain other table references fields "many-to-one". Entity model: <?php namespace Acme\Bundle\AdminBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Albums * * @ORM\Table(name="albums", indexes={@ORM\Index(name="IDX_F4E2474F3D8E604F", columns={"parent"})}) * @ORM\Entity */ class Albums { /** * @var integer * * @ORM\Column(name="id", type="integer",...

Doctrine OneByOne's and Date

php,symfony2,doctrine2,entity
I am using Symfony 2.7.1 and I seem to have a problem while using my News Entity. I am trying to use the published_at in my twig template. I tried using {{ news_item.published_at|date("m/d/Y") }} but that seems to follow up by a fatal error: Method "published_at" for object "AppBundle\Entity\News" does...

one to many unidirectional doctrine persistance

php,doctrine2
I am having some real problems with doctrines unidirectional persistence. /** @Entity @Table(name="va_area") **/ class Area extends ReferenceData { } /** @Entity @Table(name="network") **/ class Network { /** * @ManyToOne(targetEntity="Area") * @JoinColumn(name="area_code", referencedColumnName="id") **/ protected $area; } when I try to set the area value on network by using either...

Removing related entity Symfony2

symfony2,orm,doctrine2
I have related entities. Many to Many relation and the annotation exists on only one entity: /** * @ORM\ManyToMany(targetEntity="Event") * @ORM\JoinTable(name="viewed_events", * joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="event_id", referencedColumnName="id")} * ) **/ protected $viewedEvents; The problem is when I try to delete Event entity I get Integrity constraint violation: 1451 Cannot delete...

Symfony and doctrine getting null response from sql database query

php,mysql,json,symfony2,doctrine2
How do I query the mySql DB? For some reason I am not getting the response I expect below. I have a message table with a messageBody column that I would like to get. I am also trying to return it as an array of JSON formatted objects. /** *...

ORM/Doctrine2 - When to persist?

php,orm,doctrine2
This has been bugging me for a while. In Doctrine2, we have the: ObjectManager function: void persist(object $object = null) You only need to call it on new entities. My question though, is "when" should it be called? Immediately after creating the entity, or immediately before flushing it? I can't...

Search from comma separated values in column

sql,postgresql,doctrine2,doctrine
I have a table with 2 coloums - id and pets pets column contain abbreviated pet names separated by , [comma] as shown below +----+-------------+ | id | pets | +----+-------------+ | 1 | CAT,DOG | +----+-------------+ | 2 | CAT,DOG,TIG | +----+-------------+ | 3 | ZEB,MOU | +----+-------------+ Now...

Symfony2 creating and persisting entity relationships

php,mysql,symfony2,doctrine2
I have two entities Skin and Email. I want Email to be a part of the Skin entity, however I can't use the console to update schema automatically right now, and that is probably why I can't get the relationship to work. So I want to store all the Emails...

how to access class variables and constants in annotation in symfony 2 php

php,symfony2,doctrine2
I have a class like this: class Student { const GENDER_MALE = "male", GENDER_FEMALE = "female"; /** * @var string $gender * * @ORM\Column(name="gender", type="string", length=50,nullable=false) * @Assert\NotBlank(message="Gender cannot be blank",groups={"new"}) * @Assert\Choice(choices = {"male", "female"}, message = "Choose a valid gender.", groups={"new"}) */ private $gender; I have to hard...

Doctrine2 QueryBuilder: How to filter out entities having zero count for a OneToMany

symfony2,doctrine2,associations,one-to-many,query-builder
In my Dymfony2 / Doctrine2 application, I have a oneToMany relation between an object and its children. I want to select all objects which have no children. I'm stuck with various errors: SingleValuedAssociationField expected, Cannot add Having sth on non result variable, etc. $queryBuilder = $this ->createQueryBuilder('object') ->leftJoin('object.children', 'children') ->andWhere('children...

Symfony 2 - Entity is not updated

symfony2,doctrine2
I am working with form aimed at uploading the file and updating the database in Symfony2. I want to manually set value of book_id field and not to allow user to change it in the form. Thus in my controller before using doctrine to persist document I am calling: $documents->setBookId('1');...

How to fix Symfony2 deployment issues?

php,symfony2,deployment,doctrine2,symfony-2.7
I'm having this issue for a while at differents environments, differents projects and some times I did fixed some others likes now I can't find what is failing so this is my latest try. I want to deploy a app so following rules as docs say the first I did...

Converting query string to an associative array in symfony2

symfony2,doctrine2,symfony-2.7
How to convert query string to an associative array in symfony2? Im new to symfony2. I googled it for couple of hours but there is no straightforward answer (example). Can anyone tell me how to do this?...

Inject a parameter into an entity in symfony2

php,symfony2,doctrine2
I feel silly asking this question but I can't find a clear answer anywhere. I have a token entity which has, among other things, a creation_time. I have a parameter in parameters.yml called token_lifespan. For a token, if creation_time < (time() - token_lifespan) then it has expired. The problem is...

Symfony Array Collection as Entity Property

php,symfony2,doctrine2
Is there a way to associate an ArrayCollection to a database column created by an Entity? For example, I have two entities: Household and Pet Type. Household current has a property for Pet Type, but it expects the Pet Type object, so only one can chosen at the moment. I'd...

The class 'Doctrine\ORM\EntityManager' was not found in the chain configured namespaces XXX

php,doctrine2,zend-framework2,doctrine
I have read the the other questions concerning this issue but have not come across a solution as of yet. I get the following error message: The class 'Doctrine\ORM\EntityManager' was not found in the chain configured >namespaces ZfcUser\Entity, Common\Entity, Employment\Entity, Intern\Entity, >Team\Entity, PurchaseRequest\Entity. I have a HolidayEntity, HolidayController, HolidayService. Adding...

How can i view Result of Database from doctrine in twig

php,symfony2,doctrine2,twig
Edit: change findOneBy to findBy In symfony I am using the FOS-UserBundle. I have three tables. fos_user customer customer_user This is the customerUser.orm.xml <?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity...

doctrine best relation 3 tables to 1 file table - practice / perfromance

php,mysql,symfony2,doctrine2
I am googling for some days and can't decide with will be correct. all of them work but which could be best practice/performance I have some tables: 1. documents 2. envelopes 3. contracts x. Files each 1-3 tables have many Files. 1-3 are NOT related together variants: relation by columns...

How to query in Doctrine2 WHERE = 'value from a related Entity'

php,json,symfony2,orm,doctrine2
The relationship is as easy as Many posts -> one User // Acme\AppBundle\Entity\UploadPlugin\Post /** * @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\AuthBundle\LiveUser") * @ORM\JoinColumn(name="posts", referencedColumnName="id") **/ private $postOwner; So when I create a new Post like this : $image = new Post(); $image->setName($imagetitle); $image->setPostowner($this->getUser()); //(...) set further stuff $em = $this->getDoctrine()->getManager(); $em->persist($image); $em->flush(); I'd just return...

Join between ManyToMany properties at Doctrine2 entities

php,symfony2,doctrine2,dql,symfony-2.6
I have this tables relationship: This is how my entities for messages and emails looks like (I've just added the important info): class Message { /** * @var Brand * * @ORM\ManyToOne(targetEntity="Brand") * @ORM\JoinColumn(name="brands_id", referencedColumnName="id") */ protected $brand; ... } class Email { /** * @ORM\ManyToMany(targetEntity="Message", inversedBy="messageXrefMail", cascade={"persist", "remove"}) *...

How to add an entity-specific listener in Symfony2 that has access to container

php,symfony2,doctrine2
In a Symfony2 application, I have an entity that needs to be populated on pre-persist with various context properties (like user id, what page it was called from, etc.) I figured that to do this, I need to add a doctrine event listener that has access to "service_container", and the...

Symfony2 inherit from a inherited table

symfony2,inheritance,doctrine2
My goal is to inherit an already inherited table with doctrine. I've got an abstract user class... <?php namespace UserBundle\Entity; use Doctrine\ORM\Mapping as ORM; use FOS\UserBundle\Model\User as BaseUser; /** * @ORM\Entity * @ORM\InheritanceType("JOINED") * @ORM\DiscriminatorColumn(name="type", type="string") * @ORM\DiscriminatorMap( {"student" = "Student", "employee" = "Employee", "customer" = "Customer"} ) */ abstract...

Does Doctrine2 apply filters to delete statements

php,symfony2,doctrine2
I use doctrine filters and recently noticed that filters are not applied to delete statements. I have tried to dig through documentation and google, but mystery stays unsolved. For example I have filter which connects user to company so every select query like: $userRepo->find(12); and is modified from SELECT .......

Some logic in Doctrine2 Entity

php,doctrine2
in my User entity I have some field, that is responsible for the likes of some user for some post: /** * @var ArrayCollection * * @ORM\ManyToMany(targetEntity="Post") * @ORM\JoinTable(name="posts_likes", * joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")}, * inverseJoinColumns={@ORM\JoinColumn(name="post_id", referencedColumnName="id", onDelete="CASCADE")} * ) **/ protected $postsLikes; The question is: is it normal to have...

Doctrine building querybuilder

php,symfony2,doctrine2
I'm trying to make topic / comment system with symfony and I have some question about doctrine's querybuilder. if I have two entities connected: /** * @ORM\ManyToOne(targetEntity="Topicit", inversedBy="comments") * @ORM\JoinColumn(name="topic_id", referencedColumnName="id") */ protected $topicit; and /** * @ORM\OneToMany(targetEntity="Comment", mappedBy="topicit") */ protected $comments; Currently I have builder (getting every column): $repository...

Multiple level of different kind of inheritance

php,doctrine2,multiple-inheritance,single-table-inheritance
For my project, I'm trying to use the inheritance feature of Doctrine. I need to represent medias (through different tables : one table for uploaded documents, one for linked videos, ... and so on). But, the videos can vary from provider to provider (such as Youtube, Dailymotion, you name it)....

Doctrine fixtures won't get loaded in given order, instead, they get loaded in alphabetical order

symfony2,doctrine2
As far as I know, fixtures will be loaded in given order, based on the value returned in getOrder() method of each fixture files. Sharing Objects between Fixtures. For some reason, doctrine tries to load fixtures below in alphabetical order (class name) instead. In example below, it has to load...

Entity MetaData for Doctrine and multiple Entity Managers

symfony2,doctrine2
I'm trying to setup an Sql Server connection for Doctrine in Symfony2.However I can not figure out how to setup some Entity Foo to be managed by the new Entity Manager. I have seen this post in regards to managing Entities with multiple Entity Managers, however I don't know how...

Is it a bad practice to move all Doctrine2 Entities into one single Bundle?

symfony2,doctrine2
Here is my issue; Lets say you create a relationship from one bundle to another (In this case, one user => many notifications) (UserBundle => NotificationsBundle) /** * @ORM\OneToMany(targetEntity="Gabriel\NotificationsBundle\Entity\Notification", mappedBy="notificationOwner") */ private $notifications; The Problem: When the Notificationsbundle gets removed from the AppKernel, the class above gets lost, and the...

Persisting other entities inside preUpdate of Doctrine Entity Listener

symfony2,doctrine2
For clarity I continue here the discussion started here. Inside a Doctrine Entity Listener, in the preUpdate method (where I have access to both the old and new value of any field of the entity) I'm trying to persist an entity unrelated to the focal one. Basically I have entity...

Doctrine2: Adding existing entity to parent, duplicates the parent

php,doctrine2,cascade
I have two related classes (OneToMany): <?php class Container { /** * @var Content[] * @\Doctrine\ORM\Mapping\OneToMany(targetEntity="Content", mappedBy="contents", cascade={"remove"}) */ protected $contents; } class Content { /** * @var Container * @\Doctrine\ORM\Mapping\ManyToOne(targetEntity="Container", inversedBy="contents", cascade={"persist"}) */ public $container; } Now when I add a new Content item the Container will be duplicated...

Doctrine include null on join

sql,symfony2,orm,doctrine2
I am trying to create a query that will fetch every users, and, for those that have received a feedback, fetch their rating average as well. After some research, I have crafted a query that will return all the users that have received a feedback and their respective rating. Which...

how to manually set/persist a primary key in ORM Doctrine2

symfony2,orm,doctrine2
In my table primary key is ISBN so I need to set it manually when adding new Book in form. When adding new Book with ISBN 123, it result in blank ISBN in database. Entity: /** * @var string * * @ORM\Column(name="isbn", type="string", length=45) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private...

Symfony2 entity foreign keys

symfony2,doctrine2,foreign-keys,entity
I can't figure it out.. Why I haven't access to Country table? countryName should show Great Britain but it doesn't. This is my dump($User): My my piece of code of User entity: /** * * @ORM\ManyToOne(targetEntity="Dashboard\MainBundle\Entity\Country", cascade={"persist"}) * @ORM\JoinColumn(name="country_id", referencedColumnName="id", nullable=true) * */ private $countryId; And my piece of code...

Symfony one-to-one, unidirectional relation

symfony2,doctrine2
I have two entities. User and Contact. User and contact have the same property phone_number. I would like to get all contacts with user object if its exists. It is also possible that the same phone number exists in contact table but it doesn't exist in user table. Below is...

Subqueries in Doctrine Query Language

mysql,doctrine2
I have an SQL query that I was trying to translate into DQL. Seems like DQL does not like to use subquery in a FROM clause. Can you please guide me in the riqht direction? SQL: select count(x.remote_addr), ipc.country from ( select distinct(remote_addr) from update_feature_requests ufr where ufr.request_datetime BETWEEN '2015-05-14'...

Symfony Doctrine findBy and then map

php,symfony2,doctrine2,doctrine
Basically I want to execute this mysql query with doctrine: select distinct user_id from work_hour where project_id = ?; But I don't know how I can do this with pretty Doctrine code. Is it possible to make it look like the following pseudo code or do I have to use...

create properly a ManyToMany Recursive / Reflexive relation with doctrine ORM (Symfony)

php,database,symfony2,doctrine2,recursive-datastructures
I have this entity named Pointscomptage.php: class Pointscomptage { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="invariant", type="string", length=150, nullable=false) */ private $invariant; /** * @var string * * @ORM\Column(name="nom", type="string", length=150, nullable=false) */ private...

Symfony2 Functional Testing: Is a database required or not?

php,unit-testing,symfony2,doctrine2,functional-testing
I have to write functional tests for a controller that registers a user in the application. The controller has two methods (and routes): registrationAction (route=registration) endAction (route=registration/end) Now I would like to write functional tests for those two methods. My question is: as the controller creates and persists a new...

Symfony, security.yml “Unknown Entity namespace alias”

php,symfony2,doctrine2,doctrine
I would like to implement Symfony security into my project. Problem is I have to use two databases (one for admins, second for users). I have configured config.yml : orm: auto_generate_proxy_classes: %kernel.debug% default_entity_manager: default entity_managers: default: connection: system mappings: FinanceCmsBundle: ~ admin: connection: admin mappings: FinanceCzBundle: ~ and set my...

Symfony2 - Share Entity Between Bundles with different relationships

symfony2,doctrine2
How do you share an entity between multiple bundles with different relationships? For example both the ZooAnimalBundle and FarmAnimalBundle need a User Entity. A third Bundle AccountUserBundle has the User Entity. In both the Zoo and Farm AnimalBundles I create a User Entity like so: use Account\UserBundle\Entity\User as BaseUser; class...

what is wrong in this statement php doctrine

php,doctrine2,doctrine,php-5.3
I'm trying make a validation in my db using doctrine where I just need to make this statement in SQL like, Select * from usuarios where usuario_email = someEmail After I click the submit button from my form, I instantiate the class UsuarioDao, from a script that includes bootstrap.php (from...

Doctrine One to Many relationship

php,symfony2,doctrine2,doctrine,one-to-many
I got confuse in doctrine one to many relationship. Question 1: Correct me if I am wrong. I assume that when I try to $em = $this->getDoctrine()->getManager(); $product_repo = $em->getRepository('MyBundle:Product'); $products = $product_repo->findAll(); dump($products); I will see the related features attached to the $features variable, so when I use $products->getFeatures()...

zf2 + doctrine2 and No Metadata Classes to process

php,doctrine2,zend-framework2,metadata
I'm using tutorial http://www.nuvolia.com/2013/03/09/zend_framework_doctrine_install/. The module Application fork fine with Doctrine ORM but when i'm tring to connect in another module i'm reciving error: d:\Aptana Studio\Projects\app01>vendor\bin\doctrine-module orm:schema-tool:create Deprecated: "Symfony\Component\Console\Helper\DialogHelper" is deprecated since version 2.5 and will be removed in 3.0. Use "Symfony\Component\Console\Helper\Qu estionHelper" instead. in D:\Aptana Studio\Projects\app01\vendor\symfony\console...

Improve memory usage when importing data

symfony2,doctrine2
I'm actually searching for an advice, not a solution. I made a service that compare data from a distant database and insert, update, or remove local data if necessary. There are more than 50k entries in the source database, and local memory usage slow the script make it veeeery long....

Project Architecture

symfony2,doctrine2,sonata-admin
I was wondering if I did a good choice concerning my project conception. I am not an expert and it's the reason why I want to know the different views of the other developers. My project is separate in two Bundles : FrontOfficeBundle BackOfficeBundle I want to access my different...

How to order results using EntityManager from Controller in Symfony2

php,symfony2,doctrine2
I have this code: public function indexAction() { $em = $this->getDoctrine()->getManager(); $user = $this->getUser(); $entities = $em ->getRepository('BreedrGeckoBundle:Weight') ->findBy(array('user' => $user), array()); return array( 'entities' => $entities, ); } Which is fine, gets all the weights in the database for the current user. But how can I order the results...

With a OneToMany relation between entities, how create the right queryBuilder with Doctrine (on the Inversed Side entity)

php,symfony2,doctrine2,one-to-many,query-builder
I have these 3 entities in my symfony2.6 project: Compteurs.php class Compteurs { /** * @var \PointsComptage * * @ORM\ManyToOne(targetEntity="PointsComptage", inversedBy="compteurs") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="pointscomptage_id", referencedColumnName="id") * }) */ private $pointsComptage; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\OneToMany(targetEntity="ParametresMesure", mappedBy="compteurs") */ private $parametresMesure; ParametresMesure.php: class ParametresMesure { /** * @var Compteurs...

[Symfony 2]Use Doctrine into a service

xml,symfony2,doctrine2,doctrine
I've created a new service in my project. This service is configured in XML. I'd like to user the EntityManager, to retreive som data in the service but I'm not able to «connect» Doctrine to my service. Currently, I have this code: services.xml <service id="SiteService.search" class="Site\ProductBundle\Search\SphinxSearch" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"> <argument>Site\ProductBundle\Entity\Product</argument> </service>...

Getting Objects from database in Symfony2

php,database,symfony2,doctrine2,symfony-2.7
I had read somewhere some day that symfony2/Doctrine2 has a method(i don't remember the method name now) that fetches all "like" objects that we specify.. For example, I have User entity that has userName , password, name, state and city as properties.. For getting all Users who has name =...

Downgrade Doctrine ORm 2.5 to 2.4

php,doctrine2,composer-php
i want Downgrade Doctrine Orm 2.5 to 2.4 For solve this Error : syntax error, unexpected '[', expecting ')' Note : My php Version : 5.3 (Doctrine 2.5 needed to php 5.4 and later version) And write this Code in Composer.json file : { "require": { "doctrine/common": "2.4.*", "doctrine/dbal": "2.4.*",...

Doctrine - How to create inverse relation?

php,symfony2,doctrine2,dql
In symfony I created two entities from a database already created. I used the following commands from the console of symfony: php app/console doctrine:mapping:import --force IDFrontendBundle xml php app/console doctrine:mapping:convert annotation ./src php app/console doctrine:generate:entities IDFrontendBundle Two of the entities that generate me and where I have the problem are...

ZF2 / Doctrine / Cannot remove all elements from an ArrayCollection

php,doctrine2,zend-framework2
I have 2 entities, Product and Category with a bidirectional ManyToMany association mapping defined below : Product /** * @ORM\ManyToMany(targetEntity="Category", inversedBy="products") * @ORM\JoinTable(name="products_categories") */ protected $categories; // with these accessors public function addCategories(Collection $categories) { foreach ($categories as $category) { $this->addCategory($category); } return $this; } public function addCategory(Category $category) {...

Doctrine migrations:diff ignores cascade

mysql,symfony2,doctrine2
I have ManyToOne relation between two entities and would like to use DB (MySQL) level cascade on delete. When I use doctrine:migrations:diff foreign key is created without ON DELETE CASCADE. So I added this cascade myself but on next migrations:diff this statement has been removed. Is there any way how...

Doctrine get entity with item

php,symfony2,doctrine2
I want to get the field of an entity that is associated with another . My entity Offers has a last_offer field. Offers is related to the Products entity. Then , with a consultation in my entity Products, I want to get the latest offer associated with the entity Offer....

Catchable Fatal Error - __construct() must be an instance of Symfony\Component\Security\Core\SecurityContext, none given

symfony2,doctrine2,symfony-forms
I want to pass the current user into AbstractType. I followed the help from this page here: Access currently logged in user in EntityRepository Unfortunately - It is not working by me. I'm using Symfony 2.6. Catchable Fatal Error: Argument 1 passed to Checkout\Bundle\ItemBundle\Form\ItemType::__construct() must be an instance of Symfony\Component\Security\Core\SecurityContext,...

DOCTRINE 2 Use two entities for one object

symfony2,doctrine2,sonata-admin
I am trying to update my database with this cli : php app/console doctrine:schema:update But I have a conflict "The table with name '...' already exists" because i Have two entities (one for the front and one for the back) and the both are linked to one table. I would...

How to select all rows that don't have one-to-many entity with certain value using Doctrine

php,mysql,orm,doctrine2,doctrine
I have two entities: Cage and Bird. Cage has Birds inside so their relationship is one-to-many. Bird has a field name. How can I select all Cages where there's no Bird with name eagle inside. I was trying to do this: $cages = $this->createQueryBuilder("c") ->leftJoin("c.birds", "b") ->where("b.name != :name") ->setParameter("name",...

Why tree is invalid?

symfony2,doctrine2,tree,doctrine-extensions,stofdoctrineextensions
I have a entity that use doctrine extension, tree behaviuor, i found problems in tree and don't know it's reason. my entity: MyEntity: type: entity gedmo: tree: type: nested id: id: type: integer generator: strategy: AUTO fields: # ... lft: type: integer gedmo: - treeLeft rgt: type: integer gedmo: -...

Best practice for Zend 2 FieldSets, re-use them or re-create them for every specific situation?

php,forms,doctrine2,zend-framework2
Me and my colleague were arguing about whether or not we should re-use certain Zend2 FieldSet classes in our project. Using the framework we create many different forms, and there are quite a few forms for which the same information needs to be filled in. For example, we have a...

Symfony2 / Doctrine2 : how to access an entity annotation mapping?

symfony2,doctrine2,annotations,mapping,accessor
In my Symfony2/doctrine2 application, I have two entities, Media and Recipe. They can be linked by a oneToMany or a ManyToMany association. In the case of a oneToMany relationship, I am using the following code to retrieve the Recipe linked to an instance of Media : $accessor = PropertyAccess::createPropertyAccessor(); $reflect...

Symfony2 Doctrine: ContextErrorException: Catchable Fatal Error: Object of class DateTime could not be converted to string

php,symfony2,doctrine2
In my Symfony2 project I have the following query in my ProductRepository.php: $dateNow = new \DateTime(); $query = $this->createQueryBuilder('p') ->update('MyBundle\Products', 'p') ->set('p.published', $dateNow) ->getQuery(); $query->execute(); ProductEntity.php: /** * Set published * * @param \DateTime $published * @return Product */ public function setPublished($published) { $this->published = $published; return $this; } ERROR:...

Doctrine2: Building object from array

php,doctrine2
Is it possible with Doctrine2 to use a method which creates an entity out of an array? I mean somehow Doctrine2 converts the database return values to objects. Including children. If it is possible a link and en example would be very helpful. Thanks. ...

How to get all users who are not member of a particular group in Symfony?

php,symfony2,doctrine2
How to get all users who are not member of a particular group in Symfony? Users and Groups have a Many To Many relationship. I would like to get all users who are not member of the Group with group_id 8, what is an appropriate Entity Query for this in...

Symfony Form - Expected argument of type “string or Symfony\Component\Form\FormTypeInterface”, “array” given

php,arrays,forms,symfony2,doctrine2
I have created a form with doctrine. It works if I do not pass any option, like this: $builder ->add('name') ->add('password', 'password') ->add('password_repeat', 'password') ->add('email', 'email') ->add('save', 'submit') ; But, if I add an array with options as it says the docs (http://symfony.com/doc/current/book/forms.html#book-form-creating-form-classes), I get an error that says: Expected...

Sorting a collection in doctrine2

php,mongodb,doctrine2,doctrine,odm
I've written the following query (that may or may not be efficient, I'm still a newbie): $collection = $this->dm->getConnection()->selectCollection('db_name', 'collection_name'); $query = array('array_name' => new \MongoId(id)); $cursor = $collection->find($query)->limit(9)->sort('r', 'desc'); I'm trying to sort by an r value that looks like this in the document: "r": 0.58325652219355106354 but it isn't...