I have a User entity that contains address. I will save address as a json in my database. After form validation, I have to manually serialize address before persisting data. Is there anyway to avoid doing it like that ? Is it possible to call serialize event when doctrine is persisting data ?
class User{
/**
* #ORM\Column(name="username", type="string", length=30)
**/
private $username;
/**
* #ORM\Column(name="address", type="json")
**/
private $address;
}
class Address{
private $postalcode;
private $street;
}
// Inside my controller
class UserController extends Controller{
/**
* #Rest\View(StatusCode = Response::HTTP_CREATED)
*
* #Rest\Post(
* path = "/user",
* name = "user_create"
* )
*/
public function createAction(){
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->submit($request->request->all());
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$user->setAddress($this->get('jms_serializer')->serialize($user->getAddress(), 'json'));
$em->persist($user);
$em->flush();
return $this->view($user, Response::HTTP_CREATED);
}
return $form;
}
}
Doctrine failed to make it json because address property was private (PHP json_encode returning empty sctructure). Making it public resolve the problem.
When defining type as json, doctrine will use php's json encoding functions: https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#json-array
Thanks
Related
When implementing a rest json api with Symfony, one can deserialize the data for a create route with Jms Serializer:
$user = $serializer->deserialize($data, 'AppBundle\Entity\User', 'json');
but this makes all parameters of the User Entity available to set from the POST request, which might not be that good.
An alternative to this is to use setters in the controller:
$user = new User();
$user->setUsername($request->request->get('username'));
$user->sePassword($request->request->get('password'));
...
The latter option makes it more clear which parameters are actually able to set, but it requires a lot of code for a large entity.
What is the preferred way here?
Is it a third option?
You can serialize json data from your controller natively in Symfony once you have the Serializer component installed.
$user = $this->get('serializer')->deserialize($data, 'AppBundle\Entity\User', 'json');
When your object is created via this method, using the json from your request (decoded and then denormalized), the setters of your object are utilized to populate the properties of your object.
Could you post your User Entity?
Alternatively you can use Form Classes to perform this task.
Modification in relation to the comment on your question.
Annotation Groups in your entities works for serialization and deserialization.
class Item
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #Groups({"first", "second"})
*/
private $id;
/**
* #ORM\Column(type="string", name="name", length=100)
* #Groups({"first"})
*/
private $name;
/**
* #ORM\Column(type="string", name="name", length=200)
* #Groups({"second"})
*/
private $description;
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
}
If you had both "name" and "description" in your POST data, you could insert either into your entity with the following:
$object = $this->get('serializer')->deserialize($data, 'AppBundle\Entity\User', 'json', ['groups' => ['first']]);
Or
$object = $this->get('serializer')->deserialize($data, 'AppBundle\Entity\User', 'json', ['groups' => ['second']]);
In the first case, only the name property would be populated and only the description property in the second case.
I've an entity with a plainPassword and a password attribute. In form, I map on the plainPassword. After, when the user valid the form, I do password validation on the plainPassword.
To encode the password, I use an EventSubscriber that listen on prePersist and preUpdate. It works well for the register form, because it's a new entity, the user fill some persisted attributes, then doctrine persist it and flush.
But, when I just want to edit the password, it doesn't work, I think it's because the user just edit a non persisted attribute. Then Doctrine doesn't try to persist it. But I need it, to enter in the Subscriber.
Someone know how to do it ? (I've a similar problem in an other entity) For the moment, I do the operation in the controller...
Thanks a lot.
My UserSubscriber
class UserSubscriber implements EventSubscriber
{
private $passwordEncoder;
private $tokenGenerator;
public function __construct(UserPasswordEncoder $passwordEncoder, TokenGenerator $tokenGenerator)
{
$this->passwordEncoder = $passwordEncoder;
$this->tokenGenerator = $tokenGenerator;
}
public function getSubscribedEvents()
{
return array(
'prePersist',
'preUpdate',
);
}
public function prePersist(LifecycleEventArgs $args)
{
$object = $args->getObject();
if ($object instanceof User) {
$this->createActivationToken($object);
$this->encodePassword($object);
}
}
public function preUpdate(LifecycleEventArgs $args)
{
$object = $args->getObject();
if ($object instanceof User) {
$this->encodePassword($object);
}
}
private function createActivationToken(User $user)
{
// If it's not a new object, return
if (null !== $user->getId()) {
return;
}
$token = $this->tokenGenerator->generateToken();
$user->setConfirmationToken($token);
}
private function encodePassword(User $user)
{
if (null === $user->getPlainPassword()) {
return;
}
$encodedPassword = $this->passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($encodedPassword);
}
My user Entity:
class User implements AdvancedUserInterface, \Serializable
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="email", type="string", length=255, unique=true)
* #Assert\NotBlank()
* #Assert\Email()
*/
private $email;
/**
* #Assert\Length(max=4096)
*/
private $plainPassword;
/**
* #ORM\Column(name="password", type="string", length=64)
*/
private $password;
ProfileController:
class ProfileController extends Controller
{
/**
* #Route("/my-profile/password/edit", name="user_password_edit")
* #Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
*/
public function editPasswordAction(Request $request)
{
$user = $this->getUser();
$form = $this->createForm(ChangePasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Encode the password
// If I decomment it, it's work, but I want to do it autmaticlally, but in the form I just change the plainPassword, that is not persisted in database
//$password = $this->get('security.password_encoder')->encodePassword($user, $user->getPlainPassword());
//$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->flush();
$this->addFlash('success', 'Your password have been successfully changed.');
return $this->redirectToRoute('user_profile');
}
return $this->render('user/password/edit.html.twig', [
'form' => $form->createView(),
]);
}
}
You can force Doctrine to mark an object as dirty by manipulating the UnitOfWork directly.
$em->getUnitOfWork()->scheduleForUpdate($entity)
However, I do strongly discourage this approach as it violates carefully crafted abstraction layers.
I have 2 entities Client and Address with a OneToMany relationship.
When I create a new client with an address, it saves both the client and address but does not set the client_id on the address, it is NULL.
I am using fosrestbundle and jmsserializer and sending the data as a json object.
In my controller I have the following:
/**
* #REST\POST("/clients", name="create_client")
*/
public function createClientAction(Request $request)
{
$serializer = $this->get('jms_serializer');
$client = $serializer->deserialize($request->getContent(), 'AppBundle\Entity\Client', 'json');
$em = $this->getDoctrine()->getManager();
$em->persist($client);
$em->flush();
return $this->view($client, 200);
}
Here is a simplified request payload:
{ "name" : "foo", "addresses" : [ { "zip" : "12345" } ]
In my database it creates a new client with name = foo along with an address with zip = 12345, however the field client_id is NULL
My entities are mapped as follows:
//Client.php
...
...
/**
* #ORM\OneToMany(targetEntity="Address", mappedBy="client", cascade={"persist", "remove"})
*/
private $addresses;
//Address.php
...
...
/**
* #ORM\ManyToOne(targetEntity="Client", inversedBy="addresses")
*
*/
private $client;
update
I'm even more confused now, I just realized I do not have any getters/setters in my entities, yet I am able to get / set data.
I am guessing setting has something to do with serializer->deserialize. I have the following in my services:
jms_serializer.object_constructor:
alias: jms_serializer.doctrine_object_constructor
public: false
And getting has something to do with the fosrestbundle. Here is the get route:
/**
* #REST\GET("/clients/{client}", name="get_client")
*/
public function getClientAction(Request $request, Client $client)
{
return $this->view($client, 200);
}
Apparently I needed to merge and not persist the entity.
I updated the route:
$em = $this->getDoctrine()->getManager();
$em->merge($client);
$em->flush();
and the Client entity:
/**
* #ORM\OneToMany(targetEntity="Address", mappedBy="client", cascade={"persist", "remove", "merge"})
*/
private $addresses;
Seems to be working now!
I have a doctrine entity User and a document Address (stored in mongoDB). I want to set an one to many relation between them by userId property. (the user has many addresses)
My User Entity:
namespace BlaBla\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $firstName;
... and so on
My Address document:
namespace BlaBla\UserBundle\Document;
/**
* BlaBla\UserBundle\Document\Address
*/
class Address
{
/**
* #var MongoId $id
*/
protected $id;
/**
* #var string $firstName
*/
protected $firstName;
/**
* #var string $lastName
*/
protected $lastName;
/**
* #var int $userId
*/
protected $userId;
... and so on
My goal is to create the getUser() method for the Address object and the getAddresses() method for the User object.
I've decided to place the method getAddresses() to the doctrine UserRepository class and to inject there the necessary document manager to be able to access to the Address Document. I've overriden the constructor of the userRepository and passed to it the necessary document manager object.
Please, look to the UserRepository class:
<?php
namespace BlaBla\UserBundle\Repository;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
/**
* #var \Doctrine\ODM\MongoDB\DocumentManager
*/
private $_dm;
/**
* #param \Doctrine\ORM\EntityManager $dm
*/
public function __construct(\Doctrine\ORM\EntityManager $em, $dm) {
$metaData = new \Doctrine\ORM\Mapping\ClassMetadata('BlaBla\UserBundle\Entity\User');
parent::__construct($em, $metaData);
$this->_dm = $dm;
}
/**
* #param $user_id integer
* #return \BlaBla\UserBundle\Document\Address
*/
public function getAddress($user_id) {
$address = $this->_dm->getRepository('BlaBlaUserBundle:Address');
$rt = $address->findByUserId($user_id);
return $rt;
}
public function getAllUsers()
{
return $this->findAll();
}
}
After this I can access to the repository from my controller via:
$em = $this->getDoctrine()->getManager();
$dm = $this->get('doctrine_mongodb')->getManager();
$t = new \BlaBla\UserBundle\Repository\UserRepository($em, $dm);
var_dump($t->getAddress($id));
var_dump($t->getAllUsers());
Both methods work just fine, but now I can't access to the repository using shortcuts like:
$user = $this->getDoctrine()->getRepository('BlaBlaUserBundle:User');
I thought about making the Repository as service with something like this:
user.repository:
class: BlaBla\UserBundle\Repository\UserRepository
arguments: [#doctrine.orm.entity_manager, #doctrine.odm.mongo_db.document_manager]
in my services.yml file, but this only lets me to access the repository with:
$this->get('user.repository');
the default shortcuts doesn't work still.
Please help to find a correct solution for this problem.
Thanks.
Where did you specified the UserRepository? In your User.php with annotation ? Maybe that is the only thing what is missing.
But if you want to use entity and document repository, I advise you to use Doctrine extensions, specifically Reference.
I'm trying to query using entity manager in a entity class file but I'm getting this error:
FatalErrorException: Error: Call to undefined method Acme\MasoudBundle\Entity\User::getDoctrine() in /var/www/test/src/Acme/MasoudBundle/Entity/User.php line 192
my entity class is :
namespace Acme\MasoudBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set isActive
*
* #param boolean $isActive
* #return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* #inheritDoc
*/
public function getRoles()
{
$em = $this->getDoctrine()->getManager();
$Permission= $em->getRepository('MasoudBundle:Permission')->find(1);
$this->permissions[]=$Permission->permission;
return $this->permissions;
}
}
I want to have a permission and authentication system like this, can you help me please? there are 5 tables, a user table, a group table, a permission table, and a group_permission and a user_group table. so After user logins, I want to check which user is for which group, and get the groups permission. how can I do that? please help me as much as you have time.
Your entity should not know about other entities and the Entity Manager because of the separation of concerns.
Why don't you simply map your User to the appropriate Role(s) (instances of Permission entity in your case) using Doctrine Entity Relationships/Associations. It will allow you to access the appropriate permissions of a given user from the User instance itself.
In this line:
$em = $this->getDoctrine()->getManager();
$this refers to the current class, the User Entity that does not have a method called getDoctrine(). $this->getDoctrine() works in controllers where you extend the Controller class a subclass of ContainerAware which contains the getDoctrine() method.
In other terms, this method works only on objects of class container or its subclasses, like this: $controller->getDoctrine()->getManager().
Besides, you don't want to have an EntityManager inside your entity classes, that's not a good way of doing things. You would better use listners to do such stuffs
I solved this:
global $kernel;
$em = $kernel->getContainer()->get('doctrine')->getManager();
$role = $em->getRepository('BackendBundle:user_types')->findOneBy(array(
'id' => 10
));