0
votes

I've got some form type. Then I'm creating form eg. like this:

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

In twig, I am using

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

In this form theme, I want to get property name and entity name. I can get property name like this (eg. in {% block form_widget %}) :

{{ form.vars.name }}

But I can't figure out how to get mapped entity name. In this case, I just want to get something like \AppBundle\Entity\Application() or AppBundle:Application in this form theme (for using as data attribute).

Is it possible to get this value in some general way? Yes, I can set it in each FormType etc. But I am searching for more elegant way.

Thx for answers!


EDIT: whole code is something like this

controller

$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

 {% 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 %}
2

2 Answers

0
votes

Have you passed your entity in twig template? When you rendered Twig template you could pass variables to View. In your controller:

return $this->render('your_own.html.twig', [
    'entity' => $application,
]);

But note your entity is empty. Perhaps you want to render form instead of entity? Than you need to pass form into view

return $this->render('your_own.html.twig', [
    'form' => $applicationWidgetForm->createView(),
]);

and render the form in your view.

0
votes

Eventually I did it using 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;
        }
    }
}

}