Form Builder - Attribut d'une entité référencée

Par Twentyfour, il y a 8 ans


Bonjour,

Quelqu'un saurait comment on peut passer du code actuel au code souhaité avec le Form Builder de Symfony 4 ?

Merci d'avance

Ce que j'ai

# Modèle conceptuel Client : Entity - prenom : string - nom : string - rue : string - npa : string // Code postal d'une région - localite : string # Symfony $form = $this->createFormBuilder($client) ->add('rue', TextType::class) ->add('npa', TextType::class) ->add('localite', TextType::class) ->getForm();

Ce que je veux

# Modèle conceptuel Client : Entity - prenom : string - nom : string - rue : string - domicile : Region // Clé étrangère de ma table Regions Region : Entity - npa : string // Code postal d'une région - localite : string # Symfony $form = $this->createFormBuilder($client) ->add('rue', TextType::class) ->add('domicile.npa', TextType::class) ->add('domicile.localite', TextType::class) ->getForm();

1 réponse

Twentyfour, il y a 8 ans

Finalement trouvé dans la documentation officielle

# Symfony use Doctrine\ORM\EntityRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... $form = $this->createFormBuilder($client) ->add('rue', TextType::class) ->add('region', EntityType::class, [ 'class' => Region::class, 'choice_label' => function ($region) { return $region->getNpa() . ' ' . $region->getLocalite(); }, 'choice_value' => function ($entity = null) { return $entity ? $entity->getId() : ''; }, 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('r')->orderBy('r.npa', 'ASC'); } ]) ->getForm();

Prendre en compte le changement d'appel du champs dans Twig

# Twig {{ form_widget(form_client.region) }}