簡體   English   中英

Symfony2 FormType實體字段類型

[英]Symfony2 FormType entity field type

我有三個實體。 ProfileCarTrip 當用戶( Profile )創建Trip ,他可以選擇Car (僅自己的)並將其分配給Trip 我知道該字段必須是實體類型。 但是我不知道如何設置選擇列出當前用戶的汽車(配置文件)。 有任何想法嗎? 謝謝。

按用戶篩選汽車,我認為這個例子是您需要的:

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

您可以將$ userId添加為一種表單選項:

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

並在您的表單中檢索它:

/**
 * @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'];
    }
 }

我怎么說 其他解決方案,即使是我個人也不喜歡:

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

並將其存儲在受保護的變量中,以供以后在查詢中使用:

/**
 * 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