Symfony 4 - 如何从Controller访问变量到FormType

时间:2018-05-18 04:41:02

标签: forms symfony variables controller access

我的ListProductsController变量$ parentId。 我想得到$ parentId值并在我的SearchProductType中使用它:

  public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('price',EntityType::class,[
            'class'=>Product::class,
            'choice_label'=>'price',
            'choice_value'=>'price',
            'placeholder'=>'Default',
            'query_builder' => function (EntityRepository $er){
                return $er->createQueryBuilder('product')
                    ->innerJoin('product.category','c')
                    ->addSelect('c')
                    ->innerJoin('product.manorwomen','m')
                    ->addSelect('m')
                    ->where('c.parent_id=1')

            },
            'expanded'=>false,
            'multiple'=>false
        ])
        ->add('submit',SubmitType::class)
    ;
}

c.parent_id必须等于来自控制器的$ parentId

->where('c.parent_id=$parentId')

怎么做?

2 个答案:

答案 0 :(得分:4)

将其作为SearchProductType表单

的必填(必填)选项
/**      
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setRequired([
        'parentId',
    ]);
}

然后在ListProductsController

中创建表单时传递它
$form = $this->createForm(SearchProductType::class, $objName,
  ['parentId' => $parentId], //or whatever the variable is called
);

最后使用它

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $parentId = $options['parentId'];
    $builder->add('price',EntityType::class,[
        [...]
        'query_builder' => function (EntityRepository $er) use ($parentId) {
                [...]
                ->where('c.parent_id=' . $parentId)

        },
    ]);
}

答案 1 :(得分:0)

你可以尝试这样吗

<强>控制器

$data = array("parentId" => $parentId));
$form = $this->createForm(new ExampleFormType($data), $objName);

<强>形式

class ExampleFormType extends AbstractType {
    public $data = array();
    public function __construct($data) {
         $this->data = $data;  // Now you can use this value while creating a form field for giving any validation.
    }
}

您可以从 $ data 数组

访问parentId