我有一些表格类型。然后我正在创建形式,例如。像这样:
$application = new \AppBundle\Entity\Application();
$applicationWidgetForm = $this->formFactory->create(\AppBundle\Form\WidgetApplicationType::class, $application);
在树枝上,我正在使用
{% form_theme applicationWidgetForm 'form.html.twig' %}
在这个表单主题中,我想获取属性名称和实体名称。我可以获得这样的属性名称(例如,在{%block form_widget%}中):
{{ form.vars.name }}
但我无法弄清楚如何获取映射的实体名称。在这种情况下,我只想在此表单主题中获得类似\AppBundle\Entity\Application() or AppBundle:Application
的内容(用作数据属性)。
是否可以通过某种方式获得此值?是的,我可以在每个FormType等中设置它。但我正在寻找更优雅的方式。
谢谢答案!
编辑:整个代码就像这样
控制器
$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(),
]);
形式/ application_detail.html.twig
{% form_theme applicationForm 'form.html.twig' %}
{{ form(applicationForm) }}
form.html.twig
{% block form_widget %}
{{ form.vars.name }} # with this, I can get property name. But what about entity name / class?
{% endblock form_widget %}
答案 0 :(得分:0)
你是否通过树枝模板传递了你的实体?渲染Twig模板时,可以将变量传递给View。在您的控制器中:
return $this->render('your_own.html.twig', [
'entity' => $application,
]);
但请注意您的实体是空的。也许你想渲染表单而不是实体?比你需要将表单传递给视图
return $this->render('your_own.html.twig', [
'form' => $applicationWidgetForm->createView(),
]);
和render the form在你看来。
答案 1 :(得分:0)
最终我使用TypeExtension
完成了它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;
}
}
}
}