And Sorry I'm French :)
For my diploma I have to make a Tickets/Reports app and I'm stuck at the Doctrine mapping.
Clone project on GitHUB
Here is my 'Transaction.php' class:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\TransactionRepository")
*/
class Transaction
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
************************** PROBLEM STARTS HERE *************************
/**
* #ORM\OneToOne(targetEntity="User")
*/
private $sender;
/**
* #ORM\OneToOne(targetEntity="User")
*/
private $receiver;
************************** PROBLEM ENDS HERE *************************
/**
* #ORM\Column(type="integer")
*/
private $amount;
/**
* #ORM\Column(type="datetime",nullable=true)
*/
private $date;
/**
* #ORM\Column(type="text")
*/
private $comment;
/**
* #return mixed
*/
public function getComment()
{
return $this->comment;
}
/**
* #param mixed $comment
*/
public function setComment($comment): void
{
$this->comment = $comment;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getSender()
{
return $this->sender;
}
/**
* #param mixed $sender
*/
public function setSender($sender): void
{
$this->sender = $sender;
}
/**
* #return mixed
*/
public function getReceiver()
{
return $this->receiver;
}
/**
* #param mixed $receiver
*/
public function setReceiver($receiver): void
{
$this->receiver = $receiver;
}
/**
* #return mixed
*/
public function getAmount()
{
return $this->amount;
}
/**
* #param mixed $amount
*/
public function setAmount($amount): void
{
$this->amount = $amount;
}
/**
* #return mixed
*/
public function getDate()
{
return $this->date;
}
/**
* #param mixed
*/
public function setDate()
{
$this->date = new \DateTime("now");
}
}
And my 'User.php' class
<?php
// src/Entity/User.php
namespace App\Entity;
use App\Repository\TransactionRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #UniqueEntity(fields="email", message="Email already taken")
* #UniqueEntity(fields="username", message="Username 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()
* #Assert\Email()
*/
private $email;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank()
*/
private $username;
/**
* #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;
/**
* #var Monycks
*/
private $monycks = 10000;
/**
* #var Skill
* #ORM\ManyToOne(targetEntity="Skill",inversedBy="users")
*/
private $skill;
/**
* #return Skill
*/
public function getSkill()
{
return $this->skill;
}
/**
* #param mixed $skill
*/
public function setSkill(Skill $skill): void
{
$this->skill = $skill;
$skill->addUser($this);
}
/**
* #return Monycks
*/
public function getMonycks()
{
return $this->monycks;
}
/**
* #param Monycks $monycks
*/
public function setMonycks($monycks): void
{
$this->monycks = $monycks;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
// other properties and methods
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
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;
}
public function getRoles()
{
if($this->getUsername()=='admin')
return array('ROLE_ADMIN', 'ROLE_USER');
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
public function isSender()
{
return $this->getId();
}
public function isReceiver()
{
return $this->getId();
}
}
My problem is that Users can have multiple Transactions as sender or receiver an Transaction have at least 2 user (Send & receive)
With this config, I can add one transaction for each user....
I still do not manage very well Doctrine relation yet...
So somedy can EXPLAIN me how to do the tricks and how it works....
Clone project on GitHUB
I finaly found a workinf solution but I don't now if it's the right way to do
it...
I make a contrustor with two ArrayCollection(); in my User.php class and I put users_id into.
And in my Transaction.php class #ORM\JoinColumn
In my 'Transaction.php' class I put:
Everything is working now, but I don't really understand what's appened...
Someone can explain me correctly what was the problem .??
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="senders")
* #ORM\JoinColumn(nullable=true)
*/
private $sender;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="receivers")
* #ORM\JoinColumn(nullable=true)
*/
private $receiver;
public function getSender()
{
return $this->sender;
}
public function setSender(User $user)
{
$this->sender = $user;
}
public function getReceiver()
{
return $this->receiver;
}
public function setReceiver(User $user)
{
$this->receiver = $user;
}
And in my 'User.php' class:
/**
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="receiver")
*/
private $receivers;
/**
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="receiver")
*/
private $receivers;
/**
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="sender")
*/
private $senders;
public function __construct()
{
$this->senders = new ArrayCollection();
$this->receivers = new ArrayCollection();
}
/**
* #return Collection|Transaction[]
*/
public function getReceivers()
{
return $this->receivers;
}
/**
* #return Collection|Transaction[]
*/
public function getSenders()
{
return $this->senders;
}
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 trying to encode the password in symfony3 but i'm facing some problems.
this is the error i got.
Catchable Fatal Error: Argument 3 passed to GMAOBundle\Security\LoginFormAuthentificator::__construct() must be an instance of Symfony\Component\Security\Core\Encoder\UserPasswordEncoder, none given, called in C:\xampp\htdocs\ProjetSomadiag\var\cache\dev\appDevDebugProjectContainer.php on line 483 and defined
I'm working with guard in the authentification.
this is the authentification class name loginformauthentificator.
namespace GMAOBundle\Security;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
class LoginFormAuthentificator extends AbstractGuardAuthenticator
{
private $em;
private $router;
private $passwordEncoder;
public function __construct($em, $router,UserPasswordEncoder $PasswordEncoder )
{
$this->em = $em;
$this->router = $router;
//$this->passwordEncoder = new UserPasswordEncoder();
$this->passwordEncoder = $PasswordEncoder;
}
public function getCredentials(Request $request)
{
if ($request->getPathInfo() != '/login' || !$request->isMethod('POST')) {
return;
}
$request->getSession()->set(Security::LAST_USERNAME,$request->request->get('_username'));
return [
'username' => $request->request->get('_username'),
'password' => $request->request->get('_password'),
];
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['username'];
return $this->em->getRepository('GMAOBundle:Employe')
->findOneBy(['EmailEmploye' => $username]);
}
/**
* #param mixed $credentials
* #param UserInterface $user
* #return bool
*/
public function checkCredentials($credentials, UserInterface $user)
{
$password=$credentials['password'];
if ($this->passwordEncoder->isPasswordValid($user, $password)) {
return true;
}
return false;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
$url = $this->router->generate('login');
return new RedirectResponse($url);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$url = $this->router->generate('gmao_homepage');
return new RedirectResponse($url);
}
public function supportsRememberMe()
{
return true;
}
public function start(Request $request, AuthenticationException $authException = null)
{
$url = $this->router->generate('login');
return new RedirectResponse($url);
}
}
and this is the user class.
namespace GMAOBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity
* #ORM\Table(name="employe")
*/
class Employe implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/private $idEmploye;
/**
* #ORM\Column(type="string")
*/private $NomEmploye;
/**
* #ORM\Column(type="string")
*/private $PrenomEmploye;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateNaissanceEmploye;
/**
* #ORM\Column(type="string")
*/private $cinEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $AdresseEmploye;
/**
* #ORM\Column(type="string")
*/private $MatriculeEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $SituationFamiliale;
/**
* #ORM\Column(type="string", nullable=true)
*/private $SexeEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $CnssEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $FonctionEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroMutuelle;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateDebutEmploye;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateTitularisationEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroTelEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroLigneEmploye;
/**
* #ORM\Column(type="string")
*/private $EmailEmploye;
/**
* A non-persisted field that's used to create the encoded password.
* #var string
*/private $plainPassword;
/**
* #ORM\Column(type="string")
*/private $MdpEmploye;
/**
* #ORM\Column(type="string")
*/private $active;
/**
* #ORM\Column(type="json_array")
*/private $roles = [];
/**
* #ORM\ManyToOne(targetEntity="Departement")
* #ORM\JoinColumn(name="Departement",
referencedColumnName="id_departement")
*/private $Departement;
/**
* #ORM\ManyToOne(targetEntity="Equipe", cascade={"persist"})
* #ORM\JoinColumn(name="Equipe", referencedColumnName="id" ,nullable=true)
*/private $equipe;
/**
* #ORM\Column(type="string", nullable=true)
*/private $imgsrc;
/**
* #ORM\Column(type="string")
*private $responsable_projet;
/**
* #ORM\Column(type="string")
*private $m_GMAO_Projet;
/**
* #ORM\Column(type="string")
*public $m_PMP_Objectif;
/**
* #ORM\Column(type="string")
*public $m_Services;*/
/**
* User Interface Methode Override
*/
function __construct()
{
}
function __destruct()
{
}
public function getUsername()
{
return $this->EmailEmploye;
}
public function getRoles()
{
$roles = $this->roles;
if(!in_array('ROLE_USER',$roles))
{
$roles[]='ROLE_USER';
}
return $roles;
}
public function getPassword()
{
return$this->MdpEmploye;
}
public function getSalt()
{
}
public function eraseCredentials()
{
$this->plainPassword = null;
}
/**
* GETTERS AND SETTERS
**/
/**
* #return mixed
*/
public function getIdEmploye()
{
return $this->idEmploye;
}
/**
* #param mixed $idEmploye
*/
public function setIdEmploye($idEmploye)
{
$this->idEmploye = $idEmploye;
}
/**
* #return mixed
*/
public function getNomEmploye()
{
return $this->NomEmploye;
}
/**
* #param mixed $NomEmploye
*/
public function setNomEmploye($NomEmploye)
{
$this->NomEmploye = $NomEmploye;
}
/**
* #return mixed
*/
public function getPrenomEmploye()
{
return $this->PrenomEmploye;
}
/**
* #param mixed $PrenomEmploye
*/
public function setPrenomEmploye($PrenomEmploye)
{
$this->PrenomEmploye = $PrenomEmploye;
}
/**
* #return mixed
*/
public function getDateNaissanceEmploye()
{
return $this->DateNaissanceEmploye;
}
/**
* #param mixed $DateNaissanceEmploye
*/
public function setDateNaissanceEmploye($DateNaissanceEmploye)
{
$this->DateNaissanceEmploye = $DateNaissanceEmploye;
}
/**
* #return mixed
*/
public function getcinEmploye()
{
return $this->cinEmploye;
}
/**
* #param mixed $cinemploye
*/
public function setcinEmploye($Cinemploye)
{
$this->cinEmploye = $Cinemploye;
}
/**
* #return mixed
*/
public function getAdresseEmploye()
{
return $this->AdresseEmploye;
}
/**
* #param mixed $AdresseEmploye
*/
public function setAdresseEmploye($AdresseEmploye)
{
$this->AdresseEmploye = $AdresseEmploye;
}
/**
* #return mixed
*/
public function getMatriculeEmploye()
{
return $this->MatriculeEmploye;
}
/**
* #param mixed $MatriculeEmploye
*/
public function setMatriculeEmploye($MatriculeEmploye)
{
$this->MatriculeEmploye = $MatriculeEmploye;
}
/**
* #return mixed
*/
public function getSituationFamiliale()
{
return $this->SituationFamiliale;
}
/**
* #param mixed $SituationFamiliale
*/
public function setSituationFamiliale($SituationFamiliale)
{
$this->SituationFamiliale = $SituationFamiliale;
}
/**
* #return mixed
*/
public function getSexeEmploye()
{
return $this->SexeEmploye;
}
/**
* #param mixed $SexeEmploye
*/
public function setSexeEmploye($SexeEmploye)
{
$this->SexeEmploye = $SexeEmploye;
}
/**
* #return mixed
*/
public function getCnssEmploye()
{
return $this->CnssEmploye;
}
/**
* #param mixed $CnssEmploye
*/
public function setCnssEmploye($CnssEmploye)
{
$this->CnssEmploye = $CnssEmploye;
}
/**
* #return mixed
*/
public function getFonctionEmploye()
{
return $this->FonctionEmploye;
}
/**
* #param mixed $FonctionEmploye
*/
public function setFonctionEmploye($FonctionEmploye)
{
$this->FonctionEmploye = $FonctionEmploye;
}
/**
* #return mixed
*/
public function getNumeroMutuelle()
{
return $this->NumeroMutuelle;
}
/**
* #param mixed $NumeroMutuelle
*/
public function setNumeroMutuelle($NumeroMutuelle)
{
$this->NumeroMutuelle = $NumeroMutuelle;
}
/**
* #return mixed
*/
public function getDateDebutEmploye()
{
return $this->DateDebutEmploye;
}
/**
* #param mixed $DateDebutEmploye
*/
public function setDateDebutEmploye($DateDebutEmploye)
{
$this->DateDebutEmploye = $DateDebutEmploye;
}
/**
* #return mixed
*/
public function getDateTitularisationEmploye()
{
return $this->DateTitularisationEmploye;
}
/**
* #param mixed $DateTitularisationEmploye
*/
public function setDateTitularisationEmploye($DateTitularisationEmploye)
{
$this->DateTitularisationEmploye = $DateTitularisationEmploye;
}
/**
* #return mixed
*/
public function getNumeroTelEmploye()
{
return $this->NumeroTelEmploye;
}
/**
* #param mixed $NumeroTelTmploye
*/
public function setNumeroTelEmploye($NumeroTelEmploye)
{
$this->NumeroTelEmploye = $NumeroTelEmploye;
}
/**
* #return mixed
*/
public function getNumeroLigneEmploye()
{
return $this->NumeroLigneEmploye;
}
/**
* #param mixed $NumeroLigneEmploye
*/
public function setNumeroLigneEmploye($NumeroLigneEmploye)
{
$this->NumeroLigneEmploye = $NumeroLigneEmploye;
}
/**
* #return mixed
*/
public function getEmailEmploye()
{
return $this->EmailEmploye;
}
/**
* #param mixed $EmailEmploye
*/
public function setEmailEmploye($EmailEmploye)
{
$this->EmailEmploye = $EmailEmploye;
}
/**
* #return mixed
*/
public function getMdpEmploye()
{
return $this->MdpEmploye;
}
/**
* #param mixed $MdpEmploye
*/
public function setMdpEmploye($MdpEmploye)
{
$this->MdpEmploye = $MdpEmploye;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* #return mixed
*/
public function getDepartement()
{
return $this->Departement;
}
/**
* #param mixed $Departement
*/
public function setDepartement($Departement)
{
$this->Departement = $Departement;
}
/**
* #return mixed
*/
public function getImgsrc()
{
return $this->imgsrc;
}
/**
* #param mixed $imgsrc
*/
public function setImgsrc($imgsrc)
{
$this->imgsrc = $imgsrc;
}
public function setRoles($roles)
{
$this->roles =$roles;
}
/**
* #return mixed
*/
public function getEquipe()
{
return $this->equipe;
}
/**
* #param mixed $Equipe
*/
public function setEquipe($Equipe)
{
$this->equipe = $Equipe;
}
/**
* #return string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* #param string $plainPassword
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
$this->password = null;
}
}
i don't know what this error stand for.
If you are using dependency injection, you must send your password encoder in as your third argument.
Example:
services.yml
services:
app.loginform.authenticator:
class: GMAOBundle\Security\LoginFormAuthentificator
arguments:
- "#doctrine.orm.entity_manager"
- "#router"
- "#passwordencoder"
Alternatively you can "autowire".
services:
app.loginform.authenticator:
class: GMAOBundle\Security\LoginFormAuthentificator
autowire: true
Or however you're using your services.yml to inject dependencies.
If you're creating the loginFormAuthenticator as an object you have to instantiate it as:
$loginAuthenticator = new LoginFormAuthentificator($entitymanager, $router, $passwordEncoder);
You're missing the password encoder in some argument when you call the class.
I have three database tables. user, meeting, group. The meetings and group table are manytomany associations from the user table. So I can do user->getmeetings(), or user->getgroups().
I want to get just the next meeting comping up for the user, and I don't know how to achieve this. Whether by SQL Query or simply in the controller. Here is what I have done so far.
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
I have added a time_diff field in the new array to calculate the time from now to the meeting time. All I need to do now is select the smallest one.How can I do this? Thank you.
UPDATE - Below is my User Repository
namespace AppBundle\Repository;
use AppBundle\Entity\User;
use AppBundle\Entity\Meeting;
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\Criteria;
class UserRepository extends EntityRepository
{
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
$this->getMeetings()->matching($criteria);
}
}
Below is my User Entity
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #ORM\Table(name="user")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $first_name;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $last_name;
/**
* #ORM\Column(type="string", nullable=false, unique=true)
*/
private $email_address;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $phone_number;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $password;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_login;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $reset_password;
/**
* #ORM\ManyToMany(targetEntity="Meeting", inversedBy="users")
*/
private $meetings;
/**
* #ORM\ManyToMany(targetEntity="Group", inversedBy="users")
*/
private $groups;
public function __construct()
{
$this->groups = new arrayCollection();
$this->meetings = new arrayCollection();
}
/**
* #return mixed
*/
public function getFirstName()
{
return $this->first_name;
}
/**
* #param mixed $first_name
*/
public function setFirstName($first_name)
{
$this->first_name = $first_name;
}
/**
* #return mixed
*/
public function getLastName()
{
return $this->last_name;
}
/**
* #param mixed $last_name
*/
public function setLastName($last_name)
{
$this->last_name = $last_name;
}
/**
* #return mixed
*/
public function getEmailAddress()
{
return $this->email_address;
}
/**
* #param mixed $email_address
*/
public function setEmailAddress($email_address)
{
$this->email_address = $email_address;
}
/**
* #return mixed
*/
public function getPhoneNumber()
{
return $this->phone_number;
}
/**
* #param mixed $phone_number
*/
public function setPhoneNumber($phone_number)
{
$this->phone_number = $phone_number;
}
/**
* #return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* #param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return mixed
*/
public function getLastLogin()
{
return $this->last_login;
}
/**
* #param mixed $last_login
*/
public function setLastLogin($last_login)
{
$this->last_login = $last_login;
}
/**
* #return mixed
*/
public function getResetPassword()
{
return $this->reset_password;
}
/**
* #param mixed $reset_password
*/
public function setResetPassword($reset_password)
{
$this->reset_password = $reset_password;
}
/**
* #return arrayCollection|Meeting[]
*/
public function getMeetings()
{
return $this->meetings;
}
/**
* #return ArrayCollection|Group[]
*/
public function getGroups()
{
return $this->groups;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
}
below is my HomeControlller.php
class HomeController extends Controller
{
/**
* #Route("/home", name="home_show")
*/
public function showAction()
{
$em = $this->getDoctrine()->getManager();
//logged in user
$id = 1;
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
$groups = $em->getRepository('AppBundle\Entity\Group')
->findAll();
return $this->render('home/show.html.twig', [
'loggedInUser' => $loggedInUser,
'groups' => $groups,
]);
}
}
You can add a method in your UserEntity with a matching criteria on meeting collection
namespace AppBundle\Entity;
use Doctrine\Common\Collections\Criteria;
....
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
return $this->getMeetings()->matching($criteria);
}
see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/working-with-associations.html
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 am getting above error when login. With property option in security.yml it is working. I have added the #ORM\Entity(repositoryClass="versionR\userBundle\Entity\UserRepository") line on my entity class, dobule checked path, cleared cache but no luck.
User entity class
<?php
namespace versionR\userBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
//use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="versionR\userBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=40, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, nullable=false)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255, nullable=false)
*/
private $address;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="versionR\userBundle\Entity\Role", inversedBy="user")
* #ORM\JoinTable(name="user_role",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*/
private $role;
/**
* Constructor
*/
public function __construct()
{
$this->role = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #param string $address
*/
public function setAddress($address)
{
$this->address = $address;
}
/**
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* #param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param string $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* #param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* #param \Doctrine\Common\Collections\Collection $role
*/
public function setRole($role)
{
$this->role->add($role);
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getRole()
{
return $this->role;
}
/**
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* Returns the roles granted to the user.
*/
public function getRoles()
{
return $this->role->toArray();
}
/**
*/
public function getSalt()
{
return null;
}
/**
*/
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}
User repository class
<?php
namespace versionR\userBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* UserRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class UserRepository extends EntityRepository implements UserProviderInterface
{
/**
* #param string $username
* #return \versionR\userBundle\Entity\User
*/
public function loadUserByUsername($username)
{
return $this->findOneBy(array('username' => $username));
}
public function refreshUser(UserInterface $user)
{
$class = get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException(
sprintf(
'Instances of "%s" are not supported.',
$class
)
);
}
return $this->find($user->getId());
}
public function supportsClass($class)
{
return $this->getEntityName() === $class
|| is_subclass_of($class, $this->getEntityName());
}
}
Both classes are in Entity directory. Any suggestions to solve this problem. I am using symfony 2.5.2