Symfony 2 JMS Serializer Bundle - Serialize only IDs for User friends - symfony

I have a question about the JMS Serializer Bundle in Symfony 2.
I want to serialize a User entity, which has a many-to-many relation with itself called "friends".
While I want to expose a bunch of property from the original User, I only want the ids from the friend objects, which are also User entities.
How can I solve this problem?
Thanks in advance.

Okay, while I wrote the question, I also solved it.
The solution is to use the #VirtualProperty annotation.
Example:
use JMS\Serializer\Annotation\VirtualProperty;
use JMS\Serializer\Annotation\SerializedName;
// ...
/**
* #VirtualProperty
* #SerializedName("friends")
*/
public function getFriendIdsOnly()
{
$friendIds = array();
foreach ($this->friends as $friendEntity) {
$friendIds[] = $friendEntity->getId();
}
return $friendIds;
}
With this, the "friends" key will contain an array of User ids.

Or maybe you could use the #Groups annotation.
class User
{
/*
* #JMS\Groups({"user_id", "friend_id"})
*/
$id;
/*
* #JMS\Groups({"user_friends"})
*/
$friends;
}
And when you want to serialize you set up the ["user_friends", "friend_id"] groups. The difference with your solution is the format of the return (if we talk about json)
// You
{"id":, "friends":["id", "id"]}
// Me
{"id":, "friends":[{"id":}, {"id":}]}
The solution with the groups allow a more manageable return. If one day you want to send back the username for instance, you just need to change the groups annotations.

Related

Symfony 3 - Update Many-To-Many

I have been looking around for a clean solution on how to update (keep in sync) a many to many relationship?
I have the following scenario:
A Sprint Entity owns the Many To Many relationship towards the Ticket entity.
When editing a Ticket (or Sprint, but I am not there yet), I want to be able to select (checkboxes) the Sprints that this ticket belongs to.
Upon persistance (save), I want to update my join table tickets_sprint (which is just a join table on ticket_id, sprint_id).
Adding Sprints to the Ticket seems easy enough, but removing Sprints from the Ticket is not reflected at all.
Code
Ticket Entity contains this method for adding a Ticket to a Sprint:
public function setSprints($sprints) {
/**
* #var $sprint \AppBundle\Entity\Sprint
*/
foreach ($sprints as $sprint) {
$this->sprints[] = $sprint;
$sprint->addTicket($this);
}
}
I have read here that the only way to go would be to remove all relations and re-save them upon persistance.
Coming from the Laravel world, this hardly feels like a good idea :)
This is how it is done in Laravel:
/**
* #param \App\User $user
* #param \App\Http\Requests\StoreUserRequest $request
* #return \Illuminate\Http\RedirectResponse
* Update the specified resource in storage.
*/
public function update(User $user, StoreUserRequest $request)
{
$user->fill($request->input());
$user->employee_code = strtolower($user->employee_code);
$user->roles()->sync($request->role ? : []);
$user->save();
\Session::flash('flash_message_success', 'The user was successfully updated.');
return redirect()->route('frontend::users.show', [$user]);
}
All suggestions are welcome!
The EntityType that you may use to create a multiple selectbox doesn't have a by_reference option like CollectionType.
If your Ticket Entity use the "inversedBy" side, you don't need to add the reference in the other object. So you can symply do this :
public function setSprints($sprints) {
$this->sprints = $sprints;
}
Maybe this will be enough to add and remove your elements automatically (Sorry didn't try).
Otherwise you have to do it manually and you can create a new method to remove elements returns by the difference between your new ArrayCollection and the old one.

One-to-many relationship: how to set default entity-value?

I have a one-to-many relationship Cart-SendingMethod. I would like to set a default SendingMethod for new Carts. So I have tried this:
<?php
/**
* #ORM\ManyToOne(targetEntity="MetodoEnvio", inversedBy="metodoEnvios")
* #ORM\JoinColumn(name="metodo_envio_id", referencedColumnName="id")
**/
private $metodoEnvio = 1;
but doesn't work... I get:
Impossible to access an attribute ("id") on a integer variable ("1") when I call Cart.SendingMethod.id from a view file
So how to set a default SendingMethod for new Products?
I could do it in the controller, but I would like to know if it is possible from the entity Product.
Note: I didn't know exactly if this is a symfony or doctrine question.
You don't want to introduce dependencies into your entity.
The obvious and cleaner way to do it would be to create a CartFactory service, and inject that into any controller (or other class) that needs to create carts. Inject your EntityManager and other dependencies into the factory. That way you DRY up your cart-initialization code, and avoid bulking up your controller.
Just set the property's default value inside the constructor like this:
public function __construct(..)
{
$this->property = new OtherObject();
}

Symfony2 remove and save many to many relations

I need your help today. I'm working on a small application using Symfony 2.1 but I have a base problem, I have to tables with a many to many relation which creates a third table:
class Usuario implements UserInterface {
/**
* #ORM\ManyToMany(targetEntity="Alood\BackBundle\Entity\Alergeno", inversedBy="usuarios")
* #ORM\JoinTable(name="UsuariosProductos",
* joinColumns={#ORM\JoinColumn(name="usuario_user", referencedColumnName="user")},
* inverseJoinColumns={#ORM\JoinColumn(name="alergeno_id", referencedColumnName="id")}
* )
**/
protected $alergenos;
}
public function __construct(){
$this->alergenos = new ArrayCollection();
}
public function getAlergenos() { return $this->alergenos; }
and:
/**
* #ORM\ManyToMany(targetEntity="Alood\BackBundle\Entity\Usuario", mappedBy="alergenos")
**/
protected $usuarios;
Then I need to remove the non selected Alergenos, this is my controller:
$alergenosUser = $em->getRepository("BackBundle:Usuario")->find($usuario);
$resultSym = array_diff($alergenosUsuarioIds, $alergen);
foreach($resultSym as $result) {
$alergenosUser->getAlergenos()->remove($result);
}
$em->persist($alergenosUser);
$em->flush();
Could you please help me to figure out what I'm doing wrong? Thanks you so much!
In order to remove an item from a collection use the following:
$collection->removeElement($item);
The remove($key) function will remove by key while removeElement($item) removes the item from the collection if found. Have a look at the ArrayCollection code here.
Be aware that doctrine will only check the owning side of a relation for changes.
It is not clear what the $alergenosUsuarioIds and $alergen variables represent but you might be mistaken about the usage of the remove() method of ArrayCollection.
You need to give it an index, not the id of the entity you want to remove. You can also use the removeElement() method and pass it the entity.
For instance you can do something like this :
$elements = $alergenosUser->getAlergenos();
foreach ($elements as $element) {
if ($element->getId() == $id_from_array_diff_or_whatever) {
$elements->removeElement($element);
}
}
or
$elements = $alergenosUser->getAlergenos();
foreach ($elements as $key => $element) {
if ($element->getId() == $id_from_array_diff_or_whatever) {
$elements->remove($key);
// or
unset($elements[$key]);
}
}
You can also use the matching() but I'm not sure it's available with the version shipped with symfony2 2.1.
So your problem can be solved doing the relation yourself.
ManyToMany doesn't really exist because as you say a third table is created. You want to delete elements only in this third table.
So you have to build the relation yourself to delete directly an element in the third table.
So first create the third entity.
Do two relation ManyToOne from the third entity to the two others entities.
Then you just have to simply remove an element of the third entity you just created.

Symfony2: Error persisting ManyToMany/OneToMany Relationships

I don't know why, maybe i am missing some basic logic but I always run again into the same issue. I can't persists ManyToMany collections, and it also faces me with OneToMany collections, though I can work around that.
I read through the doctrine documentation, and I think I do understand the thing with mappedBy and inversedBy (where the last one is always the owner and therefor responsible for persisting the data, please correct me if I am wrong).
So here's a basic example that I have right now, which I can't figure out.
I have an Entity called Site:
#Site.php
...
/**
* #ORM\ManyToMany(targetEntity="Category", mappedBy="sites")
*/
protected $categories;
and another one called Category:
#Category.php
...
/**
* #ORM\ManyToMany(targetEntity="Site", inversedBy="categories")
* #ORM\JoinTable(name="sites_categories")
*/
protected $sites;
Using the Symfony2 entity genenerator it added me some getters and setters to my Entites which look like this.
Site:
#Site.php
...
/**
* Add categories
*
* #param My\MyBundle\Entity\Category $categories
*/
public function addCategory(\My\MyBundle\Entity\Category $categories)
{
$this->categories[] = $categories;
}
/**
* Get categories
*
* #return Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
The same counts for
Category:
#Category.php
...
/**
* Add sites
*
* #param My\MyBundle\Entity\Site $sites
*/
public function addSite(\My\MyBundle\Entity\Site $sites)
{
$this->sites[] = $sites;
}
/**
* Get sites
*
* #return Doctrine\Common\Collections\Collection
*/
public function getSites()
{
return $this->sites;
}
Fair enough.
Now in my controller, I am trying to persist a Site object:
public function newsiteAction() {
$site = new Site();
$form = $this->createFormBuilder($site); // generated with the FormBuilder, so the form includes Category Entity
// ... some more logic, like if(POST), bindRequest() etc.
if ($form->isValid()) {
$em = $this->getDoctrine()
->getEntityManager();
$em->persist($site);
$em->flush();
}
}
The result is always the same. It persists the Site Object, but not the Category entity. And I also know why (I think): Because the Category entity is the owning side.
But, do I always have to do something like this for persisting it? (which is actually my workaround for some OneToMany collections)
$categories = $form->get('categories')->getData();
foreach($categories as $category) {
// persist etc.
}
But I am running into many issues here, like I would have to do the same loop as above for deleting, editing etc.
Any hints? I will really give a cyber hug to the person who can clear my mind about that. Thanks!
.
.
.
UPDATE
I ended up changing around the relationship (owning and inverse side) between the ManyToMany mapping.
If somebody else runs into that problem, you need to be clear about the concept of bidrectional relationships, which took me a while to understand too (and I hope I got it now, see this link).
Basically what anserwed my question is: The object you want to persist must always be the owning site (The owning site is always the entity that has "inversed by" in the annotiation).
Also there is a concept of cascade annotation (see this link, thanks to moonwave99)
So thanks, and I hope that helps somebody for future reference! :)
Regarding OneToMany relationship, you want to know about cascade annotation - from Doctrine docs [8.6]:
The following cascade options exist:
persist : Cascades persist operations to the associated entities.
remove : Cascades remove operations to the associated entities.
merge : Cascades merge operations to the associated entities.
detach : Cascades detach operations to the associated entities.
all : Cascades persist, remove, merge and detach operations to associated entities.
following docs example:
<?php
class User
{
//...
/**
* Bidirectional - One-To-Many (INVERSE SIDE)
*
* #OneToMany(targetEntity="Comment", mappedBy="author", cascade={"persist", "remove"})
*/
private $commentsAuthored;
//...
}
When you add comments to the author, they get persisted as you save them - when you delete the author, comments say farewell too.
I had same issues when setting up a REST service lately, and cascade annotation got me rid of all the workarounds you mentioned before [which I used at the very beginning] - hope this was helpful.

Symfony/Doctrine 2 - Use config parameter in Entity

I have a tree of Employee objects (they are in a tree-like hierarchy, with everyone having one leader, and all leaders having more employees). All the Employees have a integer parameter called units.
/**
* #ORM\Entity
* #ORM\Table(name="employees")
*/
class Employee
{
/**
* #ORM\Id
* #ORM\Column(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToMany(targetEntity="Employee", mappedBy="leader")
*/
protected $employees;
/**
* #ORM\ManyToOne(targetEntity("Employee", inversedBy="employees")
*/
protected $leader;
}
I need to get all the employees, who have at most N units, where N is defined in config.yml. At first, I was trying to push $configContainer into $GLOBALS, and use it in ArrayCollection::filter()'s Closure. Now I found a method, so I can use variables in the Closure:
public function getBestEmployees(&$configContainer)
{
return $this->getAllEmployees()->filter(
function bestEmployees($employee) use ($configContainer)
{
return ($employee->getUnits() >= $configContainer->getParameter('best_unit_count'));
}
);
}
Now I wonder if there is any other way to access the configuration parameters from an Entity, or do I really have to pass the whole configContainer as a reference? Or am I doing it totally wrong?
You shouldn't be accessing the service container at all inside entities. The value itself should be passed instead
public function getBestEmployees($bestUnitCount)
{
return $this->getAllEmployees()->filter(function ($employee) use ($bestUnitCount) {
return $employee->getUnits()->count() >= $bestUnitCount;
});
}
Of course, we haven't actually solved the problem yet: the parameter still needs to be fetched from the container somewhere. If this method gets invoked mostly in controller actions, I wouldn't bother doing any extra work to make things cleaner and would pass the container parameter straight in the controller action.
However, should there be a need to get the best employees in a Twig template, for example, it would be nice if it wouldn't be necessary to pass the parameter. One possibility would be using a setter method and passing the parameter down beforehand to each and every entity that gets retrieved from the database. You could do this either in repositories or entitiy managers. The most advanced solution would be to listen to the postLoad event and pass the parameter in an event listener.

Resources