Home > Software engineering >  Symfony & doctrine : how limit the number of association between two entities in ManyToOne relation?
Symfony & doctrine : how limit the number of association between two entities in ManyToOne relation?

Time:01-30

Given a Symfony 6 sample project where I defined two entites 'A' and 'B'. The relation defined between 'A' and 'B' is a oneToMany ('A' can contains N instance of 'B')

My question : is there a simple server side way for limit the number of 'B' linked to 'A' ? (By exemple, when a user create a new 'A' through a form, he must add between 2 and 6 instances of 'B'. Outside, a pretty error occurs on its browser when he submits the form)

In a AType Class, we can use some property (but I didn't find a property for manage the allowed min and max):

$builder->add('b', CollectionType::class, [
    'entry_type'=>BType::class,
    'allow_add' => true,
    'allow_delete' => true,
    // no property finded on the symfony documentation
]);

I find some examples where code must be developed in back and front side. But I'm surprised that symfony (on its version 6) does not propose a quick way for do what I'm looking for...

Maybe I missed something somewhere in the symfony doc ?

CodePudding user response:

The Count Constraint does exactly what you want. It can be used in your Entity as follows:

// src/Entity/Participant.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class A
{
    #[Assert\Count(
        min: 2,
        max: 6,
        minMessage: 'You must add at least 2 instances of B',
        maxMessage: 'You cannot have more than {{ limit }} of B',
    )]
    protected $B = [];
}
  • Related