user3672853
user3672853

Reputation:

Assign filtered list of entities to Entity field in Symfony2 form

I have a little problem in my Symfony form.

This is my code:

  class ProfileFormType extends AbstractType
  {
     /**
      * @param FormBuilderInterface $builder
      * @param array $options
    */
     public function buildForm(FormBuilderInterface $builder, array      $options)
{

    $builder->add('adress',null,array('label' => 'form.adress', 'translation_domain' => 'FOSUserBundle'))

        ->add('niveau','entity',array(
                'class'=>'EnsajAdministrationBundle:Niveau',
                'property'=>'libelle'
            ,'multiple'=>false)
        )

The problem is that normally it returns all rows for the named Entity, but I want to return just the 2 first rows from the "niveau" ("level") table, to be used as the choices for my form.

What is the solution for this problem?

Upvotes: 2

Views: 140

Answers (1)

frumious
frumious

Reputation: 1575

You have (at least) a couple of options here, but the obvious one is to supply a QueryBuilder to the field which provides the required rows (see Symfony docs on EntityType Field)

E.g.

//Create function which accepts EntityRepository and returns required QueryBuilder
$qbFunction = function(EntityRepository $er) {
    return $er->createQueryBuilder('n')
        //->orderBy() //If you need to, to get the correct 2 rows!
        ->setMaxResults(2); //Just two rows
};

$builder->add('adress',null,array('label' => 'form.adress', 'translation_domain' => 'FOSUserBundle'))

        ->add('niveau','entity',array(
                'class'=>'EnsajAdministrationBundle:Niveau',
                'property'=>'libelle'
            ,'multiple'=>false
            ,'query_builder' => $qbFunction) //give function to field
        )

You can make the query more complex if you need to, e.g. add joins

Upvotes: 2

Related Questions