有没有办法检索传递给FormBuilder
的初始选项以创建表单?我知道FormConfigInterface
有方法getOptions()
,但我已经使用了它并获得了表单的已解析选项,例如:在规范化之后。
那么如何才能获得用户传递的原始选项?
//by options, I mean the $options passed here
$formFactory->create('form_name', 'form_type', $options);
然后我希望稍后访问$ options并注册到此表单的EventListener
:
//.. in a form EventListener e.g: on preSubmit
$form = $event->getForm();
$options = $form-> ? //this is where I want to get $options that was passed above during the form's creation.
答案 0 :(得分:2)
要使用当前的Form Component实现它是非常复杂的,您需要复制ResolvedTypeDataCollectorProxy
的行为才能在解析后获得“传递的选项”。
我建议你回到简单的方法:定义一个自定义表单选项来传递初始选项。
class CustomFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->setAttribute('initial_options', $options['initial']);
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
// do something with:
$event->getForm()->getConfig()->getAttribute('initial_options');
});
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'initial' => null,
]);
}
}
因此,您也将“初始”选项也传递给表单类型选项。像这样:
$options['initial'] = $options;
$formFactory->create('form_name', CustomFormType::class, $options);
答案 1 :(得分:0)
在表单类中,您可以添加以下属性和getter:
private $defaultOptions;
public function getDefaultOptions() {
return $this->defaultOptions;
}
并且,在buildForm
:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->defaultOptions = $options;
//...
}
最后,在EventListener中:
//.. in a form EventListener e.g: on preSubmit
$form = $event->getForm();
$options = $form->getDefaultOptions();