Symfony2 CRUD generator in 5 minutes

Posted on: 2014-08-19 | Categories: PHP

crudCRUD 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):

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:

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:

and set necessary configuration in app/config/config.yml file:

Generators

Now we are ready to start generating process.

Generate new bundle skeleton:

In interactive mode provide required parameters:

…and confirm code generation.

Generate User entity:

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:

And finally generate CRUD for user entity:

At the end we only need to install bootstrap assets:

and that’s it. Paste in the browser url:

You can now start using our brand new generated user CRUD. Controller, entity, form / filter and views code can be extended and modified.

Symfony2 CRUD generator

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