Learn how to easily generate the doctrine entities from a database and create the CRUD in Symfony 5.

How to generate the entities from a database and create the CRUD automatically in Symfony 5

There's a really useful approach to easily create forms to manage the records on your database in Symfony. This is the reverse engineering approach, where the model has been already built so it would be a waste of time to design the entities from scratch as they already exist. In this short article, I will explain to you how to easily create the doctrine entities from the tables in your database automatically in Symfony 5.

1. Configure Database Credentials

The first thing you need to is to configure the connection to the database in your project. In Symfony 5, this can be easily done through the DATABASE_URL parameter in the .env file:

# For example for a MySQL database
DATABASE_URL=mysql://USERNAME:[email protected]:3306/DATABASE_NAME?serverVersion=5.7
# or if you use PostgreSQL
DATABASE_URL="postgresql://127.0.0.1:5432/db?serverVersion=13&charset=utf8"

Once the project has access to the database, it should be now able to build the entities automatically.

2. Create entities automatically

Entities are objects with identity, the identity has a conceptual meaning in your project. For example, for the MySQL database that we will use in this article, we have 2 tables, Person and State:

MySQL Database Relational

So we should have 2 entities. They can be automatically generated with the following Symfony command:

php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity

The command will generate the entities from the tables on your database in the annotation format in the app/src/Entity directory, generating the following output:

Importing mapping information from "default" entity manager
  > writing src/Entity/Person.php
  > writing src/Entity/State.php
Done.

The generated entities (Entity/Person.php and Entity/State.php) will look like this:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * State
 *
 * @ORM\Table(name="state")
 * @ORM\Entity
 */
class State
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, nullable=false)
     */
    private $name;
}

They are plain entities without getters and setters, so it's not complete right now. You should now run the following command to generate the getters and setters of the entities:

php bin/console make:entity --regenerate App

This should generate the following output:

 updated: src/Entity/Person.php
 updated: src/Entity/State.php

  Success! 

So if you check now the entities, you should see the getters and setters of every property in the class:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * State
 *
 * @ORM\Table(name="state")
 * @ORM\Entity
 */
class State
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, nullable=false)
     */
    private $name;

    public function getId(): ?string
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }
}

It's now important to mention, that in this case, we do have a ManyToOne relationship in the state property of the Person entity. So if you create the CRUD for these entities, the form for Person will have a select field that allows you to select a single state to store the person entity. To prevent the error: Object of class \App\Entity\State could not be converted to a string, you need to add the magic toString method in the State entity class that returns the name of the state that will be displayed in the select when the form exists:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * State
 *
 * @ORM\Table(name="state")
 * @ORM\Entity
 */
class State
{
    // ... //
    
    public function __toString() {
        return $this->name;
    }
}

3. Create CRUD

Finally, to create the CRUD since Symfony 5 you can easily do it with a single command, the make:crud instruction:

php bin/console make:crud

This will start a simple prompt that asks for the name of the entity that you are trying to use to create the CRUD. Alternatively, if you don't want to get prompted, simply put the name of the entity as the first positional argument. In our case, to create the CRUD of the Person entity, the command would be the following one:

php bin/console make:crud Person

It will generate the following output:

The class name of the entity to create CRUD (e.g. GentleElephant):
 > Person

 created: src/Controller/PersonController.php
 created: src/Form/PersonType.php
 created: templates/person/_delete_form.html.twig
 created: templates/person/_form.html.twig
 created: templates/person/edit.html.twig
 created: templates/person/index.html.twig
 created: templates/person/new.html.twig
 created: templates/person/show.html.twig

           
  Success! 
           

 Next: Check your new CRUD by going to /person/

The CRUD generator will automatically register a route with the name of the entity that you used, a controller that will handle the basics of the crud as the index view, edit, show, and delete forms automatically for you. In this case, for the Person entity, the route is http://myapp/person. Where you can interact with any view that you want, for example in the index view you should see all the records on the Person table of your database, you may edit every record and update its values, register a new person or delete it from the database:

CRUD Symfony 5

And that's why we love Symfony, wasn't it that fast to create the CRUD for those tables on your database?

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors