Sorry about the title, it's quite hard to describe it with just a few words. Here's the problem:
I have a customer entity which has a OneToMany with Website and customerTrackingIds :
class Customer {
...
/**
* #var ArrayCollection
* #Serializer\Exclude()
* #ORM\OneToMany(targetEntity="AppBundle\Entity\WebSite", mappedBy="customer",cascade={"persist","remove"},orphanRemoval=true)
*/
private $webSites;
/**
* #var ArrayCollection
* #Serializer\Exclude()
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CustomerTrackingId", mappedBy="customer",cascade={"persist","remove"})
*/
private $customerTrackingIds;
...
}
And Website:
class WebSite {
/**
* #var Customer
* #Serializer\MaxDepth(1)
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Customer", inversedBy="webSites")
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $customer;
/**
* #var ArrayCollection
* #Serializer\Exclude()
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CustomerTrackingId", mappedBy="website")
*/
private $customerTrackingIds;
}
Customer has multiple website and multiple trackingIds. Each tracking ID is associated with one of the customer's website, but more trackingIds can exist for the same Website.
I use https://github.com/ninsuo/symfony-collection to handle the collection of website/trackingIds in the same page but when i go edit the information something really weird (at least for me) happens.
Looking in my debugger session i saw that when the form loads data from submit in my controller:
$formCustomer = $this->createForm( CustomerFormType::class, $customer );
$formCustomer->handleRequest( $request );
if ( $formCustomer->isSubmitted() && $formCustomer->isValid() ) {
$em = $this->getDoctrine()->getManager();
$em->persist( $customer );
$em->flush();
When the request is handled all of the elements of TrackingIds has their website correctly set, but inside the website the customer link gets lost (becomes null).
What happens next is that when all the data get persisted i lost in my database the phisical association between website <-> customer (customer becomes null)
How can i fix this?
If you will ever land here i solved the issue simply double-checking my website collection form type.
Since using https://github.com/ninsuo/symfony-collection i created a new FormTheme to render the collection add/delete stuff in my page with just one field for the website collection which was the website name.
Anyways, inside my website collection formType i had TWO fields, name AND, guess what, CUSTOMER.
Since the FormTheme was rendering just the name field, the other one becomes null automatically, so when it was handled by the controller he was actually doing that right.
Related
I come from a Rails background and am not really familiar with Doctrine. I am trying to set up a similar association to this one in Rails.
I have a UserRelation entity that contains a combination of user_id and company_id with a primary key. The same user can belong to multiple companies, and most data is stored with user_relation_id.
So, in this example I have a Template that has the following association set up which works fine:
/**
* The UserRelation entity who created the template.
*
* #ORM\ManyToOne(targetEntity="UserRelation")
* #ORM\JoinColumn(name="user_relation_id", referencedColumnName="id", nullable=false)
*/
protected $creator;
In this example I know I can just add a method to my template entity along the lines of:
public function getUser(): User
{
return $this->creator->getUser();
}
but I need it to be filterable so that I can get all Template entities by user_id or company_id in a repository or controller like this:
$company = $entityManager->getRepository('Company')->find($company_id);
$templatesForCompany = $entityManager->getRepository('Template')->findBy('company' => $company);
Is there any way to set up this relationship so I can query it like above, instead of having to resort to raw SQL?
I trying Symfony 4 for "fun". And for that I try to rewrite an old website without framework as the moment, with Symfony 4.
For that I configure my app on my database with existing datas. And I'd make login form.
BUT on my User classe, I have some colomn who make me some issues.
See bellow my user's class's annotations:
/**
* Utilisateur
*
* #ORM\Table(name="utilisateur", uniqueConstraints={#ORM\UniqueConstraint(name="mail", columns={"mail"})}, indexes={#ORM\Index(name="FK_UTILISATEUR_idDroit", columns={"idDroit"})})
* #ORM\Entity
*/
and my user's struct :
idutilisateur
nom
prenom
mail
password
dateinscription
datevalidation
token
iddroit
plainPassword
Like you can see, I create before iddroit as foreign key of droit's table.
Doctrine generated the propertie as
/**
* #var Droit
*
* #ORM\ManyToOne(targetEntity="Droit")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idDroit", referencedColumnName="idDroit")
* })
*/
private $iddroit;
And created the getter as
public function getIddroit(): Droit
{
return $this->iddroit;
}
And after followed the documentation about registration / login, the debugger respond =>
Return value of App\Entity\Utilisateur::getIddroit() must be an
instance of App\Entity\Droit, null returned
So I imagine he want an object and not just an ID, even if in anotation it's making the Join rules. Any ID what's happened ?
And I understand to return an objet, but I have no idea how to return that.
If any suggestion.
Thanks guys ;)
Laurent
I have 2 tables like this:
Users
- UserID
- Username
- Password
- ...
Players
- playerID
- playerName
- ...
- User
The relation is ManyToOne (see the picture) and it's not required.
I've generated my entities automatically with Doctrine. In my player Entity I have:
/**
* #var \NV\VolleyScoutBundle\Entity\Users
*
* #ORM\ManyToOne(targetEntity="NV\VolleyScoutBundle\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
protected $user;
But I don't have a $player variable in my Users Entity. In what way can I add this? Tried to do this but gave me different errors. What I'm trying to do is add a player form to my register form.
So in my RegisterType (=form) I woud like to add ->add('player', new PlayerType()). But that's not possible without a $player variable in my Users entity.
What type of relation do I need to setting for $player in my Users entity?
You have to add annotation in user entity.
In Player Enity
#ORM\OneToMany(targetEntity="Players", mappedBy="user")
protected $player;
In User Entity:
#ORM\ManyToOne(targetEntity="Users", inversedBy="player")
#ORM\JoinColumn(name="user_id", referendecColumn="UserId")
proteced $user;
This is only a draft. You have to write full namespaces for target entities, and correct errors if there are some.
A lot of setails you can find here: Doctrine documentation - working with association
Try to use small caps for table names, because MySQL under linux doesn't like uppercaps.
$player must be instance of ArrayCollection
I'm trying to create a simple form to add companies and i've a trouble using an entity.
I added a select field using a company type entity :
->add('idtypesociete', 'entity', array('class' => 'PromocastUtilisateurBundle:PcastTypesociete', 'property' => 'nomtypesociete'))
But when i submit the form my idtypesociete field contain an 'PcastTypesociete' object and not just the value of the option selected. So the submission fail.
I made a Many-To-One relation between my company entity and my typeCompany entity like this:
/**
* #var integer $idtypesociete
*
* #ORM\Column(name="IDTYPESOCIETE", type="integer", nullable=false)
* #ORM\ManyToOne(targetEntity="Promocast\UtilisateurBundle\Entity\PcastTypesociete")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="PcastTypesociete_idtypesociete", referencedColumnName="idtypesociete")
* })
*/
private $idtypesociete;
Do you have a solution to get only the id of the company type selected? (if possible without made a simple sql request to list my companies types)
Thanks a lot !
If the relationships are working then Symfony 2 usually does a very good job of building the form fields for you.
I think the issue is the $idtypesociete property. Are you expecting to store an integer here on the hydrated entity?
Doctrine associations use Entity relationships. The annotations you supply determine the behind-the-scenes stuff like the join column:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#many-to-one-unidirectional
I suggest backing up or committing your work before doing anything else.
Does changing the entity property to the following help?
/**
* #var PcastTypesociete $typesociete
*
* #ORM\Column(name="IDTYPESOCIETE", type="integer", nullable=false)
* #ORM\ManyToOne(targetEntity="Promocast\UtilisateurBundle\Entity\PcastTypesociete")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="PcastTypesociete_idtypesociete", referencedColumnName="idtypesociete")
* })
*/
private $typesociete;
You may need to update your database schema via doctrine:schema:update using the console if it doesn't work properly the first time. Your Entity will also need to be updated to reflect the new property name.
If that works then your form should only need ->add('typesociete') in the form type and you'll have a functioning entity select field because Symfony is clever enough to know what field type to use.
Doctrine NOOB here, trying to figure out how to prevent a duplicate record in an embed many property. I have a EmbededDocment like this:
<?
/**
* #EmbeddedDocument
*/
class Contact {
/**
* #Id
*/
private $id;
/**
* created timestamp
* #Date
*/
private $created;
/**
* modified timestamp
* #Date
*/
private $modified;
/**
* #String
*/
private $name;
/**
* #String
*/
private $name;
/**
* #String
*/
private $address;
}
what I want to happen is when I add a new contact, two contacts can have the same name, two contacts can have the same address, but two contacts can not have the same name and address. When checking for duplicates, doctrine will need to ignore the $id, $created and $modified properties as these will almost always be distinct. It is the combination of all the other fields that must be unique. How can this be accomplished using doctrine? Does this logic belong in a service layer or can doctrine do it for me?
UPDATE:
I do accept that Andrew's answer is the correct way to check for duplication using Mongo, I really want to know if doctrine can do this for me. Therefore, I'm starting a bounty.
You could implement an event listener which will listen to an preUpdate and prePersist event.
http://www.doctrine-project.org/docs/mongodb_odm/1.0/en/reference/events.html
In your event, you can do your own check.
You should validate your document before save it.
For example if user adding Contact with name="Name" and address="Address" you shoud check in mongodb if such Contact exists. And in case if it exists you just showing validation message, otherwise you adding contact to embedded contacts array.
So, suppose you have collection of users that's contains embedded array of contacts. To verify that new contact exists/not exists you can send request like this:
db.users.find({ userId: "userId" ,
contacts.name: "new contact name",
contacts.address: "new contact address"}).count();
If above query will return count >= 1 you no need add new contact, just show validation.