i`m trying to generate CRUD for some entities in Symfony 2, apparently the
generate:doctrine:crud command is unavailable.
[InvalidArgumentException]
Command "generate:doctrine:crud" is not defined.
also , in the list for available commands, I only get one command.
generate
generate:doctrine:entities Generates entity classes and method stubs from your mapping information
is there a bundle or something in the configuration missing, or what is the cause for not having this functionality.
Addition:
The doctrine:generate:crud command is provided by the SensioGeneratorBundle
Please also make sure you have the bundle available and registered in your app/AppKernel.php like this:
class AppKernel extends Kernel
{
public function registerBundles()
{
// ...
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
// ...
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
// ...
}
As in my example the command is also normally only available in the dev environment. Therefore ...
php app/console --env=prod doctrine:generate:crud
.. or any other configuration that uses production enviroment won't work.
doctrine:generate:crud is the command you should use
You can see a list of commands using php app/console list
Related
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
I have a Symfony 4 application and Doctrine with Doctrine migrations. I'm introducing Codeception for running API tests, and need to run migrations before the tests run. Since I'm using the Doctrine2 module I don't really want to be also including the DB module as it's not needed for the tests and would require configuring the test database in two different locations.
I am using the Symfony module currently, and I noticed that the Laravel module has a run_database_migrations configuration option.
What is the best way to handle running the Doctrine migrations command in a Symfony app prior to the tests? (bin/console doctrine:migrations:migrate -n is the specific command).
Edit I've got a solution that, although it works, is nowhere near ideal. By using Codeception Customisation I've created the following extension that basically manually execs the underlying Symfony commands.
class DatabaseMigrationExtension extends Extension
{
public static $events = [
Events::SUITE_BEFORE => 'beforeSuite',
];
public function beforeSuite(SuiteEvent $e)
{
echo(exec('bin/console doctrine:database:drop --force') . PHP_EOL);
echo(exec('bin/console doctrine:database:create') . PHP_EOL);
echo(exec('bin/console doctrine:migrations:migrate -n') . PHP_EOL);
}
}
Edit 2 The goal of this is basically to replicate similar functionality to what the Codeception DB module does, which allows you to provide an SQL dump of a database that it automatically uses in the tests, but instead use Doctrine migrations to handle the DB. - https://codeception.com/docs/modules/Db#sql-data-dump
I spent a while trying a couple of different ways to achieve this. I initially used RunProcess however this seemed to cause sporadic issues with the DB being deleted and not recreated, despite using the sleep configuration. I ended up just updating the existing extension to use the CLI module instead, and it works as desired (without having to create scripts or run multiple commands) and without having to use exec.
Final extension;
class DatabaseMigrationExtension extends Extension
{
public static $events = [
Events::SUITE_BEFORE => 'beforeSuite',
];
public function beforeSuite()
{
try {
/** #var \Codeception\Module\Cli $cli */
$cli = $this->getModule('Cli');
$this->writeln('Recreating the DB...');
$cli->runShellCommand('bin/console doctrine:database:drop --if-exists --force');
$cli->seeResultCodeIs(0);
$cli->runShellCommand('bin/console doctrine:database:create');
$cli->seeResultCodeIs(0);
$this->writeln('Running Doctrine Migrations...');
$cli->runShellCommand('bin/console doctrine:migrations:migrate --no-interaction');
$cli->seeResultCodeIs(0);
$this->writeln('Test database recreated');
} catch (\Exception $e) {
$this->writeln(
sprintf(
'An error occurred whilst rebuilding the test database: %s',
$e->getMessage()
)
);
}
}
}
and registered;
// codeception.yml
extensions:
enabled:
- \DatabaseMigrationExtension
Output (-vv or higher also displays the output of the DB & Migration commands);
I always create a bash script to do this, or a Makefile.
bash command
My ./runtests.sh scripts contains
#!/bin/bash
./bin/console command:for:migrations
./bin/phpunit
Makefile
Same with Makefile
.FOO: testsuite
testsuite:
./runtests.sh
or
.FOO: testsuite
testsuite:
./bin/console command:for:migrations
./bin/phpunit
why I prefer Makefile
Recently I added this script in my .bash_profile that allow me to autocomplete from bash all target made in makefile (very easy because you dont need anymore to remember all commands, but just make and tab).
complete -W "`grep -oE '^[a-zA-Z0-9_.-]+:([^=]|$)' Makefile | sed 's/[^a-zA-Z0-9_.-]*$//'`" make
Thus, .. you can create target like:
runtests
runtests_with_fixtures
migrations
runtests_with_migrations
...
and so on
My suggestion is to create your custom and easy way to run commands.
Here a way to run all or just one command usgin make
.FOO: dropforce
dropforce:
bin/console doctrine:database:drop --force
.FOO: dbcreate
dbcreate:
bin/console doctrine:database:create
.FOO: migrate
migrate:
bin/console doctrine:migrations:migrate
.FOO: suite
suite: dropforce dbcreate migrate
With Codeception 4 you can do it without Cli module:
$symfony = $this->getModule('Symfony');
$symfony->runSymfonyConsoleCommand('doctrine:database:drop',['--if-exists'=>true, '--force'=>true]);
$symfony->runSymfonyConsoleCommand('doctrine:database:create');
$symfony->runSymfonyConsoleCommand('doctrine:migrations:migrate', ['--no-interaction'=>true]);
When I create a docker entrypoint script for my project I run:
php /bin/composer install --no-dev
But thhat throws an exception that is:
Fatal error: Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "AjglBreakpointTwigExtensionBundle" from namespace "Ajgl\Twig\Extension\SymfonyBundle".
The code over the AppKernel.php that initializes the bundle is:
public function registerBundles()
{
//Other Bundle initialization
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Ajgl\Twig\Extension\SymfonyBundle\AjglBreakpointTwigExtensionBundle();
}
return $bundles;
}
This bundle I use int on dev and test environments where it has use. The container I build is for production use.
Therefore I want somehow to let the ScriptHandlers that when composer executes, theese run over a prod environment and not a dev one in order to supress the error message?
I suppose this is a duplicate of this issue.
Just set the SYMFONY_ENV var to prod and use composer install then:
SYMFONY_ENV=prod php /bin/composer install --no-dev
My Internet conexion is useless to install a symphony 2 dependency with composer as far as I can say. Is there a way to install a third party bundle manually? I have been looking in Google and I did not find any useful thing so far. About my connection issue, I started this thread to try and find a solution to install within this connection. here I am trying to find clues to a solution to install manually.
Regards
1 Create under vendor directory the path for bundle :
/*like mycompany*/ /*like product-bundle*/ /*like MyCompany*/
vendor/yourbundlenamespace/your-bundle-name-bundle/YourBundleNameSpace/
2 Go to in the new path and put the content of budle (or clone from github).
3* #deprecated
Load the reference path on autoload, so go to in
vendor/composer/autoload_namespaces.php
and put in the array
'YourBundleNameSpace\\YourBundleNameBundle' => array($vendorDir . '/yourbundlenamespace/your-bundle-name-bundle');
4 Register bundle: go to in
app/AppKernel.php
and put in the array $bundles the new bundle:
```
public function registerBundles()
{
$bundles = array(
//...
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
//...
// this is our bundle :)
$bundles[] = new YourBundleNameSpace\YourBundleNameBundle\YourBundleNameBundle();
}
```
UPDATE
Point 3: this method is not performance because when update via composer is overwrite, instead, you should do:
-go to on app/autoload.php
and put following code after $loader definition
```
//add customs classes
$loader->add('YourBundleNameSpace\\YourBundleNameBundle','vendor//yourbundlenamespace/your-bundle-name-bundle');
```
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