簡體   English   中英

Symfony 表單將變量選項從 Collection 傳遞到 FormType

[英]Symfony Form passing variable options from Collection to FormType

我有一個集合類型:

->add('tipi', CollectionType::class, array(
                'entry_type' => TipiType::class,
                'allow_add' => true,
                'prototype' => true,
                'mapped' => false,
                'entry_options' => array(
                    'required' => true,
                    'label' => false,
                )
            ))

擴展此表單類型:

->add('tipi', EntityType::class, array(
      'label' => 'Tipo',
      'class' => 'AppBundle:Tipi',
      'attr' => array('class' => 'form-control'),
      'query_builder' => function (EntityRepository $er) {
          return $er->createQueryBuilder('t')
                    ->innerJoin('t.requests', 'r')
          ;
      },
  ));

在第一個表單類型中,我有一個以這種方式從 controller 發送的選項:

$idRequest = $request->get('id');
$form = $this->createForm(RequestsType::class, $requests, array(
    'id_request' => $idRequest
));

在第一個我可以使用它,但在子 FormType 中不能。 我會在集合類型中傳遞這個變量。 我怎樣才能做到這一點?

$form = $this->createForm(new YourForm($options), $class);

在 2.7 之后的版本中,您可以使用“entry_options”屬性將您想要的變量傳遞給集合元素表單。

以下是如何操作的示例:

$form = $this->createFormBuilder()
->add('elements', CollectionType::class, [
    'entry_type' => ElementType::class,
    'entry_options' => [
        'myVariable' => $myVariable, // Pass the variable to the collection element form
    ],
    'allow_add' => true,
    'allow_delete' => true,
    'prototype' => true,
    'by_reference' => false,
])
->getForm();

然后,在集合元素表單 class(本例中為 ElementType)中,您可以使用 setDefaultOptions() 和 buildForm() 方法訪問傳遞的變量。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    // Get the passed variable
    $myVariable = $options['myVariable'];

    // Use the variable as needed
    // ...
}

public function setDefaultOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'myVariable' => null, // Set a default value for the variable
    ]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM