简体   繁体   English

Symfony2 FormType实体字段类型

[英]Symfony2 FormType entity field type

I have three entity. 我有三个实体。 Profile , Car and Trip . ProfileCarTrip When user( Profile ) create Trip , he can chose the Car (only his own) and assign it to the Trip . 当用户( Profile )创建Trip ,他可以选择Car (仅自己的)并将其分配给Trip I know the field must be the entity type. 我知道该字段必须是实体类型。 But I dont know how I can set to chose list a cars of current user(Profile). 但是我不知道如何设置选择列出当前用户的汽车(配置文件)。 Any ideas? 有任何想法吗? Thanks. 谢谢。

Filter the cars by user, I think this example is what you need: 按用户筛选汽车,我认为这个例子是您需要的:

$builder->add('car', 'entity', array(
    'class'         => '/path/to/entity/Car',
    'property'      => 'title',
    'empty_value'   => 'Choose a car',
    'query_builder' => function(EntityRepository $em) use ($userId) {
         return $em->createQueryBuilder('c')
             ->join('c.user', 'u')
             ->where('u.id = :userId')
             ->setParameter('userId', $userId);
         }
    )
)

You can add $userId as one form option: 您可以将$ userId添加为一种表单选项:

$form = $this->createForm(new MyFormType(), $object, array( 'userId' => $userId ));

And inside your form retrieve it: 并在您的表单中检索它:

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'userId' => function (Options $options, $value) {
            return $options['userId'];
        }
    ));
}

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    if($options['userId']){
        $userId = $options['userId'];
    }
 }

How I mentioned. 我怎么说 other solution, even personally I don't prefer it: 其他解决方案,即使是我个人也不喜欢:

$form = $this->createForm(new MyFormType($userId), $object); 

And in your form, store it in a protected variable to be used later in your query: 并将其存储在受保护的变量中,以供以后在查询中使用:

/**
 * Class MyFormType
 */
 class MyFormType extends AbstractType
 {

     protected $userId;

     /**
      * @param $userId
      */
     public function __construct($userId) {
         $this->userId = $userId;
     }

 }

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

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