duanpei8518 2014-11-23 13:52
浏览 11

Symfony2 / Twig:如何将允许的值设置为dropDownField

I have 3 Entities: User , Report and ReportCategory. A User can put Reports in ONE ReportCategory. In the User-Entity there is a list, which ReportCategories are allowed for the user. This works all fine - I made it with a connectionTable which has the userID and the reportCategoryId.

Now I make an Array in Controller to get all ReportCategories of the current logged in User:

public function newAction()
    {
        $entity = new Report();
        $form   = $this->createCreateForm($entity);

        $userId = $this->get('security.context')->getToken()->getUser()->getId();
        $user = $this->getDoctrine()->getRepository('MyBundle:User')->find($userId);
        $userReportCategories = array();

        foreach($user->getReportCategories() as $reportCategory)
        {
            $userReportCategories[] = $reportCategory->getId();
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'userReportCategories' => $userReportCategories
        );
    }

How can I set only these Values to my twig template field? When I make an own field it is not managed form Doctrine!

{{ form_row(form.reportCategory, {'attr': {'class': 'form-control'}, 'label': 'Category'}) }}

THANKS FOR ANY HELP!!!

UPDATE: My ReportType looks like this:

class ReportType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('reportCategory')
            ->add('creationDate', 'date', array(
                'data' => new \DateTime()
            ))
            ->add('headline')
            ->add('text')
            ->add('user')

        ;
    }
....
  • 写回答

1条回答 默认 最新

  • dragon012100 2014-11-23 14:54
    关注

    Create a form class and add an event listener so that the form is aware of the user. The following is an adaptation of How to dynamically Generate Forms Based on user Data in the Symfony docs. [It is not guaranteed to accurately capture your needs].

    form class

    use Symfony\Component\Security\Core\SecurityContext;
    use Doctrine\ORM\EntityRepository;
    // ...
    
    class ReportFormType extends AbstractType
    {
        private $securityContext;
    
        public function __construct(SecurityContext $securityContext)
        {
            $this->securityContext = $securityContext;
        }
    
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
    
    
            // grab the user, do a quick sanity check that one exists
            $user = $this->securityContext->getToken()->getUser();
            if (!$user) {
                throw new \LogicException(
                    'The ReportFormType cannot be used without an authenticated user!'
                );
            }
    
            $builder->addEventListener(
                FormEvents::PRE_SET_DATA,
                function (FormEvent $event) use ($user) {
                    $form = $event->getForm();
    
                    $formOptions = array(
                        'class' => 'Acme\DemoBundle\Entity\ReportCategory',
                        'property' => 'category',
                        'query_builder' => function (EntityRepository $er) use ($user) {
                            // build a custom query
                            // return $er->createQueryBuilder('c')
                            ->select('category')
                            ->where('user = $user);
                        },
                    );
    
                    // create the field, this is similar the $builder->add()
                    // field name, field type, data, options
                    $form->add('userReportCategories', 'entity', $formOptions);
                }
            );
        }
    
        // ...
    }
    

    new action

    public function newAction()
        {
            $entity = new Report();
            $form   = $this->createForm(new ReportFormType(), $entity);
    
            return array(
                'entity' => $entity,
                'form'   => $form->createView(),
            );
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。