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"));
Related
I am trying to build a simple app
I have a database with a table "matches"the table structure
and i wrote this code as Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="matches")
*/
class Match
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="text", length=512)
*/
private $descr;
/**
* #ORM\Column(type="string", length=255)
*/
private $team_a;
/**
* #ORM\Column(type="string", length=255)
*/
private $team_b;
/**
* #ORM\Column(type="string", length=255)
*/
private $location;
/**
* #ORM\Column(type="datetime")
*/
private $datetime;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set descr
*
* #param string $descr
*
* #return Match
*/
public function setDescr($descr)
{
$this->descr = $descr;
return $this;
}
/**
* Get descr
*
* #return string
*/
public function getDescr()
{
return $this->descr;
}
/**
* Set teamA
*
* #param string $teamA
*
* #return Match
*/
public function setTeamA($teamA)
{
$this->team_a = $teamA;
return $this;
}
/**
* Get teamA
*
* #return string
*/
public function getTeamA()
{
return $this->team_a;
}
/**
* Set teamB
*
* #param string $teamB
*
* #return Match
*/
public function setTeamB($teamB)
{
$this->team_b = $teamB;
return $this;
}
/**
* Get teamB
*
* #return string
*/
public function getTeamB()
{
return $this->team_b;
}
/**
* Set location
*
* #param string $location
*
* #return Match
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set datetime
*
* #param \DateTime $datetime
*
* #return Match
*/
public function setDatetime($datetime)
{
$this->datetime = $datetime;
return $this;
}
/**
* Get datetime
*
* #return \DateTime
*/
public function getDatetime()
{
return $this->datetime;
}
}
and this as controller:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Match;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
class AddMatch
{
/**
* #Route("/addmatch")
*/
public function createAction()
{
$match = new Match();
$match->setDescr('Descrizione Partita');
$match->setTeamA('Squadra A');
$match->setTeamB('Squadra B');
$match->setLocation('a nice Gym');
$match->setLocation('12/12/2012');
$em = $this->getDoctrine()->getManager();
// tells Doctrine you want to (eventually) save the Product (no queries yet)
$em->persist($match);
// actually executes the queries (i.e. the INSERT query)
$em->flush();
return new Response('Saved new match with id '.$match->getId());
}
}
but it dosent work and I get Not Found
What am I missing?
I am super n00b :(
thanks for your help
You have to extend the base symfony controller:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class AddMatch extends Controller
{
...
}
If, for some reason, you can't extend a controller, you still can use Doctrine entity manager. In that case you need to inject the service container and then get the entity manager with
$container->get('doctrine')->getManager();
You should thoroughly read the Symfony guide on Service Container.
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.
I am new in symfony2, I would like to register some user in my profile_tbl.
here is my code in the controller.
<?php
namespace Ai\QABlogBundle\Controller;
use Ai\QABlogBundle\Entity\Profile_tbl;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class QABlogController extends Controller
{
/**
*#Route("/" , name= "home")
*/
public function homeAction()
{
return $this->render('AiQABlogBundle:QABlog:primaries/index.html.twig');
}
/**
*#Route("/register/" ,name= "register")
*/
public function registerAction(Request $request)
{
$profile = new Profile_tbl();
$form = $this -> createFormBuilder($profile)
-> add ('fname' , 'text')
-> add ('lname' , 'text')
-> add ('gender' , 'text')
-> add ('email' , 'text')
-> add ('register' , 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($profile);
$em->flush();
return new Response('News added successfuly');
}
$build['form'] = $form->createView();
return $this->render('AiQABlogBundle:QABlog:primaries/registration.html.twig', $build);
}
}
When I try to run it in my browser it gives an error
"Attempted to load class "Profile_tbl" from namespace "Ai\QABlogBundle\Entity".
Did you forget a "use" statement for another namespace?"
I don't know what is wrong .. Can you help me?
my Profile_tbl entity
<?php
namespace Ai\QABlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Profile_tbl
*
* #ORM\Table()
* #ORM\Entity
*/
class Profile_tbl
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="fname", type="string", length=255)
*/
private $fname;
/**
* #var string
*
* #ORM\Column(name="lname", type="string", length=255)
*/
private $lname;
/**
* #var string
*
* #ORM\Column(name="gender", type="string", length=255)
*/
private $gender;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fname
*
* #param string $fname
* #return Profile_tbl
*/
public function setFname($fname)
{
$this->fname = $fname;
return $this;
}
/**
* Get fname
*
* #return string
*/
public function getFname()
{
return $this->fname;
}
/**
* Set lname
*
* #param string $lname
* #return Profile_tbl
*/
public function setLname($lname)
{
$this->lname = $lname;
return $this;
}
/**
* Get lname
*
* #return string
*/
public function getLname()
{
return $this->lname;
}
/**
* Set gender
*
* #param string $gender
* #return Profile_tbl
*/
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender
*
* #return string
*/
public function getGender()
{
return $this->gender;
}
/**
* Set email
*
* #param string $email
* #return Profile_tbl
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
}
I try to rename or make another entity ..
steps that I tried to generate my new entity.
Creating Database:
php app/console doctrine:database:create
Generate Entity:
php app/console doctrine:generate:entity
Generate the Getters and Setters:
php app/console doctrine:generate:entities AiQABlogBundle
after this I run it in my browser.
and gives me an error ,
Attempted to load class "Profile" from namespace "Ai\QABlogBundle\Controller".
Did you forget a "use" statement for e.g. "Twig_Profiler_Profile" or "Symfony\Component\HttpKernel\Profiler\Profile"?
This happened to me a few times. It usually happens when I copy-paste an old class file to create a new class. Check your classname and the filename of the file containing your class; they should be the same. In your case they should be Profile_tbl and Profile_tbl .php respectively.
Update
Profile_tbl is converted to Profile/tbl.php as per the PSR-0 autoload convention which Composer uses by default to load classes inside the src/ directory. You'll have to rename the class to something that does not use an underscore e.g. ProfileTbl or simply Profile.
// This should be in the file: src/Ai/QABlogBundle/Entity/Profile.php
namespace Ai\QABlogBundle\Entity;
/**
* Profile
*
* #ORM\Table()
* #ORM\Entity
*/
class Profile
{
// ...
}
Credits to Pazi for pointing this out.
I'm about to embark on trying to add a profile picture field to my User entity in a symfony2 project I'm working on which uses FOSUserBundle. I have a feeling that this should be really simple, however, I've not found any useful documentation explaining how to do it.
At the moment, I'm planning on adding an unmapped field to my form object (which I've extended from the generic ProfileEdit form) which takes an uploaded file. I'll then create an event listener for either FOSUserEvents::PROFILE_EDIT_SUCCESS or FOSUserEvents::PROFILE_EDIT_COMPLETED, which will take the form, handle the file upload and persist the path of the uploaded file (with methods to get the public URL and absolute path) to my User object, before adding a message to the Response flashbag to say it was either successful or unsuccessful. Is this really the correct/best practice way to do this? Or am I missing something? Is this functionality really not included yet in the FOSUserBundle? If so I've not found the docs for it, but would love it if it was....
Any help / tips / voodoo advice would be so greatly appreciated!
So, it turns out I was getting lost answering this question: the file upload needn't be handled by FOSUserBundle per se, rather by Doctrine. I added a property to my User entity which is not persisted, but which is simply used by the form to edit a user's profile. In the code below this property is $profilePictureFile. Lifecycle callbacks then ensure that this file is copied to the relevant location before the entity is persisted (and similarly when edited and when deleted).
Still, I thought I'd post an answer alongside my code here to help others who find themselves wanting to add profile pictures to a user in FOSUserBundle in the future.
The relevant documentation is:
http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_forms.rst
<?php
// DAWeldonExampleBundle/Entity/User.php
namespace DAWeldon\Example\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Security\Core\Util\SecureRandom;
/**
* #ORM\Entity()
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="datetime")
*/
protected $lastEdited;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank(message="Please enter your surname.", groups={"Registration", "Profile"})
*/
protected $surname;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank(message="Please enter your forename.", groups={"Registration", "Profile"})
*/
protected $forename;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $nickname;
/**
* #Assert\File(maxSize="2048k")
* #Assert\Image(mimeTypesMessage="Please upload a valid image.")
*/
protected $profilePictureFile;
// for temporary storage
private $tempProfilePicturePath;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $profilePicturePath;
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set surname
*
* #param string $surname
* #return User
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* #return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set forename
*
* #param string $forename
* #return User
*/
public function setForename($forename)
{
$this->forename = $forename;
return $this;
}
/**
* Get forename
*
* #return string
*/
public function getForename()
{
return $this->forename;
}
/**
* Asks whether the user is granted a particular role
*
* #return boolean
*/
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
/**
* Set nickname
*
* #param string $nickname
* #return User
*/
public function setNickname($nickname)
{
$this->nickname = $nickname;
return $this;
}
/**
* Get nickname
*
* #return string
*/
public function getNickname()
{
return $this->nickname;
}
/**
* Get the best way to address this person
*
* #return string
*/
public function getBestAddress() {
if (empty($this->getNickname()) and empty($this->getForename()) && empty($this->getSurname())) {
return $this->getUsername();
}
elseif (empty($this->getNickname())) {
return $this->getForename().' '.$this->getSurname();
}
else {
return $this->getNickname();
}
}
/**
* Sets the file used for profile picture uploads
*
* #param UploadedFile $file
* #return object
*/
public function setProfilePictureFile(UploadedFile $file = null) {
// set the value of the holder
$this->profilePictureFile = $file;
// check if we have an old image path
if (isset($this->profilePicturePath)) {
// store the old name to delete after the update
$this->tempProfilePicturePath = $this->profilePicturePath;
$this->profilePicturePath = null;
} else {
$this->profilePicturePath = 'initial';
}
return $this;
}
/**
* Get the file used for profile picture uploads
*
* #return UploadedFile
*/
public function getProfilePictureFile() {
return $this->profilePictureFile;
}
/**
* Set profilePicturePath
*
* #param string $profilePicturePath
* #return User
*/
public function setProfilePicturePath($profilePicturePath)
{
$this->profilePicturePath = $profilePicturePath;
return $this;
}
/**
* Get profilePicturePath
*
* #return string
*/
public function getProfilePicturePath()
{
return $this->profilePicturePath;
}
/**
* Get the absolute path of the profilePicturePath
*/
public function getProfilePictureAbsolutePath() {
return null === $this->profilePicturePath
? null
: $this->getUploadRootDir().'/'.$this->profilePicturePath;
}
/**
* Get root directory for file uploads
*
* #return string
*/
protected function getUploadRootDir($type='profilePicture') {
// the absolute directory path where uploaded
// documents should be saved
return __DIR__.'/../../../../web/'.$this->getUploadDir($type);
}
/**
* Specifies where in the /web directory profile pic uploads are stored
*
* #return string
*/
protected function getUploadDir($type='profilePicture') {
// the type param is to change these methods at a later date for more file uploads
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'uploads/user/profilepics';
}
/**
* Get the web path for the user
*
* #return string
*/
public function getWebProfilePicturePath() {
return '/'.$this->getUploadDir().'/'.$this->getProfilePicturePath();
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUploadProfilePicture() {
if (null !== $this->getProfilePictureFile()) {
// a file was uploaded
// generate a unique filename
$filename = $this->generateRandomProfilePictureFilename();
$this->setProfilePicturePath($filename.'.'.$this->getProfilePictureFile()->guessExtension());
}
}
/**
* Generates a 32 char long random filename
*
* #return string
*/
public function generateRandomProfilePictureFilename() {
$count = 0;
do {
$generator = new SecureRandom();
$random = $generator->nextBytes(16);
$randomString = bin2hex($random);
$count++;
}
while(file_exists($this->getUploadRootDir().'/'.$randomString.'.'.$this->getProfilePictureFile()->guessExtension()) && $count < 50);
return $randomString;
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*
* Upload the profile picture
*
* #return mixed
*/
public function uploadProfilePicture() {
// check there is a profile pic to upload
if ($this->getProfilePictureFile() === null) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getProfilePictureFile()->move($this->getUploadRootDir(), $this->getProfilePicturePath());
// check if we have an old image
if (isset($this->tempProfilePicturePath) && file_exists($this->getUploadRootDir().'/'.$this->tempProfilePicturePath)) {
// delete the old image
unlink($this->getUploadRootDir().'/'.$this->tempProfilePicturePath);
// clear the temp image path
$this->tempProfilePicturePath = null;
}
$this->profilePictureFile = null;
}
/**
* #ORM\PostRemove()
*/
public function removeProfilePictureFile()
{
if ($file = $this->getProfilePictureAbsolutePath() && file_exists($this->getProfilePictureAbsolutePath())) {
unlink($file);
}
}
/**
* Set lastEdited
*
* #param \DateTime $lastEdited
* #return User
*/
public function setLastEdited($lastEdited)
{
$this->lastEdited = $lastEdited;
return $this;
}
/**
* Get lastEdited
*
* #return \DateTime
*/
public function getLastEdited()
{
return $this->lastEdited;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function setLastEditedValueAsNow() {
$this->setLastEdited(new \DateTime());
}
}
And of course, the profile form looks like this:
<?php
// DAWeldonExampleBundle/Form/Type/ProfileFormType.php
namespace DAWeldon\Example\UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ProfileFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// add your custom field
$builder->add('username')
->add('surname')
->add('forename')
->add('nickname')
->add('profilePictureFile');
}
public function getParent()
{
return 'fos_user_profile';
}
public function getName()
{
return 'readypeeps_user_profile';
}
}
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.