Symfony3 error Namespace does not contain any mapped entities - php

I tried generate getters and setters in Symfony 3.0.1
when i run command
php bin/console doctrine:generate:entities VendorName/MyBundle/EntityName
i have error
Namespace "VendorName\MyBundle\EntityName" does not contain any mapped entities.
where is the mistake?
Edit-1: First generate entity with YAML format
Edit-2: I tried generate getters and setters for vendor bundle
Also i try with command php bin/console doctrine:generate:entities VendorNameMyBundle:EntityName and have another error:
Can't find base path for "VendorName\MyBundle\Entity\EntityName" (path: "/home/site/vendor/vendorname/mybundle/Entity", destination: "/home/site/vendor/vendorname/mybundle/Entity").

As John Pancoast points out in his answer to a different question:
Doctrine does not support PSR-4 when doing anything with code generation. It has to do with how they map class namespaces to filesystem paths and how PSR-4 allows class/namespace paths that don't directly map to the filesystem.
https://github.com/doctrine/DoctrineBundle/issues/282
To clarify what exactly is needed to resolve the error message; You have to edit your bundle's composer.json file, and also change the bundle's folder structure.
in composer.json change psr-4 to psr-0:
"autoload": {
"psr-4": { "Acme\\Bundle\\AwesomeBundle\\": "" }
},
to:
"autoload": {
"psr-0": { "Acme\\Bundle\\AwesomeBundle\\": "" }
},
Change bundle's folder structure from:
vendor
+--acme
+--awesome-bundle
|--Controller
|--Entity
to:
vendor
+--acme
+--awesome-bundle
+--Acme
+--Bundle
+--AwesomeBundle
|--Controller
|--Entity
The following command will no longer throw an exception:
bin/console doctrine:generate:entities AwesomeBundle

You have mistake in command, you trying to generate entities but you provide class name for one entity. Try the following for all entities:
php bin/console doctrine:generate:entities VendorName/MyBundle
or if you want just one entity:
php bin/console doctrine:generate:entity VendorName/MyBundle/EntityName

Symfony 3.22 with src/AppBundle/Entity/User.php
if you add new field using ORM
**/**
* #ORM\Column(name="last_login", type="datetimetz")
*/
private $lastLogin;**
just use
use php bin/console doctrine:generate:entities AppBundle
it will check all your Entities r and update getters and setters
then use
php bin/console doctrine:schema:update to update your database
use
php bin/console doctrine:schema:update --force in PROD enviroment

Related

Symfony make:entity annotation mapping error

I want to create a new entity in my ORO platform application by using the make:entity command from the MakerBundle.
I expect it to create an entity in my bundle Acme\Bundle\TestBundle which I set in my config_dev.yml by using:
maker:
root_namespace: 'Acme\Bundle\TestBundle'
So I execute
bin/console make:entity Test
which returns
! [NOTE] It looks like your app may be using a namespace other than "Acme\Bundle\TestBundle".
!
! To configure this and make your life easier, see:
! https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html#configuration
created: src/Acme/Bundle/TestBundle/Entity/Test.php
created: src/Acme/Bundle/TestBundle/Repository/TestRepository.php
[ERROR] Only annotation mapping is supported by make:entity, but the
<info>Acme\Bundle\TestBundle\Entity\Test</info> class uses a different format. If you would like
this command to generate the properties & getter/setter methods, add your mapping configuration, and then
re-run this command with the <info>--regenerate</info> flag.
I've tried to run the command once again, which works. But obviously this is not the way how it's meant to work. So how can I fix this mapping error?
I started with the standard Symfony 5 project by using Symfony new myapp.
I add the config file in config/packages/dev/maker.yaml
maker:
root_namespace: 'App\Core'
To generate the entity in the src/Core folder, I got the following error:
➜ symfony console make:entity Post
created: src/Core/Entity/Post.php
created: src/Core/Repository/PostRepository.php
[ERROR] Only annotation mapping is supported by make:entity, but the <info>App\Core\Entity\Post</info> class uses
a different format. If you would like this command to generate the properties & getter/setter methods, add your
mapping configuration, and then re-run this command with the <info>--regenerate</info> flag.
To avoid showing the error in the console, I install the patch created by vklux / maker-bundle-force-annotation
Step 1: install package
composer require cweagans/composer-patches
Step 2: apply the patch in composer.json
{
// {...} composer.json content
"extra": {
"patches": {
"symfony/maker-bundle": {
"Provide flag to force annotation in make entity command": "https://raw.githubusercontent.com/vklux/maker-bundle-force-annotation/master/maker-force-annotation-flag.patch"
}
}
}
}
Step 3: composer update
composer update
Step 4: try make:entity with the additional command option
➜ symfony console make:entity Post --force-annotation
created: src/Core/Entity/Post.php
created: src/Core/Repository/PostRepository.php
Entity generated! Now let's add some fields!
You can always add more fields later manually or by re-running this command.
New property name (press <return> to stop adding fields):
>
✅ 🚀 👍 Everything works fine now.
It's a bug in the doctrine version please try this version good luck
composer req doctrine/doctrine-bundle:2.2
I found a solution to create new entities with Symfony maker using doctrine/doctrine-bundle version higher than 2.2.4
These steps worked for me with:
"doctrine/doctrine-bundle": "^2.7"
PHP 8.1 (I migrate from php 7.4 in my case)
STEP 1: replace type: annotation by type: attribute inside doctrine.yaml
STEP 2: Enter entity root with namespace:
symfony console make:entity App\Entity\test

Symfony4 Error loading classes custom folder "Expected to find class... but it was not found"

Problem
I'm trying to setup a custom directory structure
for some shared classes in my Symfony project. I
want to create a custom folder in the root of my
project and I want to use the Symfony auto-load
feature to automatically register services from
that folder.
So I added a custom services namespace to the
services.yaml file:
# src ./config/services.yaml
services:
...
TestNamespace\:
resource: '../TestNamespace/*'
...
And I added an empty class in the custom folder:
# src ./TestNamespace/TestClass.php
namespace TestNamespace;
class TestClass
{
}
When I run the app I get the following error:
(1/2) InvalidArgumentException
Expected to find class "TestNamespace\TestClass" in file
"/path/to/ClassLoadErrorDemo/demo/TestNamespace/TestClass.php"
while importing services from resource
"../TestNamespace/*", but it was not found! Check the
namespace prefix used with the resource.
(2/2) FileLoaderLoadException
Expected to find class "TestNamespace\TestClass" in file
"/path/to/ClassLoadErrorDemo/demo/TestNamespace/TestClass.php" while
importing services from resource "../TestNamespace/*", but it was not
found! Check the namespace prefix used with the resource in
/path/to/ClassLoadErrorDemo/demo/config/services.yaml (which is loaded
in resource "/path/to/ClassLoadErrorDemo/demo/config/services.yaml").
I double checked the paths, namespace and the class
name multiple times and everything seems fine and I
don't understand why I still get the error.
Controllers in the ./src folder seem to load fine.
What am I doing wrong here?
Steps to reproduce
I created a demo repo to isolate the problem.
git clone https://github.com/smoelker/SymfonyClassLoadErrorDemo.git
cd SymfonyClassLoadErrorDemo/demo
composer install
mv TestNamespace/TestClass.php_ TestNamespace/TestClass.php
php bin/console server:start
Update your composer.json autoload setup
{
[...]
"autoload": {
"psr-4": {
"TestNamespace\\": "TestNamespace/",
"": "src/"
}
},
[...]
}
After run: composer dump-autoload and try again.
composer dump-autoload --classmap-authoritative will only work if your src directory is present at the time you run the command.
This can be an issue with multi-stage Docker builds in particular, when you are normally only copying the composer.json/composer.lock into the build image.

Doctrine2 generate entities with setters and getters

I've successfully installed and used doctrine according to this article: Getting started with Doctrine.
Now I want to reverse engineer an existing database. I tried running the following command:
php vendor/doctrine/orm/bin/doctrine orm:convert-mapping --from-database annotation entity/generated
and that generated entity files with the correct annotations. However, I want to generate the setters and getters instead of having to code them myself.
Many people are referring to this article: How to generate Entities from an Existing Database. The first command in the article is:
php app/console doctrine:mapping:import --force AcmeBlogBundle xml
I cannot find the app folder nor the console file from the installation of Symfony and Doctrine. My composer.json file contents are:
{
"require": {
"doctrine/orm": "2.4.*",
"symfony/yaml": "2.*"
},
"autoload": {
"psr-0": {"": "src/"}
}
}
I got this from the Getting Started with Doctrine article. Am I missing a dependency in my composer.json file? Where can I find app/console?
EDIT 1:
Paul Andrieux, I added "symfony/framework-standard-edition": "2.5.*" to my composer.json file. Now I have a folder vendor/framework-standard-edition. This contains an app folder which contains the console file. However, I get an error for because the "console" script is attempting "require_once DIR.'/bootstrap.php.cache'" and the bootstrap.php.cache does not exist. What should this file contain? do I need to create it myself? What other steps should I take after creating or acquiring this file?
I found way to generate Getter & Setters just use Doctrine ORM.
you should use orm:convert-mapping generate XML mapping file then use orm:generate-entities generate XML to PHP class
orm:convert-mapping [--filter FILTER] [-f|--force] [--from-database] [--extend [EXTEND]] [--num-spaces [NUM-SPACES]] [--namespace [NAMESPACE]] [--] <to-type> <dest-path>
orm:generate-entities [--filter FILTER] [--generate-annotations [GENERATE-ANNOTATIONS]] [--generate-methods [GENERATE-METHODS]] [--regenerate-entities [REGENERATE-ENTITIES]] [--update-entities [UPDATE-ENTITIES]] [--extend EXTEND] [--num-spaces NUM-SPACES] [--no-backup] [--] <dest-path>
A. My composer.json (I'm use doctrine 2.5.*)
...
"require": {
"doctrine/orm": "^2.5"
},
...
B. Config cli tools
My cli-config.php
NOTE: use method createXMLMetadataConfiguration NOT createAnnotationMetadataConfiguration
<?php
$db = [
// ...
];
$paths = [ __DIR__ . '/../Model/'];
// this place should use function Setup::createXMLMetadataConfiguration
$config = \Doctrine\ORM\Tools\Setup::createXMLMetadataConfiguration($paths, false);
$entityManager = \Doctrine\ORM\EntityManager::create($db, $config);
return \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet($entityManager);
C. generate XML
php vendor/bin/doctrine orm:convert-mapping -f --namespace='Model\' --from-database xml app/Model
path app/Model must match you paths when set in file cli-config.php
D. generate PHP class
php vendor/bin/doctrine orm:generate-entities --generate-annotations="true" app/
this will generate the right content and right namespace to what you want
According to your composer.json file, you didn't install symfony2, only it's yaml component.
Just follow this guide if you want to install symfony2 full stack: http://symfony.com/get-started

Symfony2 - "Warning: class_parents(): Class Ambience does not exist and could not be loaded in "

I am trying to create an entity using yml and I am getting the following error:
[ErrorException]
Warning: class_parents(): Class Ambience does not exist and could not be loaded in C:\wamp\www\demo\vendor\gedmo-doctrine-extensions\lib\Gedmo\Mapping\ExtensionMetadataFactory.php line 80
I have created a file named Entities.UserTestDelete.dcm.yml in FooBundle/Resources/config/doctrine/metadata/orm
Contents of file:
Entities\UserTestDelete:
type: entity
table: users
id:
id:
type: integer
generator:
strategy: AUTO
fields:
name:
type: string
length: 50
Then I executed the following command:
php app/console doctrine:mapping:import "DemoFooBundle" yml
And then I got the error. Any idea why would that be a problem?
Just had the same problem ... and managed to solve ...
a var_dump($this) on __contruct of the exception class, in my case:
Symfony\Component\Debug\Exception\ContextErrorException
got me the $message->$trace, which led me to:
vendor/sylius/resource-bundle/EventListener/LoadORMMetadataSubscriber.php
calling function "class_parents"
in function "setAssociationMappings"
So quick fix is to simply comment out the subscribed event:
/**
* #return array
*/
public function getSubscribedEvents()
{
// return array(
// 'loadClassMetadata',
// );
}
now when running "app/console doctrine:mapping:import" again ... there won't be anymore errors ...
also if needed, run the mapping:convert and generate:entities command before enabling / uncommenting the subscribed Event again ...
If you are not using Sylius, try var_dump'ing on your exception class ... there's a good chance you too got some Eventlistner interfering with Doctrine's Import command ...
good luck!
Update
Your first mistake is that you created the yml file. As explained in the cookbook, the doctrine:mapping:import command actually generates the file. Ditch yours, run the command, and let doctrine generate the file itself.
What you do afterwards, is generate the actual entity classes:
php app/console doctrine:mapping:convert annotation ./src
php app/console doctrine:generate:entities DemoFooBundle
If the tables themselves don't exist yet, then you can use these last 2 commands to generate the entities, and then run
php app/console doctrine:schema:update --force
To have doctrine create the tables for you.
A quick look in the cookbook tells me that the bundle name should not be quoted, and that you might want to pass the --force flag to the doctrine:mapping:import command.
It's in the reverse-engineering bit
php app/console doctrine:mapping:import --force DemoFooBundle yml
That's the example Symfony2 cookbook gives, only changed to take yml, instead of xml format.
The error message could also be related to the table name:
table: users
Where the entity is called
class Users
{}
possible related question

Generating a single Entity from existing database using symfony2 and doctrine

Is it possible to generate a single entity from database using the Symfony2 console tool?
In the middle of coding I had to add a table and there are modifications made to the existing entity classes. So I don't want all my entities regenerated.
Any suggestions will be appreciated!
I had the same problem, you've to do this way:
php app/console doctrine:mapping:convert metadata_format \
./src/App/MyBundle/Resources/config/doctrine \
--from-database \
--filter="Yourtablename"
Then
php app/console doctrine:mapping:import AppMyBundle \
metadata_format --filter="Yourtablename"
Where metadata_format is the file ending you want to generate (e.g. xml, yml, annotation)
And finally
php app/console doctrine:generate:entities AppMyBundle --no-backup
Like this doctrine will load only the entity you need. Just be carefull on the filter you must use the CamelCase !
Hope this will help you
For the third command, doctrine kept regenerating all of the Entity files. By adding the entity name after the bundle, it only generated the entity I was interested in.
php app/console doctrine:generate:entities AppMyBundle:Yourtablename --no-backup
Simple Working Solution for Symfony 2.7 option annotation and for [/xml/yml] see http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html
do 3 commands in 3 steps:
$ php app/console doctrine:mapping:import --force AppBundle xml --filter="Meeting"
(NOTE: if your database name is my_meeting You will need to change it to MyMeeting in filter="MyMeeting" for doctrine to find your table name. This is because doctrine will always strip underscores and add Camel-case to your table name. If not, you will get this error: "Database does not have any mapping information".)
$ php app/console doctrine:mapping:convert annotation ./src/AppBundle/Entity --from-database --filter="Meeting"
(NOTE: making sure you have namespace AppBundle\Entity; as below in your Meeting.php class file like this:
<?php
/**
* Created by PhpStorm.
* User:
* Date: 03-Sep-2015
* Time: 3:23 PM
*/
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
If not add it in.)
where:
AppBundle is exactly your "AppBundle" in Symfony 2.7
Meeting is the target table (Camel-Case sensitive)
TO BE SURE, check this directory:
src\AppBundle/Resources/config/doctrine/Meeting.orm.xml
AND MAKING SURE you only have .xml files for the table you want to create entity class files and no others. Then run this below command to generate get and set methods for your entity class that you created previously
$ php app/console doctrine:generate:entities AppBundle:Meeting --no-backup
NOTE2:
As the last step you must delete the xml doctrine orm db file in for example src\AppBundle/Resources/config/doctrine/VisitorData.orm.xml
It works very well for me.
For explanation please read: http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html
#fyrye's comment that is currently hidden deserves the credit, wanted to add this so it's not missed by others. This is the approach:
/** #var \Doctrine\DBAL\Connection $connection */
$config = $connection->getConfiguration();
// for excluding an specific table
$config->setFilterSchemaAssetsExpression('/^(table_to_reverse_engineer_1|table_to_reverse_engineer_2).*$/');
source: https://coderwall.com/p/jofhdw/doctrine-tell-which-tables-to-work-with
I was having issues when running the following command because of large number of badly defined legacy tables
php ./vendor/bin/doctrine orm:convert-mapping --force --from-database annotation ./src/UI/Entity/
It turns out that the --filter flag only filters AFTER it has read meta data from all of your tables which, if they don't have primary keys or have some other issue, will cause the command to fail
None of the answers were quite right for me using Symfony 3. I ended up doing:
php bin/console doctrine:mapping:import --force MyBundle xml --filter="MyTable"
php bin/console doctrine:mapping:convert annotation ./src --filter="MyTable"
php bin/console doctrine:generate:entities MyBundle:MyTable --path ./src
I would have left this as a comment to the accepted answer but I'm a newbie.
For those like me who had trouble with the --filter switch mapping multiple tables with coincident strings in names, one can use a pattern.
Example table names:
Vendor
VendorContact
php app/console doctrine:mapping:convert metadata_format \
./src/App/MyBundle/Resources/config/doctrine \
--from-database \
--filter="Vendor"
That command will convert both tables rather than just Vendor. If you want just Vendor and not VendorContact, use a pattern in --filter:
php app/console doctrine:mapping:convert metadata_format \
./src/App/MyBundle/Resources/config/doctrine \
--from-database \
--filter="\bVendor\b"
Hope that helps someone!
Works great with Symfony 3 too.
If you are getting "No Metadata Classes to process." message try convert your tablename to Doctrine camel casing in the filter parameter.
"my_table_name" needs to be write as "MyTableName".
--filter works with entity name, not table name !
php bin/console doctrine:mapping:import "App\Entity" annotation --path=config/doctrine --filter="YourEntity"
for Symfony 3
To generate the entities for a new "Group" table
php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/AppBundle/Entity --filter Group
as written in the symfony 3 documentation
I had exactly the same issue with Symfony 2.4 and MySQL.
None of the workarounds posted above worked for me.
I ended up creating a new database with the tables I want to extract (this can be easy to do because MySQL provides the creation script).
Then changed the connection to that new database and executed the entity extraction command from there.
Seems to be a bit radical, but I will not create the entities by hand.
Hope that helps
Didn't work any of these for my symfony 3.3. So I just created a copy of directory and re-generated all of the entities in copy directory. Then I copied required entities in my original directory.
--filter does not work due to this issue https://github.com/symfony/symfony/issues/7717
Since 2019 doctrine has deprecated the reserve-engineering functionality, and it is therefore not recommended to use it any more. Instead, Symfony recommends to use make:entity from the Symfony Maker Bundle instead.

Categories