gpt4 book ai didi

forms - Symfony2 : how to get the Type that a form is constructed from

转载 作者:行者123 更新时间:2023-12-05 02:23:01 24 4
gpt4 key购买 nike

我正在尝试根据用户的权限动态生成我的表单,因为我创建了一个扩展程序,它将监听器添加到表单并相应地过滤它们的字段。这工作得很好但是我在获取 typeName (从实现每个字段(FormInterface)的 FormTypeInterface 的类的 getName 方法返回。我试过 FormInterface::getName 但它会返回给构建器的字段名称,例如:$builder->add('fieldName',new FooType()) 当我调用 getName 在这样构造的 FormInterface 上我得到“fieldName”。我想要的是 FooType::getName 的返回值。我该怎么做?我还检查了 FormInterface->getConfig->getName() 但它也给出了相同的结果。监听器的代码:

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());
}
....

}

最佳答案

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

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

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

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

关于forms - Symfony2 : how to get the Type that a form is constructed from,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com