I have a problem trying to get data from a table (via entity) using Doctrine2 in a Symfony2.1 project. Here is the controller where I get the error:
/**
* Country list
*/
public function countrylistAction()
{
$em = $this->getDoctrine()->getManager();
$countryList = $em->getRepository('ProjectBaseBundle:SYS_TCountry')
->findAll();
$serializer = new Serializer(array(new GetSetMethodNormalizer()),
array('json' => new JsonEncoder()));
return new Response($serializer->serialize($countryList, 'json'));
}
The entity:
<?php
namespace Company\Project\BaseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="SYS_TCountry")
*/
class SYS_TCountry
{
/**
* #ORM\Id
* #ORM\Column(type="string", length=3, nullable=false)
* #var string
*/
protected $idcountry;
/**
* #ORM\Column(type="string", length=75, nullable=false)
* #Assert\NotBlank()
* #var string
*/
protected $name;
....
public function getIdcountry() { return $this->idcountry; }
public function getName() { return $this->name; }
public function getA2() { return $this->a2; }
public function getA3() { return $this->a3; }
public function getIdstatus() { return $this->idstatus; }
public function setIdcountry($idcountry) { $this->idcountry = $idcountry; }
public function setName($name) { $this->name = $name; }
public function setA2($a2) { $this->a2 = $a2; }
public function setA3($a3) { $this->a3 = $a3; }
public function setIdstatus($idstatus) { $this->idstatus = $idstatus; }
public function __toString() { return $this->idcountry; }
}
Config.yml:
# Doctrine Configuration
doctrine:
dbal:
driver: %database_driver%
host: %database_host%
port: %database_port%
dbname: %database_name%
user: %database_user%
password: %database_password%
charset: UTF8
orm:
auto_generate_proxy_classes: %kernel.debug%
auto_mapping: true
And this is the error:
Warning: class_parents():
Class Company\Project\BaseBundle\Entity\SYS_TCountry does not exist and could not be loaded in
/var/www/project/src/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php line 40
It is strange because, as Doctrine says in console, the mapping is properly done: I test it executing php app/console doctrine:mapping:info:
[OK] Company\Project\BaseBundle\Entity\SYS_TCountry
and if I execute a query in console everything goes fine -> app/console doctrine:query:sql 'SELECT * FROM SYS_TCountry', that return results.
I do not know if using Symfony2.1 I have to configure something different to the 2.0 version, but seems the same because the mapping is Doctrine responsibility.
Symfony follows the PSR-0 standard for filenames. That, amongst other things, means that if you use an underscore in your class name, it will replace it with a directory separator when deciding where your class should live, like this:
\namespace\package\Class_Name => /path/to/project/lib/vendor/namespace/package/Class/Name.php
So, if you have a class named SYS_TCountry it would expect to find it in
Company/Project/BaseBundle/Entity/SYS/TCountry.php
instead of
Company/Project/BaseBundle/Entity/SYS_TCountry.php
I think that your best solution would be to change the filename and class name to SYSTCountry. You don´t need to change the table name.
Your class entity name is not compliant with PSR-0 which causes the loading error.
If you rename your entity to SYSTCountry everything will work fine!
Edit: Default Symfony2 and Doctrine autoloaders ARE PSR-0 compliant.
Related
I have seen many questions in the past about this subject, but none with working solutions. I'm following the Symfony book and cookbook. I used doctrine to fill in getter/setter methods in one of the examples, but it didn't work when I tried to repeat it with another example. When I went back to the previous exercise, it stopped working there too.
The command
php app/console doctrine:generate:entities AppBundle/Entity/User
gives the error
[doctrine\ORM\Mapping\MappingException]
Class "AppBundle\Entity\User" is not a valid entity or mapped super class.
The command
php app/console doctrine:mapping:info
gives the error
[Exception]
You do not have any mapped Doctrine ORM entities according to the current configuration. If you have entities or mapping files you should check your mapping configuration for errors.
This is the class in question:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
* #ORM\Table(name="app_users")
*/
class User implements UserInterface, \Serializable {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function __construct(){
$this->isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getUsername(){
return $this->username;
}
public function getSalt(){
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getPassword(){
return $this->password;
}
public function getRoles(){
return array('ROLE_USER');
}
public function eraseCredentials(){
}
/** #see \Serializable::serialize() */
public function serialize(){
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized){
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
}
The Doctrine configuration within the config.yml:
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
My AppKernel.php
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
new Acme\DemoBundle\AcmeDemoBundle(),
new Acme\TestBundle\AcmeTestBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
edit:
Additionally, I tried generating a new entity in the same bundle and namespace with Doctrine, which it did without problems. Trying to access that entity again with doctrine:generate:entities (after adding #ORM\Entity and all that) gives me the same error again. So the filename is correct and the namespace is correct...
The correct command:
php app/console doctrine:generate:entities AppBundle:User
Try:
php app\console doctrine:generate:entity
This will take you to the Doctrine2 entity generator:
This command helps you generate Doctrine2 entities.
Which basically means that you will have to define the table structure for the users database (it needs to "map" the db table with the entity it's creating).
I'm using couchDb in symfony 2.7.2.
I have several doubts.
Now I installed this Bundle
And I create one entity for testing
<?php
namespace foo\GarageBundle\Document;
use Doctrine\ODM\CouchDB\Mapping\Annotations as CouchDB;
/**
* #CouchDB\Document
*/
class Utente
{
/** #CouchDB\Id */
private $id;
/** #CouchDB\Field(type="string") */
private $nome;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nome
*
* #param string $nome
* #return Utente
*/
public function setNome($nome)
{
$this->nome = $nome;
return $this;
}
/**
* Get nome
*
* #return string
*/
public function getNome()
{
return $this->nome;
}
}
In my controller I added this Code
$dm = $this->container->get('doctrine_couchdb.client.default_connection');
$doc = $this->container->get('doctrine_couchdb.odm.default_document_manager');
try{
$dm->createDatabase($dm->getDatabase());
}catch(\Exception $e){
$msg = $e->getMessage();
}
$user = new Utente();
$user->setNome('foo');
$doc->persist($user);
$doc->flush();
my config.yml is
doctrine_couch_db:
client:
default_connection: default
connections:
default:
dbname: symfony2
odm:
default_document_manager: default
document_managers:
default:
auto_mapping: true
With controller I created Database but I can't insert the new Document, I got this error
The class 'foo\GarageBundle\Document\Utente' was not found in the chain configured namespaces
And I don't understand why it is useful to use a bundle as what I am using ( I know it could be a stupid question ), and why I have to use * #CouchDB\Document instead of #Document inside my entity ?
Seems a problem related the namespace of the entity class.
The automapping is registering the CouchDocument subnamespace of
your bundle, not Document (which is auto-mapped by
DoctrineMongoDBBundle)
So use a different namespace for the User class and the other Counch you use, as follow:
namespace foo\GarageBundle\CouchDocument;
In particular:
<?php
namespace foo\GarageBundle\CouchDocument;
use Doctrine\ODM\CouchDB\Mapping\Annotations as CouchDB;
/**
* #CouchDB\Document
*/
class Utente
{
Hope this help
See this discussion on github.
/**
* #CouchDB\Document
* #CouchDB\Index
*/
class Utente
{
I'm trying to run a simple SQL statement (something like select * from table) in my Symfony2 controller but it's not working. Somehow Symfony cannot find the class.
some info:
I've tried providing the full namespace + class name and just class name in the FROM clause
I've tried DQL and QueryBuilder (see code below. option1 and option2)
AppKernel is loading my DoctrineBundle. This was already there when I use composer to create my project
I've tried auto_mapping true and false in settings.yml
snippets of my codes are below
error message:
[Semantical Error] line 0, col 14 near 'Job j ORDER BY': Error: Class 'Job' is not defined.
500 Internal Server Error - QueryException
1 linked Exception:
QueryException »
[2/2] QueryException: [Semantical Error] line 0, col 14 near 'Job j ORDER BY': Error: Class 'Job' is not defined. +
[1/2] QueryException: SELECT u FROM Job j ORDER BY j.name ASC +
settings.yml
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver, add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
#auto_mapping: false
#mappings:
# MyAppMyBundle:
# type: annotation
# dir: Entity/
my controller
<?php
// src/MyApp/MyBundle/Controller/JobsController.php
namespace MyApp\MyBundle\Controller;
use MyApp\MyBundle\Entity\Job;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class JobsController extends Controller {
public function listAction() {
$em = $this->getDoctrine()->getEntityManager();
//$qb = $em->createQueryBuilder();
//option1
//$qb ->select("j")
// ->from("Job", "j")
// ->orderBy("j.name", "ASC");*/
//return $this->render('MyBundle:Jobs:list.html.twig', array('jobs' => $qb->getQuery()->getResult()));
//option2
$qb = $em->createQuery("SELECT u FROM Job j ORDER BY j.name ASC");
return $this->render('MyBundle:Jobs:list.html.twig', array('jobs' => $qb->getResult()));
}
}
my entity class
<?php
// src/MyApp/MyBundle/Entity/Job.php
namespace MyApp\MyBundle\Entity;
use Doctrine\ORM\Mapping;
/**
* #Mapping\Entity
* #Mapping\Table(name="jobs")
*/
class Job {
/**
* #Mapping\Column(name="job_id", type="integer")
* #Mapping\Id
* #Mapping\GeneratedValue(strategy="AUTO")
*/
protected $jobId;
/**
* #Mapping\Column(name="name", type="text")
*/
protected $name;
/**
* #Mapping\Column(name="job_desc", type="text")
*/
protected $description;
/**
* #Mapping\Column(name="personal_req", type="text")
*/
protected $requirements;
/**
* Get jobid
*
* #return integer
*/
public function getJobId() {
return $this->applicationId;
}
/**
* Set name
*
* #param \text $name
* #return Job
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return text
*/
public function getName() {
return $this->name;
}
/**
* Set description
*
* #param \text $description
* #return Job
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return text
*/
public function getDescription() {
return $this->description;
}
/**
* Set requirements
*
* #param \text $requirements
* #return Job
*/
public function setRequirements($requirements) {
$this->requirements = $requirements;
return $this;
}
/**
* Get requirements
*
* #return text
*/
public function getRequirements() {
return $this->requirements;
}
}
use the full namespace if you make a query directly with entitymanager or just MyAppMyBundle:Job
be sure that your bundle is present in AppKernel
prefer to use $em->getRepository('MyAppMyBundle:Job')->createQueryBuilder('j') or $em->getRepository('MyAppMyBundle:Job')->findBy(array(),array('name' => 'ASC')
validate your model with php app/console doctrine:mapping:info and php app/console doctrine:schema:validate
Exceptions in symfony are always perfect so keep the focus on what your exception says
verify namespace of entity class. Because no generate error when write wrong namespace, but no find entity
I'm new to Symfony, so maybe my problem is very stupid but here it is :
I'm trying to define a custom doctrine DQL function but I can't get it work.
PHP
namespace MsfBundle\AST\Functions;
use Doctrine\ORM\Query\Lexer;
class Geo extends \Doctrine\ORM\Query\AST\Functions\FunctionNode
{
/**
* #var \Doctrine\ORM\Query\AST\ComparisonExpression
*/
private $latitude;
/**
* #var \Doctrine\ORM\Query\AST\ComparisonExpression
*/
private $longitude;
/**
* Parse DQL Function
*
* #param \Doctrine\ORM\Query\Parser $parser
*/
public function parse(\Doctrine\ORM\Query\Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->latitude = $parser->ComparisonExpression();
$parser->match(Lexer::T_COMMA);
$this->longitude = $parser->ComparisonExpression();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
/**
* Get SQL
*
* #param \Doctrine\ORM\Query\SqlWalker $sqlWalker
* #return string
*/
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return sprintf('(6366*acos(cos(radians(%s))*cos(radians(`%s`))*cos(radians(`%s`) -radians(%s))+sin(radians(%s))*sin(radians(`%s`))))',
$this->latitude->leftExpression->dispatch($sqlWalker),
$this->latitude->rightExpression->dispatch($sqlWalker),
$this->longitude->rightExpression->dispatch($sqlWalker),
$this->longitude->leftExpression->dispatch($sqlWalker),
$this->latitude->leftExpression->dispatch($sqlWalker),
$this->latitude->rightExpression->dispatch($sqlWalker));
}
}
config.yml
doctrine:
#...
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
default:
auto_mapping: true
dql:
numeric_functions:
geo :MsfBundle\AST\Functions\Geo
And here's what I get :
Fatal error: Class 'MsfBundle\AST\Functions\Geo' not found in /var/www/mcr/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php on line 3070
If you have any lead to help me get throught this, I'd really appreciate it.
Thanks !
you are missing a backslash in geo :MsfBundle\AST\Functions\Geo, should be geo :\MsfBundle\AST\Functions\Geo. Seems the class need an absolute reference.
I'm very new to Symfony 2.0 and doctrine. I have state and customer entity in different bundle. I just want to add relation between state and customer. I'm coded state and customer entities. Here is the my code:
/**
* #orm:Entity
*/
class Customer
{
/**
* #orm:Id
* #orm:Column(type="integer")
* #orm:GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #OneToOne(targetEntity="State")
* #JoinColumn(name="state_id", referencedColumnName="id")
*/
protected $state;
}
/**
* #orm:Entity
*/
class State
{
/**
* #orm:Id
* #orm:Column(type="integer")
* #orm:GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #orm:Column(type="string", length="50")
*/
protected $name;
}
And my config file:
doctrine:
dbal:
driver: %database_driver%
host: %database_host%
dbname: %database_name%
user: %database_user%
password: %database_password%
orm:
auto_generate_proxy_classes: %kernel.debug%
mappings:
FogCustomerBundle: { type: annotation, dir: Entity/ }
FogMainBundle: { type: annotation, dir: Entity/ }
So my problem is when I generate schema using php app/console doctrine:schema:create command tables are generated. But relationship doesn't generated /state column doesn't generead in customer table/. Why? I don't have any idea? I'll very happy for every advise and post.
You can run into that problem if you're closely following examples from the Doctrine2 documentation, because Symfony2 places all the Doctrine2 annotations into the orm namespace, which you seem to be missing on your OneToOne and JoinColumn annotations. Your code for the $state property should look like this:
/**
* #orm:OneToOne(targetEntity="State")
* #orm:JoinColumn(name="state_id", referencedColumnName="id")
*/
protected $state;
EDIT: With changes introduced in Symfony2 beta2, annotations have changed a little. Annotations need to be imported before they are used; importing Doctrine looks like this:
use Doctrine\ORM\Mapping as ORM;
Then the new usage looks like this:
/**
* #ORM\OneToOne(targetEntity="State")
* #ORM\JoinColumn(name="state_id", referencedColumnName="id")
*/
protected $state;
There is some discussion of further changes to the annotation system; if these changes are rolled out, I'll be back with another edit.