Symfony get entity name in twig form theme
我有一些表单类型。然后我正在创建表单,例如。像这样:
1 2 | $application = new \\AppBundle\\Entity\\Application(); $applicationWidgetForm = $this->formFactory->create(\\AppBundle\\Form\\WidgetApplicationType::class, $application); |
在树枝中,我正在使用
1 | {% form_theme applicationWidgetForm 'form.html.twig' %} |
在这个表单主题中,我想获取属性名称和实体名称。我可以得到这样的属性名称(例如在 {% block form_widget %} 中):
1 | {{ form.vars.name }} |
但我不知道如何获取映射的实体名称。在这种情况下,我只想在这个表单主题中得到类似
是否有可能以某种通用方式获得此值?是的,我可以在每个 FormType 等中设置它。但我正在寻找更优雅的方式。
谢谢解答!
编辑:整个代码是这样的
控制器
1 2 3 4 5 | $application = new \\AppBundle\\Entity\\Application(); $applicationWidgetForm = $this->formFactory->create(\\AppBundle\\Form\\WidgetApplicationType::class, $application); return $this->render('form/application_detail.html.twig', [ 'applicationForm' => $applicationWidgetForm->createView(), ]); |
form/application_detail.html.twig
1 2 | {% form_theme applicationForm 'form.html.twig' %} {{ form(applicationForm) }} |
form.html.twig
1 2 3 | {% block form_widget %} {{ form.vars.name }} # with this, I can get property name. But what about entity name / class? {% endblock form_widget %} |
最终我使用 TypeExtension
做到了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class TextTypeExtension extends AbstractTypeExtension { /** * Returns the name of the type being extended. * * @return string The name of the type being extended */ public function getExtendedType() { return TextType::class; } public function buildView(\\Symfony\\Component\\Form\\FormView $view, \\Symfony\\Component\\Form\\FormInterface $form, array $options) { $propertyName = $view->vars['name']; $entity = $form->getParent()->getData(); $validationGroups = $form->getParent()->getConfig()->getOption('validation_groups'); if ($entity) { if (is_object($entity)) { $entityName = get_class($entity); //full entity name $entityNameArr = explode('\\\', $entityName); $view->vars['attr']['data-validation-groups'] = serialize($validationGroups); $view->vars['attr']['data-entity-name'] = array_pop($entityNameArr); $view->vars['attr']['data-property-name'] = $propertyName; } } } } |
您是否在树枝模板中传递了您的实体?当您渲染 Twig 模板时,您可以将变量传递给 View。在您的控制器中:
1 2 3 | return $this->render('your_own.html.twig', [ 'entity' => $application, ]); |
但请注意,您的实体是空的。也许您想呈现形式而不是实体?比您需要将表单传递给视图
1 2 3 | return $this->render('your_own.html.twig', [ 'form' => $applicationWidgetForm->createView(), ]); |
并在您的视图中呈现表单。