I'm writing a project using codeigniter 2 framework with doctrine 2 as ORM using eclipse PDT. I would like to know if there is a way to have the autocompletition working for the doctrine 2 Entities classes (the ones located in \application\models\Entities folder) I managed to have that working CASUALLY only once, so i know it's possible, now i'm wondering how to get it always working or what i'm doing wrong.
To be clear let's suppose we have this controller:
class Main extends My_Controller {
function index() {
$casualAccount = $this->doctrine->em->find('Entities\Account' , 1);
$casualAccount-> **AUTOCOMPLETITION NOT WORKING HERE**
$this->load->view('welcome_message.php');
}
}
and we have this model in \models\Entities:
use Doctrine\ORM\Mapping as ORM;
/**
* Entities\Account
*/
class Account
{
/**
* #var integer $id
*/
private $id;
/**
* #var string $Mail
*/
private $Mail;
/**
* #var string $Password
*/
private $Password;
/**
* #var string $Type
*/
private $Type;
/**
* #var string $First_name
*/
private $First_name;
/**
* #var string $Last_name
*/
private $Last_name;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Mail
*
* #param string $mail
* #return Account
*/
public function setMail($mail)
{
$this->Mail = $mail;
return $this;
}
/**
* Get Mail
*
* #return string
*/
public function getMail()
{
return $this->Mail;
}
/**
* Set Password
*
* #param string $password
* #return Account
*/
public function setPassword($password)
{
$this->Password = $password;
return $this;
}
/**
* Get Password
*
* #return string
*/
public function getPassword()
{
return $this->Password;
}
/**
* Set Type
*
* #param string $type
* #return Account
*/
public function setType($type)
{
$this->Type = $type;
return $this;
}
/**
* Get Type
*
* #return string
*/
public function getType()
{
return $this->Type;
}
/**
* Set First_name
*
* #param string $firstName
* #return Account
*/
public function setFirstName($firstName)
{
$this->First_name = $firstName;
return $this;
}
/**
* Get First_name
*
* #return string
*/
public function getFirstName()
{
return $this->First_name;
}
/**
* Set Last_name
*
* #param string $lastName
* #return Account
*/
public function setLastName($lastName)
{
$this->Last_name = $lastName;
return $this;
}
/**
* Get Last_name
*
* #return string
*/
public function getLastName()
{
return $this->Last_name;
}
Update.
Manix comment is helping out a little bit. It's possible to declare in the class a variable telling of what class it will be using the following syntax:
class Main extends My_Controller {
/**
* #var Entities\Account
*/
var $casualAccount;
....
}
This could help a little bit but it's still far from the automatic autocompletition eclipse should be capable of.
Let me guess if I a understand. I have never use Eclipse PDT, but should use annotations in inlines variables when it is not clear. The code below helps to the IDE what type of var find() function returns, because this function generate a entity dynamically. There is not an specific type returned.
/**
* #var $casualAccount Entities\Account
*/
$casualAccount = $this->doctrine->em->find('Entities\Account' , 1);
$casualAccount-> **AUTOCOMPLETITION SHOULD WORK AT THIS POINT *
The annotation above is telling to the IDE that $casualAccount is type of Entities\Account.
That is the reason that not always the autocompletition is avaliable. Take a look:
$this->load->library('Foo');
$this->foo-> /* nothing to show */
Autocompletion does not work here because the class reference itself is generated dynamically even you had documented it.
Related
I have a question about extending Sonata UserBundle entity. I need to add more fields to the entity.
Firstly, I extended Sonata UserBundle to my project on the folder src\Application\Sonata\UserBundle
Then I tried to add these fields on the User Entity available on the same folder:
<?php
namespace App\Application\Sonata\UserBundle\Entity;
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
/**
* This file has been generated by the SonataEasyExtendsBundle.
*
* #link https://sonata-project.org/easy-extends
*
* References:
* #link http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
*/
class User extends BaseUser
{
/**
* #var int $id
*/
protected $id;
/**
* Get id.
*
* #return int $id
*/
public function getId()
{
return $this->id;
}
/**
* #var string
* #ORM\Column(type="string")
*/
protected $accountType;
/**
* #var int
* #ORM\ManyToOne(targetEntity="App\Entity\Specialty")
*/
protected $specialty;
/**
* Get AccountType
* #return string
*/
public function getAccountType()
{
return $this->accountType;
}
/**
* Set AccountType
* #param string $accountType
* #return $this
*/
public function setAccountType($accountType)
{
$this->accountType = $accountType;
return $this;
}
/**
* Get Specialty
* #return int
*/
public function getSpecialty()
{
return $this->specialty;
}
/**
* Set Specialty
* #param int $specialty
* #return Specialty
*/
public function setSpecialty($specialty)
{
$this->specialty = $specialty;
return $this;
}
}
On the fos_user.yml I mapped this entity. But when I try to update my schema, by running this command:
php bin/console doctrine:s:u --force
I have a message that states that Nothing to update - your database is already in sync with the current entity metadata.
The added field isn't added on my table. I'm not an expert on Symfony, so I tried to explain my situation as possible as I can.
Specialty entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="specialties")
* #ORM\Entity
*/
class Specialty
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Icon")
*/
private $icon;
/**
* #ORM\Column(type="boolean")
*/
private $status;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
/**
* Get string
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set name
* #param string $name
* #return Specialty
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* #return mixed
*/
public function getIcon()
{
return $this->icon;
}
/**
* #param mixed $icon
* #return $this
*/
public function setIcon($icon)
{
$this->icon = $icon;
return $this;
}
public function getStatus()
{
return $this->status;
}
public function setStatus($status)
{
$this->status = $status;
return $this;
}
public function __toString()
{
return $this->getId() ? (string) $this->getName() : '-';
}
}
Did you run php bin/console make:migration after adjusting the Entity?
php bin/console make:entity (create or update the Entity)
If you prefer to add new properties manually, the make:entity command can generate the getter & setter methods for you: php bin/console make:entity --regenerate
php bin/console make:migration
inspect src/Migrations/ folder
run the migrations php bin/console doctrine:migrations:migrate
read
I've just started to learn Symfony framework and I noticed that almost every time there is some meaningful error in my code (for example I missed some "use" statement) my server terminates unexpectedly and I don't know how to get any information about what exactly caused it.
Most of the time I was able to figure it out on my own, but now I've just started to use Doctrine and I want to save some object to the database, but when I run the code my server terminates. I figured out that the "flush()" method is causing the problem, but now I'm stuck as I can't get any more information about the error. So I actually have two questions - how can I get more information about errors like this and how to solve this particiular one?
The codes are below:
The controller
/* UserController.php */
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\User;
use Symfony\Component\HttpFoundation\Response;
class UserController extends Controller
{
/**
* #Route("/user/test")
*/
public function testAction(Request $request)
{
$user = new User();
$user->setLogin("Test");
$user->setEmail("test#test.com");
$user->setPassword(hash("sha256", "test"));
$user->setJoined(date("Y-m-d H:i:s"));
$user->setActivationCode(NULL);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush(); /* The line that causes server to terminate! */
return new Response("Hello");
}
}
And the entity
/* User.php (Entity) */
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="`user`")
*/
class User
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=128)
*/
private $email;
/**
* #ORM\Column(type="string", length=64)
*/
private $login;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="datetime")
*/
private $joined;
/**
* #ORM\Column(type="string", length=64, nullable=TRUE)
*/
private $activation_code;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* 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 login
*
* #param string $login
*
* #return User
*/
public function setLogin($login)
{
$this->login = $login;
return $this;
}
/**
* Get login
*
* #return string
*/
public function getLogin()
{
return $this->login;
}
/**
* 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 joined
*
* #param \DateTime $joined
*
* #return User
*/
public function setJoined($joined)
{
$this->joined = $joined;
return $this;
}
/**
* Get joined
*
* #return \DateTime
*/
public function getJoined()
{
return $this->joined;
}
/**
* Set activationCode
*
* #param string $activationCode
*
* #return User
*/
public function setActivationCode($activationCode)
{
$this->activation_code = $activationCode;
return $this;
}
/**
* Get activationCode
*
* #return string
*/
public function getActivationCode()
{
return $this->activation_code;
}
}
Use web/app_dev.php as your endpoint.
So your url will be like localhost:8000/app_dev.php/<your-routing-alias>
Are you using a web browser to access your Symfony instance on a remote host - I mean a machine that is not the 'localhost'? If so, you'll need to edit the 'web/app_dev.php' file where it has a line like so:
|| !(in_array(#$_SERVER['REMOTE_ADDR'], ['192.168.40.208', '192.168.255.74',
'127.0.0.1', 'fe80::1', '::1']) || php_sapi_name() === 'cli-server')
Enter in the IP address of the remote host that you are trying to access your web URL from. Using the DEV URL: of "http://ip_address/app_dev.php/" would be the best way to troubleshoot.
You'll see useful help information when you use this link - I highly recommend it.
I also notice this one line:
#ORM\Table(name="`user`")
I'm not sure if you need those backticks. Try this:
#ORM\Table(name="user")
I recently had this issue and after a lot of investigation discovered the date was causing my issue. I can see this is an old question, but the answer may help someone.
It looks like Doctrine requires a full date time object when inserting into a datetime / datetimetz field:
Try replacing
$user->setJoined(date("Y-m-d H:i:s"));
With
$user->setJoined(new \DateTime("now"));
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.
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.
Simple process,
Need to create Users with mapped Roles.
I followed the step from link
http://symfony.com/doc/current/cookbook/security/entity_provider.html
User and Roles table generated but users_roles table is not generated in MySql...
Will i need to create it manually?
Second
I have configured with User table for Authentication
After login it redirects to Error page,
FatalErrorException: Error: Call to a member function toArray() on a non-object in /var/www/vibilling_3/src/ViBillingPortal/AuthenticationBundle/Entity/users.php line 130
I searched, but i cant find any solutions... Below my code
Bill/PortalBundle/Entity/users.php
namespace ViBillingPortal\AuthenticationBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* users
*/
class users implements UserInterface, \Serializable
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $username;
/**
* #var string
*/
private $password;
/**
* #var string
*/
private $created_date;
/**
* #ORM\ManyToMany(targetEntity="roles", inversedBy="users")
* #ORM\JoinTable(name="user_roles")
*/
private $userroles;
public function __construct()
{
$this->userroles = new ArrayCollection();
}
/**
* 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 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 created_date
*
* #param string $created_date
* #return users
*/
public function setCreated_date($password)
{
$this->password = $created_date;
return $this;
}
/**
* Get Created_date
*
* #return string
*/
public function getCreated_date()
{
return $this->created_date;
}
/**
* Get Roles
*/
public function getRoles()
{
return $this->userroles->toArray();
}
/**
* #inheritDoc
*/
public function getSalt()
{
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
}
}
Bill/PortalBundle/Entity/roles.php
namespace ViBillingPortal\AuthenticationBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* roles
*/
class roles implements RoleInterface, \Serializable
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="users", mappedBy="userroles")
*/
protected $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return roles
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #see RoleInterface
*/
public function getRole()
{
return $this->role;
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
}
}
You should use a ManyToMany relation, not a ManyToOne if you want to use a join table : http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#many-to-many-bidirectional
For the second error, it's strange as you initialize usersroles as an ArrayCollection in your construct method, it should work.
Could you add a var_dump to look what is stored in this property ?
Why don't you get any setter/getter for usersroles ?
I think you should also read Symfony coding standards : http://symfony.com/doc/current/contributing/code/standards.html. You coding style is not consistent.