I'm using Zend Framework 2 with Doctrine2.
I use a User and Project entity. A user can have more projects and a project can have multiple users. So i use another entity User_Project.
They are all set up and I've validated the schema. All mapping files are correct and the database schema is in sync (orm:validate-schema).
When I try to get all my users, I get an error that the target entity cannot be found (see title). Same error when I try getting one user.
ERROR
The target-entity Application\Entity\User_Project cannot be found in 'Application\Entity\User#user'.
Controller:
return $this->getEntityManager()->getRepository('Application\Entity\User')->findAll();
User entity
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/** #ORM\Entity
* #ORM\Table(name="user")
**/
class User {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", name="user_id")
*/
protected $user_id;
/** #ORM\Column(type="string") */
protected $fullName;
/** #ORM\OneToMany(targetEntity="User_Project", mappedBy="user") */
protected $user;
public function getUserId()
{
return $this->user_id;
}
public function getFullName()
{
return $this->fullName;
}
public function setFullName($value)
{
$this->fullName = $value;
}
}
Project entity
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/** #ORM\Entity
#ORM\Table(name="project")
**/
class Project {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", name="project_id")
*/
protected $project_id;
/** #ORM\Column(type="string") */
protected $customer;
/** #ORM\Column(type="string") */
protected $project_name;
/** #ORM\OneToMany(targetEntity="User_Project", mappedBy="project") */
private $project;
public function getProjectId()
{
return $this->project_id;
}
}
User_Project entity
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/** #ORM\Entity
* #ORM\Table(name="user_project")
**/
class User_Project {
/**
* #ORM\Id()
* #ORM\ManyToOne(targetEntity="User", inversedBy="user")
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id", nullable=false)
*/
protected $user;
/**
* #ORM\Id()
* #ORM\ManyToOne(targetEntity="Project", inversedBy="project")
* #ORM\JoinColumn(name="project_id", referencedColumnName="project_id", nullable=false)
*/
protected $project;
public function getUser()
{
return $this->project;
}
public function getProject()
{
return $this->user;
}
public function setUser($value)
{
$this->user = $value;
}
public function setProject($value)
{
$this->project = $value;
}
}
Modules.php
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
may definition of your entity in Module.php or module.config.php is wrong .
please copy Module.php or module.config.php
correct definition in module.config.php:
return array(
'doctrine' => array(
'driver' => array(
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
))))),
in user Entity may be better rename user property to userProjects or projects and apply change on relation definition on User_Project
check your column names in database . if you want have correct db . i recommend schema tool for create db .
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->getEntityManager());
$classes = array(
$this->getEntityManager()->getClassMetadata('Application\Entity\User'),
$this->getEntityManager()->getClassMetadata('Application\Entity\Project'),
$this->getEntityManager()->getClassMetadata('Application\Entity\User_Project'),
);
$tool->dropSchema($classes);
$tool->createSchema($classes);
in a controller or somewhere else .
Related
I created Document manually, and tried to save data using persist.its show me following error.
The class 'Kdm\\SettingBundle\\Document\\Discount' was not found in the chain configured namespaces FOS\\UserBundle\\Entity, Ivory\\GoogleMapBundle\\Entity at
/var/www/project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:37)"}
Here is my document file Discount.php
<?php
namespace Kdm\SettingBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Discount
* #MongoDB\Document(repositoryClass="Kdm\SettingBundle\Repository\SettingRepository")
*/
class Discount
{
/**
* #MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* #MongoDB\Field(type="integer")
*/
protected $value;
/**
* Get id
*
* #return string $id
*/
public function getId()
{
return $this->id;
}
/**
* #param integer $value
*/
public function setValue($value)
{
$this->value = $value;
}
/**
* #return integer
*/
public function getValue()
{
return $this->value;
}
}
Here is my SettingController.php
<?php
namespace Kdm\SettingBundle\Controller;
use Kdm\KdmBundle\Controller\RefController as KdmController;
use Kdm\SettingBundle\Document\Discount as Setting;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
* #Route("/setting")
*/
class SettingController extends KdmController
{
/**
* Constructor
*/
public function __construct()
{
parent::__construct('Kdm', 'Setting', 'setting','Discount');
}
/**
* #Route
* (
* path="/",
* name="kdm_setting"
* )
* #Template("::KdmSetting/Front/index.html.twig")
*/
public function indexAction()
{
$setting = new Setting();
$setting->setValue('5');
$em = $this->getDoctrine()->getManager();
$em->persist($setting);
$em->flush();
$form = $this->createFormBuilder($setting)
->add('value','integer')
->add('save','submit')
->getForm();
return array(
'form' => $form->createView()
);
}
}
i try to solve this error since last 2 days :( Can you help?
I am using the ResolveTargetEntityListener from Doctrine to access SQL tables that are in an external database.
when I use the createQueryBuilder to query the data on the external/base Vehicle class I get the following error:
Expected value of type "AppBundle\Entity\VehicleFox" for association field "AppBundle\Entity\FM_Positions#$truck", got "FoxBundle\Entity\Vehicle" instead.
When I do it on the internal VehicleFox class the Query returns NULL.
Is there anything that I have missed?
Below is the Controller which I am doing the query from withe the relevant functions. I have also included the classes and interfaces that have been used as well as the config.yml file.
FmController
<?php
namespace BWT\FMBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Request;
use Vendors\FM;
use AppBundle\Entity\FuelData;
use MaxBundle\Entity\UdoDriver;
use FoxBundle\Entity\Vehicle;
use AppBundle\Entity\FM_Positions;
class FMController extends Controller
{
public function latestPositionsAction(Request $request)
{
$_render_args = array();
$_results = array();
$tripProcesses = new FM();
$success = $this->login($tripProcesses);
If ($success === true) {
$_results = $tripProcesses->getTrackingData();
}
if ($_results) {
$_render_args['results'] = $_results;
}
$this->CreateFmPositions($_results);
return $this->render('Telematics/latestPositions.html.twig', $_render_args);
}
private function CreateFmPositions(array $results)
{
foreach ($results as $result){
$resultArray = (array) $result;
$vehicle = $this->getVehicleFM($resultArray['VehicleID']);
$position = new FM_Positions();
if ($vehicle) {
$position->setTruck($vehicle[0]);
}
$em = $this->getDoctrine()->getManager();
$em->persist($position);
$em->flush();
}
}
private function getVehicleFM(int $vehFmId)
{
$repository = $this->getDoctrine()->getRepository('FoxBundle:Vehicle', 'foxem'); // error for incorrect Entity
//$repository = $this->getDoctrine()->getRepository('AppBundle:VehicleFox'); // returns NULL
$query = $repository->createQueryBuilder('v')
->where('v.fmId = :fmid')
->setParameter('fmid', $vehFmId)
->getQuery()
->getResult();
return $query;
}
}
Fm_Positions.php
<?php
// src/AppBundle/Entity/FM_Possitions.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Model\VehicleInterface;
use AppBundle\Model\UDODriverInterface;
/**
* #ORM\Entity
* #ORM\Table(name="fm_positions")
* #author sarah
*
*/
class FM_Positions
{
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Model\VehicleInterface", inversedBy="fm_positions")
* #ORM\JoinColumn(name="truck_id", referencedColumnName="id")
* #var VehicleInterface
*/
private $truck;
// ...
}
Base Vehicle class
<?php
namespace FoxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Vehicle
* #ORM\Table(name="vehicle", uniqueConstraints={#ORM\UniqueConstraint(name="fleet_number", columns={"fleet_number"})}, indexes={#ORM\Index(name="log_book_date", columns={"log_book_date"})})
* #ORM\Entity
*/
class Vehicle
{
/**
* #var string|null
* #ORM\Column(name="fleet_number", type="string", length=20, nullable=true)
*/
private $fleetNumber;
/**
* #var string|null
* #ORM\Column(name="FM_ID", type="string", length=20, nullable=true)
*/
private $fmId;
// ...
}
Extended Vehicle Class
<?php
// src/AppBundle/Entity/VehicleFox.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FoxBundle\Entity\Vehicle as BaseVehicle;
use AppBundle\Model\VehicleInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="vehicle_fox")
*/
class VehicleFox extends BaseVehicle implements VehicleInterface
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string|null
* #ORM\Column(name="fleet_number", type="string", length=20, nullable=true)
*/
private $fleetNumber;
/**
* #var string|null
* #ORM\Column(name="FM_ID", type="string", length=20, nullable=true)
*/
private $fmId;
/**
* #ORM\OneToMany(targetEntity="FM_Positions", mappedBy="truck")
*/
private $fm_positions;
}
Vehicle Interface
<?php
// src/AppBundle/Model/VehicleInterface.php
namespace AppBundle\Model;
interface VehicleInterface
{
public function __construct();
/**
* #return string
*/
public function getId();
public function addTruckUnit(\AppBundle\Entity\Truck_Units $truckUnit);
public function removeTruckUnit(\AppBundle\Entity\Truck_Units $truckUnit);
public function getTruckUnits();
public function addFmPosition(\AppBundle\Entity\FM_Positions $fmPosition);
public function removeFmPosition(\AppBundle\Entity\FM_Positions $fmPosition);
public function getFmPositions();
public function addFmTrip(\AppBundle\Entity\FM_Trips $fmTrip);
public function removeFmTrip(\AppBundle\Entity\FM_Trips $fmTrip);
public function getFmTrips();
public function addSkytrackPosition(\AppBundle\Entity\Skytrack_Positions $skytrackPosition);
public function removeSkytrackPosition(\AppBundle\Entity\Skytrack_Positions $skytrackPosition);
public function getSkytrackPositions();
}
Config.yml
doctrine:
# ...
orm:
resolve_target_entities:
AppBundle\Model\VehicleInterface: AppBundle\Entity\VehicleFox
auto_generate_proxy_classes: "%kernel.debug%"
default_entity_manager: maxem
entity_managers:
maxem:
connection: maxdb
mappings:
AppBundle:
foxem:
connection: foxdb
mappings:
FoxBundle: ~
FMPositionType form
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
class FM_PositionsType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('position_id')
->add('truck_id', EntityType::class, Array(
'class' => 'FoxBundle:Vehicle',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('v')
->orderBy('v.fleetNumber', 'ASC');
},
'placeholder' => 'Select A Truck',
'choice_label' => 'fleetNumber',
'em' => 'foxem',
))
->add('driver_id', EntityType::class, Array(
'class' => 'MaxBundle:UdoDriver',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('d')
->orderBy('d.nickname', 'ASC');
},
'placeholder' => 'Select A Driver',
'choice_label' => 'nickname',
'em' => 'max2em',
))
->add('date')
->add('latitude')
->add('longitude')
->add('heading')
->add('speed')
->add('altitude');
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\FM_Positions'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_fm_positions';
}
}
I have a PSR-loaded package that defines a series of relationships around a 'User' entity it provides.
In many of the use cases where you use this package, you may want to keep all entities intact, but, substitute your own User entity.
As concrete example, the package gives me this Entity (using Annotations here to keep things clear):
namespace CirclicalUser\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* An example entity that represents an action rule.
*
* #ORM\Entity
* #ORM\Table(name="acl_actions_users")
*
*/
class UserActionRule
{
/**
* #var int
* #ORM\Id
* #ORM\ManyToOne(targetEntity="CirclicalUser\Entity\ActionRule", inversedBy="user_exceptions")
* #ORM\JoinColumn(name="action_rule_id", referencedColumnName="id")
*/
protected $action_rule;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="CirclicalUser\Entity\User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
}
Given the above, is there any way I could supplant the user relationship in UserActionRule::$user, that targets CirclicalUser\Entity\User, with my own user: Acme\Entity\User (assuming it is a Doctrine Entity in its own right)
e.g., pretend PHP:
function onBoostrap( $e ){
DoctrineMagic::getMapping(UserActionRule::class)->get('user')->getManyToOne()->setTargetEntity(Acme\Entity\User::class);
}
Thank you!
I managed to solve this by listening to the loadClassMetadata event.
namespace CirclicalUser\Listener;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\Common\EventSubscriber;
class UserEntityListener implements EventSubscriber
{
const DEFAULT_ENTITY = 'CirclicalUser\Entity\User';
private $userEntity;
public function __construct($userEntity)
{
$this->userEntity = $userEntity;
}
public function getSubscribedEvents()
{
return ['loadClassMetadata'];
}
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
{
/** #var \Doctrine\ORM\Mapping\ClassMetadata $classMetadata */
$classMetadata = $eventArgs->getClassMetadata();
if ($this->userEntity == self::DEFAULT_ENTITY) {
return;
}
switch ($classMetadata->getName()) {
case 'CirclicalUser\Entity\UserActionRule':
$classMetadata->associationMappings['user']['targetEntity'] = $this->userEntity;
break;
}
}
}
This listener successfully substitutes the mapping for the user-defined entity class.
Adding the listener (Zend Framework) was trivial:
'doctrine' => [
'eventmanager' => [
'orm_default' => [
'subscribers' => [
UserEntityListener::class,
],
],
],
Separately, in service manager config:
'service_manager' => [
'invokables' => [
UserAuthenticationLogMapper::class => UserAuthenticationLogMapper::class,
],
'factories' => [
UserEntityListener::class => UserEntityListenerFactory::class,
],
],
I am making entities using doctrine in codeigniter by reversenginerring (i.e. i had my database and i had made the entities by running the command orm:convert-mapping --form-database annotation models/Entity)
my doctrine.php goes like this ...
<?php
use Doctrine\Common\ClassLoader,
Doctrine\ORM\Tools\Setup,
Doctrine\ORM\EntityManager;
class Doctrine
{
public $em;
public function __construct()
{
require_once __DIR__ . '/Doctrine/ORM/Tools/Setup.php';
Setup::registerAutoloadDirectory(__DIR__);
// Load the database configuration from CodeIgniter
require APPPATH . 'config/database.php';
$connection_options = array(
'driver' => 'pdo_mysql',
'user' => $db['default']['username'],
'password' => $db['default']['password'],
'host' => $db['default']['hostname'],
'dbname' => $db['default']['database'],
'charset' => $db['default']['char_set'],
'driverOptions' => array(
'charset' => $db['default']['char_set'],
),
);
// With this configuration, your model files need to be in application/models/Entity
// e.g. Creating a new Entity\User loads the class from application/models/Entity/User.php
$models_namespace = 'Entity';
$models_path = APPPATH . 'models';
$proxies_dir = APPPATH . 'models/Proxies';
$metadata_paths = array(APPPATH . 'models');
// Set $dev_mode to TRUE to disable caching while you develop
$config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode = true, $proxies_dir);
$this->em = EntityManager::create($connection_options, $config);
//changing enum to string coz enum is not support as default by doctrine :)
$platform = $this->em->getConnection()->getDatabasePlatform();
$platform->registerDoctrineTypeMapping('enum', 'string');
$loader = new ClassLoader($models_namespace, $models_path);
$loader->register();
}
}
and the entities which i get after running the commnad goes like this ...
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SsClass
*
* #ORM\Table(name="ss_class")
* #ORM\Entity
*/
class SsClass
{
/**
* #var integer $classId
*
* #ORM\Column(name="class_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $classId;
/**
* #var string $class
*
* #ORM\Column(name="class", type="string", length=200, nullable=true)
*/
private $class;
/**
* #var string $classContent
*
* #ORM\Column(name="class_content", type="string", length=500, nullable=true)
*/
private $classContent;
/**
* #var string $isApproved
*
* #ORM\Column(name="is_approved", type="string", nullable=true)
*/
private $isApproved;
/**
* #var string $isActive
*
* #ORM\Column(name="is_active", type="string", nullable=true)
*/
private $isActive;
public function getClassId() {
return $this->classId;
}
public function setClassId($classId) {
$this->classId = $classId;
}
public function getClass() {
return $this->class;
}
public function setClass($class) {
$this->class = $class;
}
public function getClassContent() {
return $this->classContent;
}
public function setClassContent($classContent) {
$this->classContent = $classContent;
}
public function getIsApproved() {
return $this->isApproved;
}
public function setIsApproved($isApproved) {
$this->isApproved = $isApproved;
}
public function getIsActive() {
return $this->isActive;
}
public function setIsActive($isActive) {
$this->isActive = $isActive;
}
}
I am trying to fetch the data from database by my controller name as welcome controller as ..
public function index()
{
//$user=new Entity\SsClass;
$data=$this->em->find('Entity\Ssclass',1);
print_r($data);
//echo $user->get();
die();
}
}
But when i run this code i gote the error as
Fatal error: Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class Entity\Ssclass is not a valid entity or mapped super class.' in D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\MappingException.php:147 Stack trace: #0 D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\Driver\AnnotationDriver.php(165): Doctrine\ORM\Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass('Entity\Ssclass') #1 D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\ClassMetadataFactory.php(293): Doctrine\ORM\Mapping\Driver\AnnotationDriver->loadMetadataForClass('Entity\Ssclass', Object(Doctrine\ORM\Mapping\ClassMetadata)) #2 D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\ClassMetadataFactory.php(178): Doctrine\ORM\Mapping\ClassMetadataFactory->loadMetadata('Entity\Ssclass') #3 D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\EntityManager.php(269): Doctrine\ORM\Mapping\ClassMetadataFactory->getMetadataFor( in D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\MappingException.php on line 147
What is going on here any suggestion??
Have you tried clearing your cache ?
I just ran into the same problem and clearing the cache did it !
You can use the symfony2 command line like so:
$ php app/console cache:clear [--env=yourenv]
Or delete the cache folder in app/cache.
Good luck :)
I am trying to set up Doctrine (2.2.1) to use with my site and I followed the getting started guide and I am getting the following error:
Fatal error: Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class DocumentField is not a valid entity or mapped super class.' in C:\inetpub\sites\hd\Doctrine\ORM\Mapping\MappingException.php:147 Stack trace: #0 C:\inetpub\sites\hd\Doctrine\ORM\Mapping\Driver\AnnotationDriver.php(165) {...}
DocumentField is defined as follows (in root/Doctrine/entities/DocumentField.php:
<?php
/** #Entity **/
/** #Table(name="DocumentFields") */
class DocumentField
{
/** #Id #GeneratedValue #Column(type="integer") **/
protected $id;
/** #var #Column(type="string") **/
protected $fieldName;
/** #var #Column(type="integer") **/
protected $fieldType;
/** #var #Column(type="integer") **/
protected $required;
public function getId() {
return $this->id;
}
public function getName() {
return $this->fieldName;
}
public function setName($name) {
$this->fieldName = $name;
}
public function getType() {
return $this->fieldType;
}
public function setType($type) {
$this->fieldType = $type;
}
public function getRequired() {
return $this->required;
}
public function setRequired($value) {
$this->required = $value;
}
}
?>
Doctrine is included like this in the page:
/* Load Doctorine ORM */
require "$root/Doctrine/ORM/Tools/Setup.php";
$lib = "$root/";
Doctrine\ORM\Tools\Setup::registerAutoloadDirectory($lib);
require "doctrine-configure.php";
The doctrine-configure.php file:
//if ($applicationMode == "development") {
$cache = new \Doctrine\Common\Cache\ArrayCache;
//} else {
// $cache = new \Doctrine\Common\Cache\ApcCache;
//}
$config = new Configuration;
$config->setMetadataCacheImpl($cache);
$driverImpl = $config->newDefaultAnnotationDriver($GLOBALS["BASE_PATH"].'\\Doctrine\\entities');
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCacheImpl($cache);
$config->setProxyDir($GLOBALS["BASE_PATH"].'\\Doctrine\\proxies');
$config->setProxyNamespace('Helpdesk\Proxies');
//if ($applicationMode == "development") {
$config->setAutoGenerateProxyClasses(true);
//} else {
// $config->setAutoGenerateProxyClasses(false);
//}
$connectionOptions = array(
'driver' => 'pdo_sqlsrv',
'user' => '{user}',
'password' => '{pass}',
'host' => 'sql1',
'dbname' => 'HD'
);
$entityManager = EntityManager::create($connectionOptions, $config);
?>
And finally the code that causes the crash:
require "$root/Doctrine/entities/DocumentField.php";
$field = new DocumentField();
$field->setName("Hello World");
$field->setType(1);
$field->setRequired(1);
$entityManager->persist($field);
$entityManager->flush();
Each Doctrine annotation is actually a representation of an instance of a class, so you have to specify a namespace (\Doctrine\ORM\Mapping) for each annotation if you are not inside such namespace, just as if you are instantiating one of those classes by yourself.
Try it this way:
<?php
use \Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="DocumentFields")
*/
class DocumentField
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $fieldName;
/**
* #ORM\Column(type="integer")
*/
protected $fieldType;
/**
* #ORM\Column(type="integer")
*/
protected $required;
// ...
<?php
// bootstrap or config.php
require __DIR__ . '/../vendor/autoload.php';
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
$paths = array('PATH_WITH_ENTITIES');
$isDevMode = false;
// the connection configuration
$dbParams = array(
'driver' => 'pdo_mysql',
'user' => 'USER',
'password' => 'PASS',
'host' => 'HOST',
'dbname' => 'DB',
);
$classLoader = new Doctrine\Common\ClassLoader('Application\Entity',__DIR__.'/../admin/module/Application/src/');
$classLoader->register();
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$driver = new AnnotationDriver(new AnnotationReader(), $paths);
// registering noop annotation autoloader - allow all annotations by default
AnnotationRegistry::registerLoader('class_exists');
$config->setMetadataDriverImpl($driver);
$em = EntityManager::create($dbParams, $config);
?>