Symfony2 CRUD generator in 5 minutes
Posted on: 2014-08-19 | Categories:
PHP
CRUD is the acronym for Create, Retrieve Update, Delete.
Symfony2 has their own CRUD generator that is so simple that hardly anyone uses it. Fortunately, there is really nice Symfony2 CRUD generator which extends default SensioGeneratorBundle and add a paginator using PagerFanta and filter support using LexikFormFilterBundle. In the next few lines of code i will show you how to create (generate) full feature user bundle in just 5 minutes (maybe less). Generated code will be easy to extend and modify – there is no magic.
Project skeleton
Let’s start brand new Symfony 2.5 project (more information can be found on Installing and Configuring Symfony2 page):
|
$ composer create-project symfony/framework-standard-edition sfSampleCrudApp/ '~2.5' |
Don’t you have Composer installed yet?
Composer is the package manager used by modern PHP applications and the only recommended way to install Symfony2. To install Composer execute the following commands:
During the installation you will be asked for application database configuration – please provide proper parameters. For mailer configuration confirm default settings.
Notice: you will be also asked if you want to generate Acme demo bundle but we do not need it in our project.
Install required CRUD bundle:
|
$ cd sfSampleCrudApp $ composer require "jordillonch/crud-generator" |
Composer will ask you for version constraint – please provide:
Next step is to enable installed bundles – add the following lines to app/config/AppKernel.php:
|
new Lexik\Bundle\FormFilterBundle\LexikFormFilterBundle(), new JordiLlonch\Bundle\CrudGeneratorBundle\JordiLlonchCrudGeneratorBundle(), |
and set necessary configuration in app/config/config.yml file:
|
framework: translator: { fallback: "%locale%" } ... twig: form: resources: - LexikFormFilterBundle:Form:form_div_layout.html.twig |
Generators
Now we are ready to start generating process.
Generate new bundle skeleton:
|
$ php app/console generate:bundle |
In interactive mode provide required parameters:
|
Bundle namespace: <em>Demo/UserBundle</em> Bundle name [DemoUserBundle]: <em># leave default</em> Target directory [/var/www/sfSampleCrudApp/src]: <em># leave default</em>t Configuration format (yml, xml, php, or annotation): <em>annotation</em> |
…and confirm code generation.
Generate User entity:
|
$ php app/console generate:doctrine:entity --no-interaction --entity=DemoUserBundle:User --fields="username:string(100) password:string(100) firstName:string(100) lastName:string(100) email:string(100) lastLogin:datetime note:text created:datetime" --format=annotation |
This will generate user entity in no-interactive mode with some fields.
Notice: I prefer generating bundles, controllers, forms and entities in interactive mode. For me it’s just more convenient but in this example I wanted to show you that there is also –no-interactive option.
Create and update database schema:
|
$ php app/console doctrine:database:create $ php app/console doctrine:schema:update --force |
And finally generate CRUD for user entity:
|
$ php app/console jordillonch:generate:crud --entity=DemoUserBundle:User --route-prefix=user --with-write --format=annotation --no-interaction |
At the end we only need to install bootstrap assets:
|
$ php app/console assets:install |
and that’s it. Paste in the browser url:
|
http://localhost/sfSampleCrudApp/web/app_dev.php/user/ |
You can now start using our brand new generated user CRUD. Controller, entity, form / filter and views code can be extended and modified.
This bundle can be combined with e.g. FOSUserBundle to provide user authentication and authorization or with GenemuFormBundle for extra widgets.
The complete source code can be found on GitHub.
This post is also available in:
Polish
Mauro
January 13, 2015 02:56
Thank you for this tutorial, very helpful.
Would it be possible to create a crud bundle with table joins?
For example:
Table 1: (UserId, UserName)
Table 2: (UserId, UserAddress)
Create a crud bundle to display UserId, UserName, UserAddress.
Is it possible at all?
Kamil
January 13, 2015 21:30
Almost everything is possible as long as this is the just PHP and Symfony2 code. Generated code can be extended and modified. You can simply add extra joins to
QueryBuilder
and modifyform
orTwig
template to display more properties.Mauro
January 16, 2015 01:30
Hi Kamil,
Thank you very much for your reply.
You were absolutely right, the code is fully customizable and once you get a good understanding of how the code is structured, you can do pretty much anything.
I managed to edit my db query with multiple joins, I also added sorting functionality by clicking on columns and other minor upgrades that matched my needs.
Now I am facing another challenge which I have been looking how to overcome. I was wandering if you had any suggestions about this:
When I’m trying to display a db table with lots of rows (let’s say about 10 millions), it obviously takes a very long time to load; so I was trying to set a limit in the query.
I tried to add a “->setMaxResults(100)” to the query builder on both the paginator() query and the filter() query, but seems like they are ignored and it still returns all data. I’m not sure if this is the right approach.
When I print the generated query to the log, I get exactly what I expect:
SELECT … FROM myTable p0_ LIMIT 100
But I look at the doctrine log in the profiler, the limit is not set in the subquery generated by the paginator:
Do you have any idea how to add a limit to the result in order to speed up the data retrieval?
Or any other suggestions how to deal with big tables?
Thanks very much in advance.
Mauro
Kamil
January 20, 2015 08:26
I think the problem is not in
PagerFanta
bundle and also not in paginator implemenatation:DoctrinePager
which is used for pagination inDoctrineORMAdapter
(check: https://github.com/whiteoctober/Pagerfanta/blob/master/src/Pagerfanta/Adapter/DoctrineORMAdapter.php#L14).This is some kind of DB problem with joins which was explained here: http://stackoverflow.com/a/10941773/751387
dave
April 29, 2015 06:28
hello
this CRUD has delete function ? and there is CRUD that allow to ‘move to trash can’ ..
thanks
Kamil
April 29, 2015 06:40
As you can see in source code: https://github.com/level7systems/sf2-crud/blob/master/src/Demo/UserBundle/Controller/UserController.php#L260 there is
deleteAction
method but it’s not displayed on the user list page by default. You can add it manually or delete user fromshow
/edit
actions.Cheers,
Kamil
Bruno
June 27, 2016 03:02
perfect tutorial , I’m learning now about the ‘ symfony ‘ and his tutorial was the one who helped me .
my only difficulty was version , the new changes ‘ app / console ‘ to ‘ bin / console’