2017-02-22 63 views
0

我有一些表单类型。然后我创建表单,例如。像这样:Symfony以树枝形式主题获取实体名称

$application = new \AppBundle\Entity\Application(); 
$applicationWidgetForm = $this->formFactory->create(\AppBundle\Form\WidgetApplicationType::class, $application); 

在树枝,我使用

{% form_theme applicationWidgetForm 'form.html.twig' %} 

在这种形式的主题,我想获得属性名和实体名称。我能得到的属性名这样的(例如{%块form_widget%}):

{{ form.vars.name }} 

但我无法弄清楚如何获得映射实体名称。在这种情况下,我只想在这个表单主题中获得类似\AppBundle\Entity\Application() or AppBundle:Application的东西(用作数据属性)。

是否有可能以某种常规方式获取此值?是的,我可以在每个FormType中设置它,但我正在寻找更优雅的方式。

Thx for answers!


编辑:整个代码是这样

控制器

$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

最终我做到了使用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; 
     } 
    } 
} 

} 
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在您的看法。

+0

我没有提供完整的代码。我想在form_theme中获得实体名称,因此我认为,很明显我也在使用{{form(applicationWidgetForm)}}。 这就是为什么我写我使用{%form_theme applicationWidgetForm'form.html.twig'%}。没有“形式”功能,这将是无用的... –