I have the following model, or as you call them entity, and I also have a controller, everything works in this action, but when I check the database there is no user. So I am curious as what I am missing. So lets start at the beginning as to what I have:
bootstrap.php contains the following code, among other things.
...
/** ---------------------------------------------------------------- **/
// Lets Setup Doctrine.
/** ---------------------------------------------------------------- **/
require_once 'vendor/autoload.php';
$loader = require 'vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
/**
* Set up Doctrine.
*/
class DoctrineSetup {
/**
* #var array $paths - where the entities live.
*/
protected $paths = array(APP_MODELS);
/**
* #var bool $isDevMode - Are we considered "in development."
*/
protected $isDevMode = false;
/**
* #var array $dbParams - The database paramters.
*/
protected $dbParams = null;
/**
* Constructor to set some core values.
*/
public function __construct(){
if (!file_exists('db_config.ini')) {
throw new \Exception(
'Missing db_config.ini. You can create this from the db_config_sample.ini'
);
}
$this->dbParams = array(
'driver' => 'pdo_mysql',
'user' => parse_ini_file('db_config.ini')['DB_USER'],
'password' => parse_ini_file('db_config.ini')['DB_PASSWORD'],
'dbname' => parse_ini_file('db_config.ini')['DB_NAME']
);
}
/**
* Get the entity manager for use through out the app.
*
* #return EntityManager
*/
public function getEntityManager() {
$config = Setup::createAnnotationMetadataConfiguration($this->paths, $this->isDevMode, null, null, false);
return EntityManager::create($this->dbParams, $config);
}
}
/**
* Function that can be called through out the app.
*
* #return EntityManager
*/
function getEntityManager() {
$ds = new DoctrineSetup();
return $ds->getEntityManager();
}
/**
* Function that returns the conection to the database.
*/
function getConnection() {
$ds = new DoctrineSetup();
return $ds->getEntityManager()->getConnection();
}
...
So now that we have doctrine set up its time to create a model (entity) and set which fields can and cannot be blank and so on and so forth.
Note At this point, you should know that I am not using Symfony other then its components on top of Doctrine. I am using Slim Framework. So if any suggestion is to use x or y from symfony, please make sure its a component.
Models/User.php
<?php
namespace ImageUploader\Models;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="users", uniqueConstraints={
* #ORM\UniqueConstraint(name="user", columns={"userName", "email"})}
* )
*/
class User {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(type="string", length=32, nullable=false)
* #Assert\NotBlank()
*/
protected $firstName;
/**
* #ORM\Column(type="string", length=32, nullable=false)
* #Assert\NotBlank()
*/
protected $lastName;
/**
* #ORM\Column(type="string", length=100, unique=true, nullable=false)
* #Assert\NotBlank(
* message = "Username cannot be blank"
* )
*/
protected $userName;
/**
* #ORM\Column(type="string", length=100, unique=true, nullable=false)
* #Assert\NotBlank(
* message = "Email field cannot be blank."
* )
* #Assert\Email(
* message = "The email you entered is invalid.",
* checkMX = true
* )
*/
protected $email;
/**
* #ORM\Column(type="string", length=500, nullable=false)
* #Assert\NotBlank(
* message = "The password field cannot be empty."
* )
*/
protected $password;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $created_at;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $updated_at;
/**
* Get the value of Created At
*
* #return mixed
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set the value of Created At
*
* #param mixed created_at
*
* #return self
*/
public function setCreatedAt(\DateTime $created_at = null)
{
$this->created_at = $created_at;
return $this;
}
/**
* Get the value of Updated At
*
* #return mixed
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set the value of Updated At
*
* #param mixed updated_at
*
* #return self
*/
public function setUpdatedAt(\DateTime $updated_at = null)
{
$this->updated_at = $updated_at;
return $this;
}
/**
* Get the value of First Name
*
* #return mixed
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set the value of First Name
*
* #param mixed firstName
*
* #return self
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get the value of Last Name
*
* #return mixed
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set the value of Last Name
*
* #param mixed lastName
*
* #return self
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get the value of User Name
*
* #return mixed
*/
public function getUserName()
{
return $this->userName;
}
/**
* Set the value of User Name
*
* #param mixed userName
*
* #return self
*/
public function setUserName($userName)
{
$this->userName = $userName;
return $this;
}
/**
* Get the value of Email
*
* #return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* Set the value of Email
*
* #param mixed email
*
* #return self
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Set ths password.
*
* #param string password
*
* #return self
*/
public function setPassword($password) {
$this->password = password_hash($password, PASSWORD_DEFAULT);
return $this;
}
/**
* Check the users password against that which is enterd.
*
* #param string password
*
* #return bool
*/
public function checkPassword($password) {
if (password_hash($password, PASSWORD_DEFAULT) === $this->getPassword()) {
return true;
}
return false;
}
/**
* Return the password value.
*
* #return hash
*/
private function getPassword(){
return $this->password;
}
/**
* #ORM\PrePersist
*/
public function setCreatedAtTimeStamp() {
if (is_null($this->getCreatedAt())) {
$this->setCreatedAt(new \DateTime());
}
}
/**
* #ORM\PreUpdate
*/
public function setUpdatedAtTimeStamp() {
if (is_null($this->getUpdatedAt())) {
$this->setUpdatedAt(new \DateTime());
}
}
}
The above model is correct, as far as I know, I mean when I run "vendor/bin/doctrine migrations:migrate" a database table is created.
Now, where is all this used? it's used in a controller called SignupController under an action called createAction($params)
**createAction($params)**
public static function createAction($params){
$postParams = $params->request()->post();
$flash = new Flash();
if ($postParams['password'] !== $postParams['repassword']) {
$flash->createFlash('error', 'Your passwords do not match.');
self::$createEncryptedPostParams($postParams);
$params->redirect('/signup/error');
}
$user = new User();
$user->setFirstName($postParams['firstname'])
->setLastName($postParams['lastname'])
->setUserName($postParams['username'])
->setEmail($postParams['email'])
->setPassword($postParams['password'])
->setCreatedAtTimeStamp();
$validator = Validator::createValidatorBuilder();
$validator->enableAnnotationMapping();
$errors = $validator->getValidator()->validate($user);
if (count($errors) > 0) {
foreach($errors as $error) {
$flash->createFlash(
$error->getPropertyPath() . 'error',
$error->getMessage()
);
}
self::createEncryptedPostParams($postParams);
$params->redirect('/signup/error');
}
$anyEncryptedErors = self::getEncryptedPostParams();
if ($anyEncryptedErors !== null) {
$anyEncryptedErors->destroy('error');
}
getEntityManager()->flush();
getEntityManager()->persist($user);
$flash->createFlash('success', ' You have signed up successfully! Please sign in!');
$params->redirect('/signin');
}
Now should you enter everything in correctly I show a flash of success and redirect you. THIS WORKS it redirects, it shows a flash message. But its the:
getEntityManager()->flush();
getEntityManager()->persist($user);
That I don't think is working. Why? Because doing a select * from users on the database in question comes back with no records.
Why?
Flush statement should be execute after persist. So Code should be:
getEntityManager()->persist($user);
getEntityManager()->flush();
I had a similar issue and thought I would post it here. I was creating an entity and everything was responding correctly, but when I checked the database no record had been created.
Just wrapped the flush in a try-catch and logged the error.
$this->em->persist($insectLifeCycle);
try {
$this->em->flush();
} catch (\Exception $error) {
$this->logger->debug($error);
}
It turns out that one of properties was exceeding its character limit and the database was throwing an error. Also found out I need to improve my error handling....
As Samiul Amin Shanto said:
getEntityManager()->persist($user);
getEntityManager()->flush();
will be correct way, because persist action prepare the data to be stored in DB and flush "Flushes all changes to now to the database."
If you have the object id and then, the database is not showing it, you might have a "START TRANSACTION" and then you have your insert, after this insert you will have a "COMMIT". If any error appears between your persist and the COMMIT, object won't be stored in your database.
Check your Symfony request profiler information.
You can find it using the developer tool and checking your response for it.
Related
I am retrieving the code of an old application that have not been updated for a few years now. Our sysadmin have put the code in a php7 server (it was working correctly on a php5 previously). The code worked quite good. I wanted to make some updates and the first one I did was to upgrade symfony from 2.3 to 2.7.*. And of course, now the problems arise.
I have a form that is correctly rendered (all the fields are OK even the ones from the database). Here is my builer:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('object','text',array(
"required"=>false,
"attr"=>array(
"placeholder"=>"Object"
)
))
->add('date','date',array(
'widget'=>'single_text',
))
->add('contact', 'entity', array(
'label'=>'Contact',
'class'=>'MyApp\AppliBundle\Entity\Contact',
'choice_translation_domain' => true,
'placeholder'=>'initials',
'choice_label' => 'initials',
'multiple'=>true
))
->add('text','redactor',array(
"required"=>false,
"redactor"=>"default"
))
;
}
Here is my controller:
public function editMeetingAction($id,Request $request)
{
$em = $this->getDoctrine()->getManager();
$meeting = $em->getRepository('MyAPPAppliBundle:Meeting')-
>findOneById($id);
$form = $this->createForm(new MeetingType, $meeting);
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($meeting);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Meeting
edited successfully');
return $this->redirect($this-
>generateUrl('myapp_appli_manage_editmeeting', array("id" => $id)));
}
return array(
"form" => $form->createView(),
"id" => $id,
);
}
Now when I try to save the form, I have the following error:
[Syntax Error] line 0, col -1: Error: Expected Literal, got end of string.
[1/2] QueryException: SELECT e FROM MyApp\AppliBundle\Entity\Contact e WHERE
It seems that the app is not able to retrieve the Contact being selected in the form.
I have no idea what is wrong here as it worked correctly in the previous version. I followed the steps in this website to help me with the migration and modified already some fields in the form (placeholder, choices_as_values etc)
https://gist.github.com/mickaelandrieu/5211d0047e7a6fbff925
It would be much appreciated if you could help me.
[EDIT1]: the form was working properly before I updated symfony from 2.3 to 2.7
[EDIT2]: Entity Contact:
<?php
namespace MyApp\AppliBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\EntityRepository;
/**
* Contact
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyApp\AppliBundle\Entity\ContactRepository")
*/
class Contact
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="Name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="Email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="Initials", type="string", length=255)
*/
private $initials;
/**
* #var integer
*
* #ORM\Column(name="id_binome", type="integer")
*/
private $id_binome;
/**
* #var string
*
* #ORM\Column(name="JobTitles", type="string", length=255)
*/
private $jobtitle;
/**
* Tostring method
*
*/
public function __toString()
{
return $this->name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Contact
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set email
*
* #param string $email
* #return Contact
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set initials
*
* #param string $initials
* #return Contact
*/
public function setInitials($initials)
{
$this->initials = $initials;
return $this;
}
/**
* Get initials
*
* #return string
*/
public function getInitials()
{
return $this->initials;
}
/**
* Get id_binome
*
* #return integer
*/
public function getIdBinome()
{
return $this->id_binome;
}
/**
* Set id_binome
*
* #param integer $id
* #return Contact
*/
public function setIdBinome($id)
{
$this->id_binome = $id;
return $this;
}
/**
* Get jobtitle
*
* #return string
*/
public function getjobtitle()
{
return $this->jobtitle;
}
/**
* Set jobtitle
*
* #param string $jobtitle
* #return Contact
*/
public function setjobtitle($jobtitle)
{
$this->jobtitle = $jobtitle;
return $this;
}
}
class ContactRepository extends EntityRepository
{
public function findEmailBinome($id_binome)
{
$querybuilder = $this->createQueryBuilder("Contact")
->select("Contact.email")
->where("Contact.id = :idbinome")
->setParameter('idbinome',$id_binome)
;
return $querybuilder
->getQuery()
->getSingleResult()
;
}
}
[EDIT getter setter]
/**
* Add contacts
*
* #param \MyApp\AppliBundle\Entity\Contact $contacts
* #return Meeting
*/
public function addContact(\MyApp\AppliBundle\Entity\Contact $contacts)
{
$this->contacts[] = $contacts;
return $this;
}
/**
* Remove contacts
*
* #param \MyApp\AppliBundle\Entity\Contact $contacts
*/
public function removeContact(\MyApp\AppliBundle\Entity\Contact $contacts)
{
$this->contacts->removeElement($contacts);
}
/**
* Get contacts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getContacts()
{
return $this->contacts;
}
I think I found the solution. As it was a problem related to the db connection I suspected dotrine/orm to be guilty! I update the composer.json by changing :
"doctrine/orm": "=2.2.*"
to
"doctrine/orm": ">=2.2.3"
When I tried composer update doctrine/orm it did not solve the problem. However when I simply tried composer update then my app worked again.
Thanks a lot for your help
I would like to check if I am logged in when I login with a form, but I can't find my anwser and I don't understand the tutorial on symfony website... I try to follow this : http://symfony.com/doc/current/security.html , but I don't want to do with a "HTTP basic authentication", but with my symfony form.
Here is my user class :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Player
*
* #ORM\Table(name="player")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PlayerRepository")
*/
class Player implements UserInterface, \Serializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="pseudo", type="string", length=255, unique=true)
*/
private $pseudo;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
protected $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
protected $password;
/**
* #var \DateTime
*
* #ORM\Column(name="date_log", type="datetime", nullable=true)
*/
private $dateLog;
/**
* #ORM\OneToMany(targetEntity="Characters", mappedBy="player")
*/
private $characters;
public function __construct(){
$this->characters = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set pseudo
*
* #param string $pseudo
*
* #return Player
*/
public function setPseudo($pseudo)
{
$this->pseudo = $pseudo;
return $this;
}
/**
* Get pseudo
*
* #return string
*/
public function getPseudo()
{
return $this->pseudo;
}
/**
* Set email
*
* #param string $email
*
* #return Player
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
*
* #return Player
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set dateLog
*
* #param \DateTime $dateLog
*
* #return Player
*/
public function setDateLog($date_log)
{
$this->dateLog = $date_log;
return $this;
}
/**
* Get dateLog
*
* #return \DateTime
*/
public function getDateLog()
{
return $this->dateLog;
}
/**
* Set Characters
*
* #param array $characters
*
* #return Characters
*/
public function setCharacters($characters)
{
$this->characters = $characters;
return $this;
}
/**
* Get characters
*
* #return array
*/
public function getCharacters()
{
return $this->characters;
}
/**
* Add character
*
* #param \AppBundle\Entity\Characters $character
*
* #return Player
*/
public function addCharacter(\AppBundle\Entity\Characters $character)
{
$this->characters[] = $character;
return $this;
}
/**
* Remove character
*
* #param \AppBundle\Entity\Characters $character
*/
public function removeCharacter(\AppBundle\Entity\Characters $character)
{
$this->characters->removeElement($character);
}
public function getUsername()
{
return $this->pseudo;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->pseudo,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->pseudo,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
}
Then my login form (it work well, I am just not able to check if anybody is connected):
public function indexAction(Request $request)
{
$player = new Player;
$form = $this->createFormBuilder($player)
->add('email', TextType::class, array('label' => 'Email :'))
->add('password', PasswordType::class, array('label' => 'Mot de passe :'))
->add('login', SubmitType::class, array('label' => 'Login'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$password = $form['password']->getData();
$email = $form['email']->getData();
$encoded_pass = sha1($form['password']->getData());
$date = date_create();
$player = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findOneByEmail($email);
$pass_check = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findByPassword($encoded_pass);
if(!$player)
{
//return $this->redirectToRoute('registration');
}
else
{
$pseudo = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findOneByEmail($email)->getPseudo();
$player->setDateLog($date);
$em = $this->getDoctrine()->getManager();
$em->persist($player);
$em->flush(); // insère dans la BD
return $this->redirectToRoute('accueil', array('pseudo' => $pseudo));
}
}
return $this->render('Sko/menu.html.twig', array('form' => $form->createView()));
}
EDIT : I don't want to encode my password because I already do it (even if it is not 100% securised)
EDIT2 : Well I think I can't do that, when I saw the tutoriel, I saw that on their symfony toolbar, we can seethere is the role of the user instead of an anonymous user, but they didn't do this dynamically. Maybe I can't do it dynamically so I need to send user information each time I change page
EDIT3 : I will clarify my question : How to change the token class when I login?
You dont need to create your token, but encoder like described in this answer
After that you can log in programmatically with this code
$token = new UsernamePasswordToken($player, $player->getPassword(), "main");
$event = new InteractiveLoginEvent(new Request(), $token);
$this->container->get("event_dispatcher")->dispatch("security.interactive_login", $event);
$this->container->get("security.token_storage")->setToken($token);
Now you can use standard symfony security functionality to check if user logged in etc
I have created two bundle using two different vendor names. Two bundle names is-
SystemUsersBundle
Namespace= SystemUsersBundle\Namespace
AppBundle
Namespace= AppBundle\Namespace
Now, I have created two Entity inside two bundle. Entity name given below-
Comment.php – this entity created under AppBundle and it’s namespace
is AppBundle\Entity.
Users.php – this entity created under SystemUsersBundle and it’s
namespace is SystemUsersBundle\Entity.
My directory Structure is-
Now, I wanted to make a relationship between Users.php and Comment.php entity. For this purpose I make a relation between them according to the rule of Doctrine ManyToOne relationship.
Users.php and Comment.php file given below-
Users.php
<?php
namespace SystemUsersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Users
*
* #ORM\Table("users")
*/
class Users implements AdvancedUserInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #Gedmo\Slug(fields={"name"}, updatable=false)
* #ORM\Column(length=255, unique=true)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*/
private $plainpassword;
/**
* #var string
*/
private $resetPassword;
/**
* #var array
*
* #ORM\Column(name="roles", type="array")
*/
private $roles = array();
/**
* #var boolean
*
* #ORM\Column(name="app_status", type="boolean")
*/
private $appStatus;
/**
* #var boolean
*
* #ORM\Column(name="is_active",type="boolean")
*/
private $isActive;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
public function __construct()
{
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return Users
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set name
*
* #param string $name
* #return Users
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set email
*
* #param string $email
* #return Users
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set slug
*
* #param string $slug
* #return Users
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set password
*
* #param string $password
* #return Users
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set plainpassword for the application
*
* #param type $plainpassword
*/
function setPlainpassword($plainpassword)
{
$this->plainpassword = $plainpassword;
}
/**
* Get plainpassword for the application
*
* #return type
*/
function getPlainpassword()
{
return $this->plainpassword;
}
/**
* Set resetPassword for the application
*
* #param type $resetPassword
*/
function setResetPassword($resetPassword)
{
$this->resetPassword = $resetPassword;
}
/**
* Get plainpassword for the application
*
* #return type
*/
function getResetPassword()
{
return $this->resetPassword;
}
/**
* Set roles
*
* #param string $roles
* #return Users
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return string
*/
public function getRoles()
{
$roles = $this->roles;
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
/**
* set salt property of user
*
* #return type
*/
function getSalt()
{
return $this->salt;
}
/**
* Get salt value of user
*
* #param type $salt
*/
function setSalt($salt)
{
$this->salt = $salt;
}
/**
* Set appStatus
*
* #param boolean $appStatus
* #return Users
*/
public function setAppStatus($appStatus)
{
$this->appStatus = $appStatus;
return $this;
}
/**
* Get appStatus
*
* #return boolean
*/
public function getAppStatus()
{
return $this->appStatus;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Users
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Users
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Get Is active property
*
* #return type
*/
function getIsActive()
{
return $this->isActive;
}
/**
* Set Is active property
*
* #param \SystemUsersBundle\Entity\type $isActive
* #return $users
*/
function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* erase plain password credentials
*/
public function eraseCredentials()
{
$this->setPlainpassword(null);
}
/**
* Checks whether the user's account has expired.
*
* Internally, if this method returns false, the authentication system
* will throw an AccountExpiredException and prevent login.
*
* #return bool true if the user's account is non expired, false otherwise
*
* #see AccountExpiredException
*/
public function isAccountNonExpired()
{
return true;
}
/**
* Checks whether the user is locked.
*
* Internally, if this method returns false, the authentication system
* will throw a LockedException and prevent login.
*
* #return bool true if the user is not locked, false otherwise
*
* #see LockedException
*/
public function isAccountNonLocked()
{
return true;
}
/**
* Checks whether the user's credentials (password) has expired.
*
* Internally, if this method returns false, the authentication system
* will throw a CredentialsExpiredException and prevent login.
*
* #return bool true if the user's credentials are non expired, false otherwise
*
* #see CredentialsExpiredException
*/
public function isCredentialsNonExpired()
{
return true;
}
/**
* Checks whether the user is enabled.
*
* Internally, if this method returns false, the authentication system
* will throw a DisabledException and prevent login.
*
* #return bool true if the user is enabled, false otherwise
*
* #see DisabledException
*/
public function isEnabled()
{
return $this->getIsActive();
}
Comment.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SystemUsersBundle\Entity\Users;
/**
* Comment
*
* #ORM\Table("comment")
* #ORM\Entity
*/
class Comment
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var integer
*
* #ORM\Column(name="user_id", type="integer")
*/
private $userId;
/**
* #var boolean
*
* #ORM\Column(name="status", type="boolean")
*/
private $status;
/**
*
* #ORM\ManyToOne(targetEntity="Users")
*/
protected $owner;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Comment
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set userId
*
* #param integer $userId
* #return Comment
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->userId;
}
/**
* Set status
*
* #param boolean $status
* #return Comment
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status;
}
}
In comment.php file, make relationship using
/**
*
* #ORM\ManyToOne(targetEntity="Users")
*/
protected $owner;
it's give the following error-
But if I wanted make relationship with two entity under same Bundle(like SystemUsersBundle or AppBundle) it works perfectly ok. If you need more information let me know.
The provided syntax #ORM\ManyToOne(targetEntity="Users") means that given entity is at the same namespace as of the current file. Which is not the case. Your mapping should be like this:
#ORM\ManyToOne(targetEntity="SystemUsersBundle\Entity\Users")
When entities are in different namespace, you should always provide the full path.
If you need to set a relation between your two entities just make it all in one bundle, why you use two bundle if they depends on each other.
take a look at this :
A bundle is meant to be something that can be reused as a stand-alone piece of software. If UserBundle cannot be used "as is" in other Symfony apps, then it shouldn't be its own bundle. Moreover, if InvoiceBundle depends on ProductBundle, then there's no advantage to having two separate bundles.
my nightmare of a day continues.....
after implimenting a successful solution in an earlier thread where I need to alter my inter-entity relationships I am now getting this error when I try to log a user into the app:
CRITICAL - Uncaught PHP Exception Symfony\Component\Debug\Exception\UndefinedMethodException: "Attempted to call method "getRole" on class "Closure"." at C:\Dropbox\xampp\htdocs\etrack3\src\Ampisoft\Bundle\etrackBundle\Entity\Users.php line 234
I changed from a manyToMany relationship, to a manyToOne/OneToMany between a Users/Roles entity.
Ive read that serialize could cause the issue but Ive taken it out and it didnt make any difference. The remnants of the serialize required methods are still in there so please ignore (unless they are the issue).
Please could someone tell me what Ive done wrong? Im wondering if its best to scrap all the database tables and start again!!!!
here is the entity class.
/**
* user
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="Ampisoft\Bundle\etrackBundle\Entity\UsersRepository")
*/
class Users implements UserInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=25, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=64)
*/
private $password;
/**
* #ORM\Column(name="firstname", type="string", length=25)
*/
private $firstname;
/**
* #ORM\Column(name="surname", type="string", length=25)
*/
private $lastname;
/**
* #var boolean
*
* #ORM\Column(name="isActive", type="boolean")
*/
private $isActive = 1;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
private $email;
/**
* #var \DateTime
*
* #ORM\Column(name="lastLogged", type="string")
*/
private $lastLogged = '-0001-11-30 00:00:00';
/**
* #var string;
*
* #ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* #ORM\ManyToOne(targetEntity="Roles", inversedBy="users")
*
*/
private $roles;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Id
*
* #return integer
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Set username
*
* #param string $username
* #return user
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return user
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* 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;
}
/**
* 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 lastLogged
*
* #param \DateTime $lastLogged
* #return user
*/
public function setLastLogged($lastLogged)
{
$this->lastLogged = $lastLogged;
return $this;
}
/**
* Get lastLogged
*
* #return \DateTime
*/
public function getLastLogged()
{
return $this->lastLogged;
}
public function __construct()
{
$this->roles = new ArrayCollection();
$this->isActive = true;
}
/**
* #inheritDoc
*/
public function getRoles()
{
$roles = array();
foreach ($this->roles as $role) {
$roles[] = $role->getRole();
}
return $roles;
}
/**
* #param $roles
* #return $this
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
/**
* #inheritDoc
*/
public function getSalt()
{
return $this->salt;
}
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
/**
* Add roles
*
* #param \Ampisoft\Bundle\etrackBundle\Entity\Roles $roles
* #return users
*/
public function addRoles(Roles $roles)
{
$this->roles[] = $roles;
return $this;
}
/**
* Remove roles
*
* #param \Ampisoft\Bundle\etrackBundle\Entity\Roles $roles
*/
public function removeRoles(Roles $roles)
{
$this->roles->removeElement($roles);
}
/**
* Set firstname
*
* #param string $firstname
* #return users
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
* #return users
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* #see \Serializable::serialize()
*/
/**
* Serializes the content of the current User object
* #return string
*/
public function serialize()
{
return \json_encode(
array($this->username, $this->password, $this->salt,
$this->roles, $this->id));
}
/**
* Unserializes the given string in the current User object
* #param serialized
*/
public function unserialize($serialized)
{
list($this->username, $this->password, $this->salt,
$this->roles, $this->id) = \json_decode(
$serialized);
}
}
update 1
this has worked but produced a new error Im going to move it to a new question when the post timer lets me.
Catchable Fatal Error: Argument 4 passed to Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::__construct() must be of the type array, object given, called in C:\Dropbox\xampp\htdocs\etrack3\vendor\symfony\symfony\src\Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider.php on line 96 and defined
HI I think what you want is not this
public function getRoles()
{
$roles = array();
foreach ($this->roles as $role) {
$roles[] = $role->getRole();
}
return $roles;
}
but this
public function getRoles()
{
return $this->roles;
}
Roles should be an ArrayCollection already, so calling getRole on the ( I assume ) Role class seems to be possible the issue.
If you are using an IDE such as Eclipse then the class is Doctrine\Common\Collections\ArrayCollection; this should be your collection of Roles, I would suggest also is you are using an IDE to do something like this ( for type hinting )
//... at the top of the class file before the class deceleration
use Doctrine\Common\Collections\ArrayCollection;
/**
* #param ArrayCollection $roles
*/
public function setRoles(ArrayCollection $roles)
{
//.. type cast the input to allow only use of ArrayCollection class
$this->roles = $roles;
}
/**
* #return ArrayCollection
*/
public function getRoles()
{
return $this->roles;
}
Also there is a good chance you are setting $this->roles to be a standard array at some point. You should always type cast your input to a specific class if it can only accept that type of class to rule out errors such as using a plain array.
Last thing, is generally protected for the properties are preferred because latter you can extend the class, it's not accessible outside the class much like private, but unlike private it is accessible in inheriting classes.
hello I'm having trouble with:
public function isAdmin()
{
$role = $this->getFirstRole();
if ($role->getRoleId() == "admin")
return true;
return false;
}
it causes: Call to a member function getRoleId() on a non-object
please guys, help. thanks
classes:
class Role implements HierarchicalRoleInterface
{
/**
* Store id.
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Store role kind.
* Possible user kinds: 'guest' (not signed in),
'user' (default for signed in user), 'admin'.
* #var string
* #ORM\Column(type="string", length=255,
unique=true, nullable=true)
*/
protected $roleId;
/**
* Store role parent for inheritance measure.
* #var Role
* #ORM\ManyToOne(targetEntity="User\Entity\Role")
*/
protected $parent;
/**
* Get id.
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
* #param int $id
* #return void
*/
public function setId($id)
{
$this->id = (int)$id;
}
/**
* Get role kind.
* #return string
*/
public function getRoleId()
{
return $this->roleId;
}
/**
* Set role kind.
* #param string $roleId
* #return void
*/
public function setRoleId($roleId)
{
$this->roleId = (string) $roleId;
}
/**
* Get parent role
* #return Role
*/
public function getParent()
{
return $this->parent;
}
/**
* Set parent role.
* #param Role $parent
* #return void
*/
public function setParent(Role $parent)
{
$this->parent = $parent;
}
}
class User implements UserInterface, ProviderInterface
{
/**
* Store id.
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Store username.
* #var string
* #ORM\Column(type="string", length=255, unique=true)
*/
protected $username;
/**
* Store email.
* #var string
* #ORM\Column(type="string", unique=true, length=255)
*/
protected $email;
/**
* Store displayName.
* #var string
* #ORM\Column(type="string", length=50, nullable=true)
*/
protected $displayName;
/**
* Store password.
* #var string
* #ORM\Column(type="string", length=128)
*/
protected $password;
/**
* Store state.
* #var int
*/
protected $state;
/**
* Store mark.
* #var float
*/
protected $mark;
/**
* Store roles collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="User\Entity\Role")
* #ORM\JoinTable(name="users_roles",
* joinColumns={
#ORM\JoinColumn(
name="user_id",
referencedColumnName="id"
)
},
* inverseJoinColumns={
#ORM\JoinColumn(
name="role_id",
referencedColumnName="id"
)
}
* )
*/
protected $roles;
/**
* Store albums collection
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Album\Entity\Album", mappedBy="user",
cascade={"all"})
*/
protected $albums;
/**
* Store comments collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Comment\Entity\Comment", mappedBy="user",
cascade={"all"})
*/
protected $comments;
/**
* Store marks collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Mark\Entity\Mark", mappedBy="user",
cascade={"all"})
*/
protected $marks;
/**
* Initialies collections.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
$this->albums = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->marks = new ArrayCollection();
}
/**
* Get id.
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
* #param int $id
* #return void
*/
public function setId($id)
{
$this->id = (int) $id;
}
/**
* Get username.
* #return string
*/
public function getUsername()
{
return htmlspecialchars($this->username);
}
/**
* Set username.
* #param string $username
* #return void
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Get email.
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
* #param string $email
* #return void
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get displayName.
* #return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Set displayName.
* #param string $displayName
* #return void
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
/**
* Get password.
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set password.
* #param string $password
* #return void
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get state.
* #return int
*/
public function getState()
{
return $this->state;
}
/**
* Set state.
* #param int $state
* #return void
*/
public function setState($state)
{
$this->state = $state;
}
/**
* Get roles collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoles()
{
return $this->roles;
}
public function getFirstRole() {
$roles = $this->getRoles();
$firstRole = $roles[0];
return $firstRole;
}
/**
* Get comments collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getComments()
{
return $this->comments;
}
/**
* Get marks collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getMarks()
{
return $this->marks;
}
/**
* Add a role to user.
* #param Role $role
* #return void
*/
public function addRole($role)
{
$this->roles[] = $role;
}
/**
* Get albums.
* #return \Doctrine\Common\Collections\Collection
*/
public function getAlbums()
{
return $this->albums;
}
public function isAdmin(){
$role = $this->getFirstRole();
if ($role->getRoleId() == "admin")
return true;
return false;
}
/**
* Calculate user mark.
* #return float
*/
public function mark()
{
if (!$this->mark) {
$albums = $this->getAlbums();
$result = 0;
foreach ($albums as &$album) {
$result += $album->mark();
}
$this->mark = $result;
}
return $this->mark;
}
}
anyone?
(writing this becaue it says my post is mostly code)
(writing this becaue it says my post is mostly code)
/**
* Get roles collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoles()
{
return $this->roles;
}
Collections are not accessed by [0], they are Collection objects, use like this:
public function getFirstRole() {
return $this->roles->first();
}
#h2ooooooo gave this helpful link to the docs, containing all methods of the collection: http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html
You can compare ID with an ID (integer), or string by string,
but the best is to compare Entities to keep the whole system integral:
public function isAdmin() {
$role = $this->getFirstRole();
$admin = $entityManager
->getRepository('User\Entity\Role')
->findOneByName('admin');
if ($role === $admin) {
return true;
} else {
return false;
}
}
it seems that $this->getFirstRole() returned user role as string. you just need to compare it as string.
try this:
public function isAdmin()
{
$role = $this->getFirstRole();
return $role == "admin" ? true : false;
}