Form Dynamic Symfony2 ManyToMany

时间:2017-01-11 11:10:04

标签: php symfony doctrine-orm

我有2个实体:公司和用户有一个链接company_user ManyToMany

我希望能够显示链接到已连接用户的公司列表。

所以我遵循了这个:http://symfony.com/doc/current/form/dynamic_form_modification.html#form-events-user-data

但是,在我的请求中,我无法显示与用户相关的公司。

这是我的CompanyRepo

 <?php

namespace BudgetBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * CompanyRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CompanyRepository extends EntityRepository
{
    public function companyByUser($user){


   return    $qb = $this->createQueryBuilder('cr')

            ->where('cr.id = :user')
            ->setParameter('user', $user);



    }
}

我的FOrmType

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


       // grab the user, do a quick sanity check that one exists
       $user = $this->tokenStorage->getToken()->getUser();
       if (!$user) {
           throw new \LogicException(
               'The FriendMessageFormType cannot be used without an authenticated user!'
           );
       }

       $builder->addEventListener(
           FormEvents::PRE_SET_DATA,
           function (FormEvent $event) use ($user) {
               $form = $event->getForm();

               $formOptions = array(
                   'class'         => Company::class,
                   'property'      => 'name',
                   'query_builder' => function (CompanyRepository $er) use ($user) {
                       // build a custom query
                       // return $er->createQueryBuilder('u')->addOrderBy('fullName', 'DESC');
               return $er->companyByUser($user);
                       // or call a method on your repository that returns the query builder
                       // the $er is an instance of your UserRepository
                       // return $er->createOrderByFullNameQueryBuilder();
                   },
               );

               // create the field, this is similar the $builder->add()
               // field name, field type, data, options
               $form->add('company', EntityType::class, $formOptions);
           }
       );
   }

我的控制器

public function addDebitAction( Request $request ) {

    $em = $this->getDoctrine()->getManager();
    $debit = new Debit();
    $form  = $this->createForm( DebitType::class, $debit );

    $amountCapital = $em->getRepository('BudgetBundle:Capital')->find($this->getUser());



    if ( $request->isMethod( 'POST' ) && $form->handleRequest( $request )->isValid() ) {

        $em = $this->getDoctrine()->getManager();
        $capital = $em->getRepository( 'BudgetBundle:Capital' )->findOneBy( [ 'user' => $this->getUser()->getId() ] );




        if ($capital == false){
            $this->get('session')->getFlashBag()->set('error', 'Vous devez avoir un capital de départ, merci d\'en ajouter un !');
            return $this->redirectToRoute('budget_add_gain');
        }



        else{

            $capital->setTotalDebits($capital->getTotalDebits() + $debit->getAmount());
            $amountCapital->setAmount($amountCapital->getAmount() - $debit->getAmount()); // MEt a jout le capital
        }



        $em = $this->getDoctrine()->getManager();
        $debit->setUser( $this->getUser() );
        $em->persist( $debit );


        $em->flush();
        $request->getSession()->getFlashBag()->add( 'success', 'Debit Added !' );

        return $this->redirectToRoute( 'budget_homepage' );

    }


    return $this->render( '@Budget/Views/company/debit.html.twig', [ 'form' => $form->createView() ] );


}

1 个答案:

答案 0 :(得分:0)

试试这个:

 public function companyByUser($user){
       return $this->createQueryBuilder('cr')
            ->innerJoin('cr.users', 'u', 'WITH', 'u = :user')
            ->setParameter('user', $user);
    }

您还需要在表单类型的查询构建器上设置choice_label。类似的东西:

choice_label => 'company_name'

我不知道您的公司和用户实体字段是什么,因此请务必使用正确的字段名称替换userscompany_name