简体   繁体   English

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

[英]Load options into drop down on a form based on user's id in symfony 2

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. 我有一个系统,用户可以将壁虎添加到数据库中,添加壁虎后,它将用户ID保存到名为user_id的列中-这很完美,并为我现在想要实现的目标做好了准备。

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. 我有一个系统,用户可以为该壁虎添加重量条目,问题是,现在它仅加载数据库中的每个壁虎,而不是特定于该用户的壁虎。

Here is a portion from my Weight.php entity: 这是我的Weight.php实体的一部分:

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

Which is linked to this part in the Gecko.php : 链接到Gecko.php这一部分:

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

And here is the user part inside Gecko.php entity which links the current user's id to save to the database: 这是Gecko.php实体内的用户部分,它链接当前用户的ID以保存到数据库:

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

And the linked part in the User.php entity: 以及User.php实体中的链接部分:

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

Now, here is my Weight entities Form ( WeightType.php ): 现在,这是我的Weight实体FormWeightType.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: 根据上面的部分,您会得到一个下拉列表,如下所示: 重量输入表

So what i am now trying to achieve is to ONLY show the geckos that are linked with the current user's ID. 因此,我现在试图实现的是仅显示与当前用户ID链接的壁虎。 What is the best way to achieve this? 实现此目标的最佳方法是什么?

Thanks in advance :) 提前致谢 :)

Andy 安迪

EDIT: 编辑:

Here is my WeightType file: 这是我的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';
    }
}

EDIT 2: Here is my create form snippet: 编辑2:这是我的创建表单片段:

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;
    }

You must use entity Field Type + query_build option. 您必须使用实体字段类型 + query_build选项。 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);
            },
        ));
    }    
}

On the controller... 在控制器上...

<?php 
//...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM