I have this entity:
Profile.php
/**
* LoPati\BlogBundle\Entity\Profile
*
* #ORM\Table(name="profile")
* #ORM\Entity
* #Gedmo\TranslationEntity(class="LoPati\BlogBundle\Entity\ProfileTranslation")
*/
class Profile
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Gedmo\Translatable
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
protected $name=null;
/**
* #var text $description
* #Gedmo\Translatable
* #ORM\Column(name="description", type="text", nullable=true)
*/
protected $description=null;
/**
* #ORM\OneToMany(targetEntity="ProfileTranslation", mappedBy="object", cascade={"persist", "remove"})
*/
protected $translations;
/**
* Required for Translatable behaviour
* #Gedmo\Locale
*/
protected $locale;
public function __construct()
{
$this->translations = new ArrayCollection;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function getLocale()
{
return $this->locale;
}
public function setLocale($locale)
{
$this->locale = $locale;
}
public function setName($name)
{
$this->name=$name;
}
public function getName()
{
return $this->name;
}
public function setDescription($description)
{
}
public function getDescription()
{
return $this->description;
}
public function getTranslations()
{
return $this->translations;
}
public function addTranslation(ProfileTranslation $t)
{
$this->translations->add($t);
$t->setObject($this);
$this->name = $this->translations[0];
$this->description = $this->translations[1];
}
public function removeTranslation(ProfileTranslation $t)
{
$this->translations->removeElement($t);
}
public function setTranslations($translations)
{
$this->translations = $translations;
$this->name = $this->translations[0];
$this->description = $this->translations[1];
}
public function __toString()
{
return "hola";
}
}
And ProfileTranslation.php
/**
* #ORM\Entity
* #ORM\Table(name="profile_translations",
* uniqueConstraints={#ORM\UniqueConstraint(name="lookup_unique_idx", columns={
* "locale", "object_id", "field"
* })}
* )
*/
class ProfileTranslation extends AbstractPersonalTranslation
{
/**
* Convinient constructor
*
* #param string $locale
* #param string $field
* #param string $content
*/
public function __construct($locale = null, $field = null, $content = null)
{
$this->setLocale($locale);
$this->setField($field);
$this->setContent($content);
}
/**
* #ORM\ManyToOne(targetEntity="Profile", inversedBy="translations")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $object;
public function __toString()
{
return $this->getContent();
}
}
I want that when edit arraycollection that is a ProfileTranslation table, then also update the name and description field but form Profile Table, and it be the first element that collection.
It work when I create new Profile, but when I edit this profile, only update the ProfileTranslation Table and not Profile table.
How I can do it?
Your implementation turns away a little too classic Translatable use.
You could maybe have a look about TranslationFormBundle and its Demo if it right for you.
Related
I'm creating an application to generate test questions, where I can add N answers to single question. (I can add these answers via jQuery).
How should I correctly POST this? I have read about Form Events but I don't have any idea how to implement it in this situation.
Here is my current code (I'm using Symfony 4):
Question Entity
/**
* #ORM\Entity(repositoryClass="App\Repository\QuestionRepository")
* #ORM\Table(name="question")
*/
class Question
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="questions")
* #ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private $user;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $label;
/**
* #ORM\Column(type="text", length=2000)
*/
private $content;
/**
* #ORM\Column(type="string", length=45, options={"default": "single"})
*/
private $type;
/**
* #ORM\OneToMany(targetEntity="App\Entity\QuestionAnswer", mappedBy="question")
*/
private $answers;
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #return User
*/
public function getUser(): User
{
return $this->user;
}
/**
* #param User $user
*/
public function setUser(User $user): void
{
$this->user = $user;
}
/**
* #return string
*/
public function getLabel(): string
{
return $this->label;
}
/**
* #param string $label
*/
public function setLabel(string $label): void
{
$this->label = $label;
}
/**
* #return string
*/
public function getContent(): string
{
return $this->content;
}
/**
* #param string $content
*/
public function setContent(string $content): void
{
$this->content = $content;
}
/**
* #return string
*/
public function getType(): string
{
return $this->type;
}
/**
* #param mixed $type
*/
public function setType($type): void
{
$this->type = $type;
}
/**
* #return Collection|QuestionAnswer[]
*/
public function getAnswers()
{
return $this->answers;
}
}
QuestionAnswer Entity
class QuestionAnswer
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="answers")
* #ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private $question;
/**
* #ORM\Column(type="text")
*/
private $content;
/**
* #ORM\Column(type="boolean")
*/
private $is_correct;
public function getId()
{
return $this->id;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getIsCorrect(): ?bool
{
return $this->is_correct;
}
public function setIsCorrect(bool $is_correct): self
{
$this->is_correct = $is_correct;
return $this;
}
/**
* #return self
*/
public function getQuestion(): self
{
return $this->question;
}
/**
* #param Question $question
*/
public function setQuestion(Question $question): void
{
$this->question = $question;
}
}
You need to follow the documentation:
How to Embed a Collection of Forms
Where in your case Question = Task, and QuestionAnswer = Tag.
try to change your code to this and see the difference your self:
in Question entity:
use Doctrine\Common\Collections\ArrayCollection;
//....
/**
* #ORM\Entity(repositoryClass="App\Repository\QuestionRepository")
* #ORM\Table(name="question")
*/
class Question
{
//....
/**
* #ORM\ManyToMany(targetEntity="App\Entity\QuestionAnswer")
* #var answers
*/
private $answers;
public function setAnswers(answers $answers)
{
$this->answers = $answers;
}
public function getAnswers()
{
return $this->answers;
}
public function __construct()
{
$this->answers = new ArrayCollection();
}
}
then delete the question field from QuestionAnswer entity and update your database schema
I'm creating an app that keeps user scores in the database based on questions they solve. I have User, Problem and Submission entities. For all of them I have One-to-Many relationship from the User entity. The problem entity has the point field that holds the score of a problem. I'm trying to retrieve all users with their total points.
Here is my controller;
$userService = $this->container->get('userservice');
$users = $userService->findAll();
foreach ($users as $user){
$usersWPoints = $user->getSubmissions()->getProblemId()->getPoints;
}
However this returns the following error;
Attempted to call an undefined method named "getProblemId" of class "Doctrine\ORM\PersistentCollection".
Here are my models
User.php
/**
* Class User
* #package AppBundle\Entity
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #ORM\Table(name="user")
* #ORM\HasLifecycleCallbacks()
* #UniqueEntity(fields="username", message="Email already taken")
*
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank(message="Please enter a valid email address")
* #Assert\Email()
*/
private $username;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank(message="Please enter a valid email address")
*/
private $usrname;
/**
* #Assert\NotBlank()
* #Assert\Length(max=4096)
*/
private $plainPassword;
/**
* The below length depends on the "algorithm" you use for encoding
* the password, but this works well with bcrypt.
*
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank(message="Please enter a valid name")
*/
private $fullname;
/**
* #var array
* #ORM\Column(name="roles", type="json_array")
*/
protected $roles;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Problem", mappedBy="createdby")
*/
protected $problems;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Feed", mappedBy="createdby")
*/
protected $feeds;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Comment", mappedBy="createdby")
*/
protected $comments;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Submission", mappedBy="user_id")
*/
protected $submissions;
// other properties and methods
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($password)
{
$this->plainPassword = $password;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getSalt()
{
// The bcrypt algorithm doesn't require a separate salt.
// You *may* need a real salt if you choose a different encoder.
return null;
}
// other methods, including security methods like getRoles()
/**
* #return array
*/
public function getRoles()
{
return $this->roles;
}
public function setRoles(array $roles){
$this->roles = $roles;
return $this;
}
/**
* #return mixed
*/
public function getFullname()
{
return $this->fullname;
}
/**
* #param mixed $fullname
*/
public function setFullname($fullname)
{
$this->fullname = $fullname;
}
/**
* #return mixed
*/
public function getUsrname()
{
return $this->usrname;
}
/**
* #param mixed $usrname
*/
public function setUsrname($usrname)
{
$this->usrname = $usrname;
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getSubmissions()
{
return $this->submissions;
}
Problem.php
/**
* Class Problem
* #package AppBundle\Entity
* #ORM\Entity(repositoryClass="AppBundle\Repository\ProblemRepository")
* #ORM\Table(name="problem")
* #ORM\HasLifecycleCallbacks()
*
*/
class Problem
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, unique=True)
* #Assert\NotBlank(message="Please enter a valid title")
*/
protected $title;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Please enter a valid description")
*/
protected $description;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Please enter a valid value")
*/
protected $points;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Please enter a valid flag")
*/
protected $flag;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Please enter a valid value")
*/
protected $category;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="problems")
* #ORM\JoinColumn(name="createdby", referencedColumnName="id")
*/
protected $createdby;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Submission", mappedBy="problem_id")
*/
protected $submissions;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(type="string", length=255, unique=false,)
*/
protected $slug;
/**
* #return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* #param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* #return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* #param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* #return mixed
*/
public function getPoints()
{
return $this->points;
}
/**
* #param mixed $points
*/
public function setPoints($points)
{
$this->points = $points;
}
/**
* #return mixed
*/
public function getFlag()
{
return $this->flag;
}
/**
* #param mixed $flag
*/
public function setFlag($flag)
{
$this->flag = $flag;
}
/**
* #return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* #param mixed $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* #return mixed
*/
public function getCreatedby()
{
return $this->createdby;
}
/**
* #param mixed $createdby
*/
public function setCreatedby($createdby)
{
$this->createdby = $createdby;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set slug
*
* #param string $slug
*
* #return Problem
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* #return mixed
*/
public function getSubmissions()
{
return $this->submissions;
}
/**
* #param mixed $submissions
*/
public function setSubmissions($submissions)
{
$this->submissions = $submissions;
}
}
Submission.php
class Submission
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Problem", inversedBy="submissions")
* #ORM\JoinColumn(name="problem_id", referencedColumnName="id")
*/
protected $problem_id;
/**
* #ORM\Column(type="boolean")
*/
protected $correct = false;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="submissions")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user_id;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Flag cannot be blank")
*/
protected $submission_flag;
/**
* #return mixed
*/
public function getProblemId()
{
return $this->problem_id;
}
/**
* #param mixed $problem_id
*/
public function setProblemId($problem_id)
{
$this->problem_id = $problem_id;
}
/**
* #return mixed
*/
public function getCorrect()
{
return $this->correct;
}
/**
* #param mixed $correct
*/
public function setCorrect($correct)
{
$this->correct = $correct;
}
/**
* #return mixed
*/
public function getUserId()
{
return $this->user_id;
}
/**
* #param mixed $user_id
*/
public function setUserId($user_id)
{
$this->user_id = $user_id;
}
/**
* #return mixed
*/
public function getSubmissionFlag()
{
return $this->submission_flag;
}
/**
* #param mixed $submission_flag
*/
public function setSubmissionFlag($submission_flag)
{
$this->submission_flag = $submission_flag;
}
}
Any suggestions on accessing each user and their total points would be highly appreciated.
getSubmissions() returns collenction and getProblemId() is method of Submissions.
So as soon as you have many Submissions fo each user - i would create some getTotalPoints() method for User where you can run in foreach.
This kind of way:
public function getTotalPoints()
{
$submissions = $this->getSubmissions();
$points = 0;
foreach ($submissions as $submission) {
$points += $submission->getProblemId()->getPoints();
}
return $points;
}
You could do something like this:
$userService = $this->container->get('userservice');
$users = $userService->findAll();
$pointPerUser = array();
foreach ($users as $user){
$userSubmissions = $user->getSubmissions();
$pointPerUser[$user->getId()] = 0;
foreach ($userSubmissions as $userSubmission) {
// Probably here you want to check if the submission is correct
$pointPerUser[$user->getId()] += $userSubmission->getProblemId()->getPoints();
}
}
By the way, the submission attribute shouldn't be $problem_id but $problem, and the method is getProblem(), as you are getting a Problem instance, not an id. The field name for the table is ok, as you are storing an id.
I have the following inventory entity object for Doctrine that I created for use in Symfony 3.0.
Simply put how do I get access to the information that I put in the entity via annotations?
For example, companyID, has a ManyToOne annotation that references inversedBy="location". This particular information is very useful to me so I can tell if its a child relationship by foreign key or parent relationship.
If I can get the information about the entity that I described via annotations somehow in an array with Doctrine that would be great. Is this possible to do? Essentially I'm looking for introspection functions on the entity.
<?php
namespace AppBundle\Entity;
use Gedmo\Translatable\Translatable;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Inventory
*
* #ORM\Table(name="distribution_inventory")
* #ORM\Entity(repositoryClass="AppBundle\Repository\InventoryRepository")
*/
class Inventory implements Translatable {
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
/**
* #var string
* #Gedmo\Slug(fields={"name","id"},suffix=".html")
* #ORM\Column(name="inventoryslug", type="string", length=255, nullable=false, nullable=true)
*/
private $inventoryslug;
/**
* #var string
*
* #ORM\Column(name="barcode", type="string", length=255, nullable=true)
*/
private $barcode;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var string
* #ORM\Column(name="imagename", type="string", nullable=true)
*/
private $imagename;
/**
* #Gedmo\Locale
* Used locale to override Translation listener`s locale
* this is not a mapped field of entity metadata, just a simple property
*/
private $locale;
/**
* #var \AppBundle\Entity\InventoryCategory
*
* #ORM\ManyToOne(targetEntity="\AppBundle\Entity\InventoryCategory")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="categoryid", referencedColumnName="id")
* })
*/
private $category;
/**
* #var \AppBundle\Entity\Company
* #Assert\Type(type="\AppBundle\Entity\Company")
* #Assert\Valid()
* #ORM\ManyToOne(targetEntity="\AppBundle\Entity\Company", inversedBy="Location")
* #ORM\JoinColumn(name="companyid", referencedColumnName="id", onDelete="CASCADE")
*/
protected $companyId;
/**
* #var \DateTime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* #var string
* #ORM\Column(name="defaultsellprice",precision=14, scale=2, nullable=true)
*/
private $defaultsellprice;
/**
* #var boolean
*
* #ORM\Column(name="onwaycount", type="integer", nullable=false)
*/
private $onwaycount;
/**
* #var boolean
*
* #ORM\Column(name="instorecount", type="integer", nullable=false)
*/
private $instorecount;
/**
* #var boolean
*
* #ORM\Column(name="wayoutcount", type="integer", nullable=false)
*/
private $wayoutcount;
/**
* #var boolean
*
* #ORM\Column(name="instore", type="string", length=10, nullable=false)
*/
private $instore;
/**
* #var string
*
* #ORM\Column(name="isarchived", type="string", length=5, nullable=false,options={"default":false})
*/
private $isarchived;
/**
* #var string
*
* #ORM\Column(name="archivestatus", type="string", length=5, nullable=false,options={"default":true})
*/
private $archivestatus;
function __construct() {
$this->onwaycount=0;
$this->instore=FALSE;
$this->instorecount=0;
$this->wayoutcount=0;
}
/**
* Get id
*
* #return int
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Inventory
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set barcode
*
* #param string $barcode
*
* #return Inventory
*/
public function setBarcode($barcode) {
$this->barcode = $barcode;
return $this;
}
/**
* Get barcode
*
* #return string
*/
public function getBarcode() {
return $this->barcode;
}
/**
* Set description
*
* #param string $description
*
* #return Inventory
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
public function getImagename() {
return $this->imagename;
}
public function getCategory() {
return $this->category;
}
public function getCompanyId() {
return $this->companyId;
}
public function getCreated() {
return $this->created;
}
public function getUpdated() {
return $this->updated;
}
public function getOnwaycount() {
return $this->onwaycount;
}
public function getInstorecount() {
return $this->instorecount;
}
public function getWayoutcount() {
return $this->wayoutcount;
}
public function getInstore() {
return $this->instore;
}
public function setImagename($imagename) {
$this->imagename = $imagename;
return $this;
}
public function setCategory(\AppBundle\Entity\InventoryCategory $category) {
$this->category = $category;
return $this;
}
public function setCompanyId(\AppBundle\Entity\Company $companyId) {
$this->companyId = $companyId;
return $this;
}
public function setCreated(\DateTime $created) {
$this->created = $created;
return $this;
}
public function setUpdated(\DateTime $updated) {
$this->updated = $updated;
return $this;
}
public function setOnwaycount($onwaycount) {
$this->onwaycount = $onwaycount;
return $this;
}
public function setInstorecount($instorecount) {
$this->instorecount = $instorecount;
return $this;
}
public function setWayoutcount($wayoutcount) {
$this->wayoutcount = $wayoutcount;
return $this;
}
public function setInstore($instore) {
$this->instore = $instore;
return $this;
}
public function getDefaultsellprice() {
return $this->defaultsellprice;
}
public function setDefaultsellprice($defaultsellprice) {
$this->defaultsellprice = $defaultsellprice;
return $this;
}
public function getInventoryslug() {
return $this->inventoryslug;
}
public function setInventoryslug($inventoryslug) {
$this->inventoryslug = $inventoryslug;
return $this;
}
public function setTranslatableLocale($locale) {
$this->locale = $locale;
}
public function getIsarchived() {
return $this->isarchived;
}
public function getArchivestatus() {
return $this->archivestatus;
}
public function setIsarchived($isarchived) {
$this->isarchived = $isarchived;
return $this;
}
public function setArchivestatus($archivestatus) {
$this->archivestatus = $archivestatus;
return $this;
}
}
Found this not sure if it will help though (http://tocacar.com/2013/01/25/doctrine2-object-introspection/)
To get an array of metadata:
$cmf = $em->getMetadataFactory();
$metadata = $cmf->getMetadataFor(\AppBundle\Entity\Inventory::class);
//Doctrine\ORM\Mapping\ClassMetadata instance
//as array:
$metadata = (array) $metadata;
To get the inversed information:
$metadata->getAssociationMapping('companyId')['inversedBy'];
//as array
$metadata['associationMappings']['companyId']['inversedBy'];
You can find more info on the docs.
I am having troubles with user authorization.
This is my User
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
* #var int id
*/
protected $id;
/**
* #ORM\Column(type="string", length=25)
*
* #var string username
*/
protected $username;
/**
* #ORM\Column(type="string", length=25)
*
* #var string password
*/
protected $password;
/**
* #ORM\Column(type="string", length=25)
*
* #var string firstName
*/
protected $firstName;
/**
* #ORM\Column(type="string", length=25)
*
* #var string lastName
*/
protected $lastName;
/**
* #ORM\Column(type="string", length=25)
*
* #var string email
*/
protected $email;
/**
* #ORM\Column(type="string", length=255)
*
* #var string salt
*/
protected $salt;
/**
* #ORM\ManyToMany(targetEntity="Role")
* #ORM\JoinTable(name="user_role",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*
* #var ArrayCollection $userRoles
*/
protected $userRoles;
public function __construct()
{
$this->posts = new ArrayCollection();
$this->userRoles = new ArrayCollection();
$this->createdAt = new \DateTime();
}
public function getId()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function getPassword()
{
return $this->password;
}
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
public function getEmail()
{
return $this->email;
}
public function getSalt()
{
return $this->salt;
}
public function getUserRoles()
{
return $this->userRoles;
}
public function getRoles()
{
return $this->getUserRoles()->toArray();
}
public function setUsername($username)
{
$this->username = $username;
}
public function setPassword($password)
{
$this->password = $password;
}
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
public function setEmail($email)
{
$this->email = $email;
}
public function setSalt($value)
{
$this->salt = $value;
}
public function eraseCredentials()
{
}
public function equals(UserInterface $user)
{
return md5($this->getUsername()) == md5($user->getUsername());
}
}
And this is my Role
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="role")
*/
class Role implements RoleInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
* #var integer $id
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #var string $name
*/
protected $name;
/**
* #ORM\Column(type="datetime", name="created_at")
*
* #var DateTime $createdAt
*/
protected $createdAt;
/**
* Геттер для id.
*
* #return integer The id.
*/
public function getId()
{
return $this->id;
}
/**
* Геттер для названия роли.
*
* #return string The name.
*/
public function getName()
{
return $this->name;
}
/**
* Сеттер для названия роли.
*
* #param string $value The name.
*/
public function setName($value)
{
$this->name = $value;
}
/**
* Геттер для даты создания роли.
*
* #return DateTime A DateTime object.
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Конструктор класса
*/
public function __construct()
{
$this->createdAt = new \DateTime();
}
/**
* Реализация метода, требуемого интерфейсом RoleInterface.
*
* #return string The role.
*/
public function getRole()
{
return $this->getName();
}
}
RoleHierarchy.php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Role;
/**
* RoleHierarchy defines a role hierarchy.
*
* #author Fabien Potencier <fabien#symfony.com>
*/
class RoleHierarchy implements RoleHierarchyInterface
{
private $hierarchy;
protected $map;
/**
* Constructor.
*
* #param array $hierarchy An array defining the hierarchy
*/
public function __construct(array $hierarchy)
{
$this->hierarchy = $hierarchy;
$this->buildRoleMap();
}
/**
* {#inheritdoc}
*/
public function getReachableRoles(array $roles)
{
$reachableRoles = $roles;
foreach ($roles as $role) {
if (!isset($this->map[$role->getRole()])) {
continue;
}
foreach ($this->map[$role->getRole()] as $r) {
$reachableRoles[] = new Role($r);
}
}
return $reachableRoles;
}
protected function buildRoleMap()
{
$this->map = array();
foreach ($this->hierarchy as $main => $roles) {
$this->map[$main] = $roles;
$visited = array();
$additionalRoles = $roles;
while ($role = array_shift($additionalRoles)) {
if (!isset($this->hierarchy[$role])) {
continue;
}
$visited[] = $role;
$this->map[$main] = array_unique(array_merge($this->map[$main], $this->hierarchy[$role]));
$additionalRoles = array_merge($additionalRoles, array_diff($this->hierarchy[$role], $visited));
}
}
}
}
I am getting next error - FatalErrorException in RoleHierarchy.php line 43: Error: Call to a member function getRole() on string
How should i solve the problem?
I have a one-to-many self referencing entity. Everything works fine as long as the parent value is set to null. When I set the parent item to something actually in the list, I get the error:
Class integer does not exist
500 Internal Server Error - ReflectionException
Here is the code for my entity:
<?php
namespace WorkRecorder\WorkBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="WorkRecorder\WorkBundle\Repository\WorkRepository")
* #ORM\Table(name="strategyUsed")
*/
class StrategyUsed
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="integer")
*/
protected $sortOrder;
/**
* #ORM\Column(type="string", length=50)
*/
protected $name;
/**
* #ORM\Column(type="text")
*/
protected $description;
/**
* #ORM\OneToMany(targetEntity="StrategyUsed", mappedBy="parent")
*/
private $children;
/**
* #ORM\ManyToOne(targetEntity="StrategyUsed", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
public function __construct() {
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return text
*/
public function getDescription()
{
return $this->description;
}
/**
* Set sortOrder
*
* #param integer $sortOrder
*/
public function setSortOrder(\integer $sortOrder)
{
$this->sortOrder = $sortOrder;
}
/**
* Get sortOrder
*
* #return integer
*/
public function getSortOrder()
{
return $this->sortOrder;
}
/**
* Add children
*
* #param WorkRecorder\WorkBundle\Entity\StrategyUsed $children
*/
public function addStrategyUsed(\WorkRecorder\WorkBundle\Entity\StrategyUsed $children)
{
$this->children[] = $children;
}
/**
* Get children
*
* #return Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Set parent
*
* #param WorkRecorder\WorkBundle\Entity\StrategyUsed $parent
*/
public function setParent(\WorkRecorder\WorkBundle\Entity\StrategyUsed $parent)
{
$this->parent = $parent;
}
/**
* Get parent
*
* #return WorkRecorder\WorkBundle\Entity\StrategyUsed
*/
public function getParent()
{
return $this->parent;
}
}
What am I doing wrong?
You can't type hint on a scalar type (integer/string/boolean etc) in PHP. e.g.
public function setSortOrder(\integer $sortOrder)
Should be:
public function setSortOrder($sortOrder)
You can validate the type of the value within the method and perhaps throw an InvalidArgumentException if passed something that isn't an integer.