Symfony2:如何获取构造表单的Type

问题描述 投票:0回答:4

我正在尝试根据用户的权限动态生成我的表单,因为我创建了一个扩展,它将监听器添加到表单并相应地过滤它们的字段。这很好但是我遇到了获取typeName的问题(从getName方法实现FormTypeInterface每个字段的类(这是FormInterface)。我已经尝试了FormInterface::getName,但返回给建设者的字段名称,例如:$builder->add('fieldName',new FooType()),当我在getName上调用FormInterface时就是这样构造的我得到“fieldName”。我想要的是来自FooType::getName的返回值。我可以这样做吗?我还检查了FormInterface->getConfig->getName()但是也给了相同的Result.the侦听器的代码:

class FooListener implements EventSubscriberInterface{
public static function getSubscribedEvents()
{
    //set low priority so it's run late
    return array(
        FormEvents::PRE_SET_DATA => array('removeForbiddenFields', -50),
    );
}

public function removeForbiddenFields(FormEvent $event){

    $form = $event->getForm();

    $formName = $form->getName();/*what I want for this is to return the name of the
    type of the form.e.g: for the field that is construced with the code below 
    it must return FooType::getName*/

    $fields = $form->all();

    if($fields){
        $this->removeForbiddenFormFields($form, $formName, $fields);
    }
}
}

class barType extends AbstractType{   

public function buildForm(FormBuilderInterface $builder, array $options){
    $builder->add('fieldName',new FooType());
}
....

}
forms symfony
4个回答
1
投票

我找到了答案。

$form->getConfig()->getType()->getName();

这将返回从FooType::getName通过ResolvedTypeDataCollectorProxy类返回的名称。


1
投票

从Symfony> 2.8中取消并删除了getName()。

您现在可以使用:

   $form->get('fieldName')->getConfig()->getInnerType()

获取特定的FieldName类型。


0
投票

不确定这是你在寻找什么,这是以FormName的形式

public function __construct($permissions = null) {
    $this->permissions = $permissions;
}

这就是你创建表单的方式,而在buildForm中你可以使用if或其他一些逻辑

$myForm = $this->createForm(new FormName($user->getPermissions()));

0
投票

对于那些使用Symfony 3的人来说,现在可以通过以下方式完成:

$formClass = $form->getConfig()->getType()->getInnerType();

$formClass将是类本身的stdClass表示(虽然不是它的实例),你可以使用get_class($formClass)来获取其FQCN的字符串,例如: "App\Form\Type\SillyFormType"

我没有在Symfony 4上测试过这个,尽管它可能是相同的。

© www.soinside.com 2019 - 2024. All rights reserved.