how to call function of entity repository in form type in symfony2

Rajesh Vasani picture Rajesh Vasani · May 21, 2013 · Viewed 10.5k times · Source

i want to call function in form type class. function generate array and is written in entity repository class. using that array i will generate dynamic form field. here is entity repository class function.

public static $roleNameMap = array(
            self::ROLE_SUPER_ADMIN => 'superAdmin',
            self::ROLE_MANAGEMEN => 'management',
            self::ROLE_MANAGERS => 'manager',
            self::ROLE_IT_STAFF => 'itStaff',
            self::ROLE_CS_CUSTOMER => 'csCustomer',
            self::ROLE_CS => 'cs',
            self::ROLE_DEALER => 'dealer',
            self::ROLE_ACCOUNT_STAFF => 'accountStaff',
            self::ROLE_BROKER_USER => 'staff',
    );

    public function getGroupListArray()
        {
            $qb = $this->createQueryBuilder('g')
                ->orderBy('g.hierarchy','ASC');
            $query = $qb->getQuery();
            $groupList = $query->execute();
            $roleNameMap = array();
            foreach ($groupList as $role){
                $roleNameMap[$role->getId()] = $role->getRole();
            }

            return $roleNameMap;
        }

below is my form builder class where i want to call above entity repository function.

public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder->add('routeId', 'hidden');

        foreach (GroupListRepository::$roleNameMap as $key=>$value){
            $builder->add($value, 'checkbox',array('label' => '', 'required' => false,));
        }       
    }

i am able to get static variable as show in above code but, i have confusion that how should i access repository function in form builder class in symfony2.

thanks in advance.

Answer

Ryan picture Ryan · May 21, 2013

It's not available in the form builder, and it's normally not necessary. It's also not really how Symfony forms work. For what it looks like you're wanting to do, you could try something like this. It will create a list of checkboxes corresponding to a list of roles.

$builder->add(
  'roles',
  'entity',
  array(
    'class' => 'Acme\DefaultBundle\Entity\Group',
    'expanded' => true,
    'multiple' => true,
    'property' => 'role', // Or use __toString()
    'query_builder' => function ($repository) {
      return $repository->createQueryBuilder('g')
        ->orderBy('g.hierarchy', 'ASC');
    }            
  )
);

See http://symfony.com/doc/master/reference/forms/types/entity.html.

If you really need the repository in the form builder, then create the form type as a service and inject the entity manager with the DIC. Or just pass it directly into the form type when you create it.