Get FosUser authenticated to persist into Easy Admin Entity ( USER LOG) - symfony

I have An entity Product Manged By EasyAdmin, i ALSO USE fos UserbUNDLE for user Management.
Everything works fine but when i add a new user in easyadmin i have a dropdown of user but i want to have automatically the authenticated user.
I have defined an one to Many relation between User and Product in an attribut of the class Product.
/**
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
Product Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Product
*
* #ORM\Table(name="product")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ProductRepository")
* #Vich\Uploadable
*/
class Product
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="reference", type="string", length=150)
*/
private $reference;
/**
* #ORM\ManyToOne(targetEntity="Type")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
*/
private $type;
/**
* #ORM\Column(type="boolean")
*/
public $status;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=150)
*/
private $titre;
User :
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
}
How to get it automatically?

Can we have more details ? Both entities and controller because i think your not using the good targetEntity

i had quite the same issue,i mean,in some cases i was needing to get ONLY THE CURRENT LOGGED USER INFO INSIDE MY SELECT, and sometimes i was needing to get the full list of users from the database
maybe the solution i found could help you:
Get the logged user info in the easyadmin select
to make it simple you have to override the easyadmin formbuilder and ask only the currently logged user info
$formBuilder->add('user', EntityType::class, array(
'class' => 'AppBundle:User',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.id = :id')->setParameter('id',$this->getUser()->getId());
},
));
return $formBuilder;

Related

Unable to find the Entity relative to a proxy

I have a simple Request on a Contact table.
use App\Entity\Contact;
...
$contact = $this->getUser()->getContact();
$form = $this->createForm(ParentContactType::class,$contact);
$form->handleRequest($request);
But when Handling the form, Symfony throws following Exception:
Unable to find the object manager associated with an entity of class "Proxies\__CG__\App\Entity\Contact".
The contact Class is a normal one,
<?php
namespace App\Entity;
use App\Repository\ContactRepository;
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Core\Annotation\ApiResource;
/**
* #ORM\Entity(repositoryClass=ContactRepository::class)
*/
#[ApiResource]
class Contact
{
const FIRST_CONTACT = "Contact principal";
const SECOND_CONTACT = "Second contact";
const THIRD_CONTACT = "Troisième contact";
public function __construct(){
}
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $type;
/**
* #ORM\Column(type="string", length=3, nullable=true)
*/
private $gender;
+ getter and setter
It used to be working fine, but I do not know how to debug the issue.
Any help would be great.

FOSUserBundle and custom fields in user entity

I'm using FOSUserBundle with custom fields in my user class.
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
* #ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
*/
class User extends BaseUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your name.", groups={"Registration", "Profile"})
* #Assert\Length(min="3", max="255", groups={"Registration", "Profile"})
*/
protected $name;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Message", mappedBy="fromUser")
*/
protected $sentMessages;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Message", mappedBy="toUser")
*/
protected $receivedMessages;
/**
* #ORM\Column(type="date")
*/
protected $dateRegistered;
/**
* #ORM\Column(type="string", length=250, nullable=true)
*
*/
protected $banReason;
public function __construct() {
parent::__construct();
$this->dateRegistered = new \DateTime();
}
/* getters and setters */
}
I want to show a personal message to the locked users, filling $banReason field.
I found that error.user variable contains part of the user entity, but my field is set to null instead of it's real value.
Sorry, but i'm kinda noob in hooks and services. :-(
Have a nice day!

Why does Doctrine update related entities, after JMS deserialize

I'm using Doctrine+JMSserializer in Symfony2 project, just found a problem that related entities and their data could be compromised during typical JMS "deserialize" and Doctrine "persist" operation.
$data = [
'locale' => 'en',
'name' => $this->faker->sentence(),
'content' => $this->faker->text(),
'subject' => [
'id' => $page->getId(),
'name' => 'new name' // <-- compromised property
]
];
$rawPayload = json_encode($data);
$entity = $this->serializer->deserialize(
$rawPayload,
$resolvedClass,
'json'
);
and after typical persist operation for new $entity related Page entity name, being change - so its a problem.
$this->getEntityManager()->persist($entity);
$this->getEntityManager()->flush();
The goal is to set page Id for the review, but prevent change for other properties, otherwise Page entity can be compromised. I tried to solve this issue changing annotations, doctrine settings, etc..
Any ideas how to solve this issue in natural way?
Review and Page entites:
use Aisel\ReviewBundle\Entity\Review as BaseReview;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation as JMS;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Review
*
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="aisel_page_review")
* #ORM\Entity(repositoryClass="Aisel\ResourceBundle\Repository\CollectionRepository")
* #JMS\ExclusionPolicy("all")
*/
class Review extends BaseReview
{
/**
* #var Page
* #Assert\NotNull()
* #ORM\ManyToOne(targetEntity="Aisel\PageBundle\Entity\Page", inversedBy="pages")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="page_id", referencedColumnName="id", nullable=false)
* })
* #JMS\Type("Aisel\PageBundle\Entity\Page")
* #JMS\Expose
* #JMS\MaxDepth(2)
*/
private $subject;
/**
* #return Page
*/
public function getSubject()
{
return $this->subject;
}
/**
* #param Page $subject
*/
public function setSubject($subject)
{
$this->subject = $subject;
}
}
<?php
namespace Aisel\PageBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use JMS\Serializer\Annotation as JMS;
use Aisel\ResourceBundle\Domain\UrlInterface;
use Aisel\PageBundle\Entity\Node;
use Aisel\PageBundle\Entity\Review;
use Aisel\UserBundle\Entity\User;
use Aisel\ResourceBundle\Domain\IdTrait;
use Aisel\ResourceBundle\Domain\UpdateCreateTrait;
use Aisel\ResourceBundle\Domain\MetaTrait;
use Aisel\ResourceBundle\Domain\LocaleTrait;
use Aisel\ResourceBundle\Domain\StatusTrait;
use Aisel\ResourceBundle\Domain\NameTrait;
use Aisel\ResourceBundle\Domain\ContentTrait;
use Aisel\ResourceBundle\Domain\CommentStatusTrait;
/**
* Page
*
* #author Ivan Proskuryakov <volgodark#gmail.com>
*
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="aisel_page")
* #ORM\Entity(repositoryClass="Aisel\ResourceBundle\Repository\CollectionRepository")
* #JMS\ExclusionPolicy("all")
*/
class Page implements UrlInterface
{
use IdTrait;
use NameTrait;
use ContentTrait;
use LocaleTrait;
use StatusTrait;
use CommentStatusTrait;
use MetaTrait;
use UpdateCreateTrait;
/**
* #var ArrayCollection
* #ORM\ManyToMany(targetEntity="Aisel\PageBundle\Entity\Node")
* #ORM\JoinTable(
* name="aisel_page_page_node",
* joinColumns={#ORM\JoinColumn(name="page_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="node_id", referencedColumnName="id")}
* )
* #JMS\Type("ArrayCollection<Aisel\PageBundle\Entity\Node>")
* #JMS\Expose
* #JMS\MaxDepth(2)
* #JMS\Groups({"collection","details"})
*/
private $nodes;
/**
* #var ArrayCollection<Aisel\PageBundle\Entity\Review>
* #ORM\OneToMany(targetEntity="Aisel\PageBundle\Entity\Review", mappedBy="subject", cascade={"remove"})
* #ORM\OrderBy({"createdAt" = "DESC"})
* #JMS\Expose
* #JMS\MaxDepth(2)
* #JMS\Type("ArrayCollection<Aisel\PageBundle\Entity\Review>")
* #JMS\Groups({"collection","details"})
*/
private $reviews;

symfony2 how to override the User class with FosuserBundle?

My problem is quite simple but i search for an hour without succeed, i would like to add some constraint to the UserEntity. For example, i would like to limit the length of a username
I think the best way is to not touche FOS in Vendor. I have create my own userBundle with my own layout.html etc ... But i cannot override attribut who is already existing in FosuserBundle (it's working for the layout overriding btw my userBundle is a child of FOS)
the funny thing is "id" has no problem for the overriding
My User entity :
<?php
namespace Diane\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Diane\UserBundle\Entity\UserRepository")
*/
class User extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="username", type="string", length=10)
*/
protected $username;
}
Fos User model :
<?php
namespace FOS\UserBundle\Model;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
abstract class User implements UserInterface, GroupableInterface
{
protected $id;
/**
* #var string
*/
protected $username;
...
}
i have already try to remove :
/**
* #var string
*/
Error message :
Doctrine\ORM\Mapping\MappingException] Duplicate definition of column
'username' on entity 'Diane\UserBundle\Entity\User' in a field or
discriminator column mapping.
Thanks for any idea you could give me
Try AttributeOverrides Doctrine annotation:
/**
* User
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Diane\UserBundle\Entity\UserRepository") / class User extends
*
* #ORM\AttributeOverrides({
* #ORM\AttributeOverride(name="username",
* column=#ORM\Column(
* name = "username",
* type = "string",
* length = 10
* )
* )
* })
*
*/
class User extends BaseUser
{

Doctrine2 - OneToMany/ManyToOne Bidirectional not working

Hi everyone and thanks for help,
I'm currently dealing with a problem while I want to make an OneToMany/ManyToOne Bidirectional Relationship with Doctrine2 (& Symfony2).
Here are my two classes : User (which extends FOSUser) and collection which represents a collection of videos.
Of course, a user can have several collections, but a collection is only related to one user.
/* COLLECTION */
namespace Com\ComBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Com\ComBundle\Entity\Collection
*
* #ORM\Table(name="collection")
* #ORM\HasLifecycleCallbacks
*/
class Collection
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Com\UserBundle\Entity\User", inversedBy="collections")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* Set user
*
* #param Com\UserBundle\Entity\User $user
* #return Collection
*/
public function setUser(\Com\UserBundle\Entity\User $user) {
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return Com\UserBundle\Entity\User User
*/
public function getUser() {
return $this->user;
}
}
And user,
/* USER */
namespace Com\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/*
* #ORM\OneToMany(targetEntity="Com\ComBundle\Entity\Collection", mappedBy="user")
*/
private $collections;
public function __construct()
{
parent::__construct();
$this->collections = \Doctrine\Common\Collections\ArrayCollection();
}
}
When I use the doctrine:generate:entities command, it does not generate the methods relative to $collections (get/add/remove), and even if I wrote it myself, it does not work.
getCollections() return NULL for example.
What am I missing in this code ?

Resources