根据 symfony 2 中的用户 ID 将选项加载到表单的下拉列表中

根据 symfony 2 中的用户 ID 将选项加载到表单的下拉列表中

问题描述:

我有一个问题要问你,为了让你了解我在做什么,我会尝试解释这个想法.我有一个系统,用户可以在其中将壁虎添加到数据库中,当添加壁虎时,它会将用户 ID 保存到名为 user_id 的列中 - 这非常有效,并为我做好了准备努力实现现在.

I have a question for you and to give you some idea of what i'm doing, i will try and explain the idea. I have a system where user's are able to add geckos to a database, when that gecko is added, it saves the user id into a column called user_id - this works perfect and sets me up for what i am trying to achieve now.

我有一个系统,用户可以为该壁虎添加体重条目,问题是,现在它只加载数据库中的每个壁虎,而不是特定于该用户的壁虎.

I have a system where user's are able to add weight entries for that gecko, problem is, right now it just loads every gecko in the database, not the one's that are specific to that user.

这是我的 Weight.php 实体的一部分:

Here is a portion from my Weight.php entity:

/**
 * @ORM\ManyToOne(targetEntity="Gecko", inversedBy="weights")
 * @ORM\JoinColumn(name="gecko_id", referencedColumnName="id")
 */
private $geckoId;

Gecko.php中链接到这部分:

/**
 * @ORM\OneToMany(targetEntity="Weight", mappedBy="geckoId", cascade={"persist", "remove"})
*/
private $weights;

这里是 Gecko.php 实体中的用户部分,它链接当前用户的 ID 以保存到数据库:

And here is the user part inside Gecko.php entity which links the current user's id to save to the database:

/**
 * @ORM\ManyToOne(targetEntity="Breedr\UserBundle\Entity\User", inversedBy="geckos")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

以及User.php实体中的链接部分:

And the linked part in the User.php entity:

/**
 * @ORM\OneToMany(targetEntity="Breedr\GeckoBundle\Entity\Gecko", mappedBy="user", cascade={"persist", "remove"})
 */
protected $geckos;

现在,这是我的 Weight 实体 Form (WeightType.php):

Now, here is my Weight entities Form (WeightType.php):

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('weighedDate')
        ->add('weight')
        ->add('geckoId')
    ;
}

根据上面的部分为您提供一个下拉菜单,如下所示:

Which gives you a drop down based on the parts above that look like this:

所以我现在想要实现的是只显示与当前用户 ID 相关联的壁虎.实现这一目标的最佳方法是什么?

So what i am now trying to achieve is to ONLY show the geckos that are linked with the current user's ID. What is the best way to achieve this?

提前致谢:)

安迪

这是我的 WeightType 文件:

<?php

namespace Breedr\GeckoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class WeightType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('weighedDate')
            ->add('weight')
            ->add('geckoId')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Breedr\GeckoBundle\Entity\Weight'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'breedr_geckobundle_weight';
    }
}

编辑 2:这是我的创建表单片段:

EDIT 2: Here is my create form snippet:

private function createCreateForm(Weight $entity)
    {
        $form = $this->createForm(new WeightType(), $entity, array(
            'action' => $this->generateUrl('weight_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

您必须使用 实体字段类型 + query_build 选项.因此,您可以构建自定义查询以过滤结果,例如:

You must use entity Field Type + query_build option. Thus You can build a custom query in order to filter the results, for instance:

<?php 
namespace AppBundle\Form\Type;

use Doctrine\ORM\EntityRepository;
// ...

$builder->add('users', 'entity', array(
    'class' => 'AcmeHelloBundle:User',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('u')
            ->orderBy('u.username', 'ASC');
    },
));

在您的特定情况下,您的表单类型可能如下所示:

On your specific case your form type might looks like something like this:

<?php 
# maybe you need to fix some namespaces...

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class WeightType extends AbstractType
{

     /** @var int */
    protected $currentUserId;

    /**
     * param int $currentUserId It can be passed from controller 
     * when creating form instance
     */
    public function __construct($currentUserId)
    {
        $this->currentUserId = $currentUserId;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $id = $this->currentUserId;

        $builder->add('users', 'entity', array(
            'class' => 'GeckoBundle:Gecko',
            'query_builder' => function (EntityRepository $er) use ($id) {
                return $er->createQueryBuilder('g')
                    ->where('user_id = ?')                  
                    ->setParameter(0, $id);
            },
        ));
    }    
}

在控制器上...

<?php 
//...

public function add()
{
   $currentUserId = $this->getUser()->getId(); # may be it...
   $form = $this->createForm(new WeigthType($currentUserId));
}