Search code examples
postgresqlsymfonyeasyadmin

HTTP 500 ERROR An exception occurred Symfony/EasyAdmin


An exception occurred while executing a query: SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "genre_id" of relation "book" violates not-null constraint DETAIL: Failing row contains (7, blabla, abababa, 0, Lorem ipsum dolor sit amet, consectetur adipiscing elit. In inte..., 21/07/2007, null, null, null, null).

Have this error while writing a book data. I tried to enter the genre_id, the name of the genre but it doesn't work. The ID is generated automatically by Symfony so I don't understand how to avoid this to create a book data.

Precision : I made a ManyToOne relation between genre and book, in book entity.

Do you know how to avoid this error ?

My book entity file:

...
/**
* @ORM\Column(type="string", length=255)
     */
    private $genre;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $description;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $date_de_parution;

    /**
     * @ORM\ManyToOne(targetEntity=Genre::class, inversedBy="livres")
     * @ORM\JoinColumn(nullable=false)
     */
    private $Genre;


[![genre table related to books][1]][1]
  [1]: https://i.sstatic.net/GWQNR.png

Solution

  • Your Genre is a required (nullable=false) foreign key. So it requires a Genre to be set when saving to the database.

    If you want books to have NO Genre, you should be using a nullable=true Genre reference. Keep in mind that your getters/setters of Genre should also reflect this nullable return.

    /**
     * @return Genre|null
     */
    public function getGenre(): ?Genre   // See the questionmark (for php 7+ only)
    {
        return $this->Genre;
    }
    

    [update - missed the EasyAdmin part]

    When using admin generators, you should look for something like how to manage relations. It seems that EasyAdmin's documentation is not that great. Looking at the demo application it seems there is an AssociationField field type, which can be used to reference relations.