简体   繁体   中英

Symfony3: form: populate select with related model entries

I have two models, topic and user . Both are related by many-to-one relationship (a topic is defined by only one user) such as:

class User
{
    private $idUser;
    private $username;
}


class Topic
{
    private $idTopic;
    private $topicName;

    private $idUser;
}

MAIN CONCERN : I would like (using symfony-forms) to create a creation form for the topic model. The form would contain:

  1. a topic name input
  2. a user select (list populated by the existing users in the database. The displayed value would be the username of course).

I have created a TopicType class that will build the topic creation form:

class TopicType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->
            ->add('topicName')
            ->add(/* 'idUser', 'choice',  'THE USER LIST ???*/)
    }

    public function configureOptions(FormBuilderInterface $builder, array $options)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Topic'
    ));
    }

}
  • How can I retrieve the list of users and populate the choices considering I don't have access to the entity manager in TopicType context?
  • Could I pass a $users array in the controller as a parameter when invoking createForm method ? If so, how ?
  • If you understood what I'm trying to do, Is there a better/simplier way to get it done ? Am I missing something ?

I know this question might look similar but all the solutions I found on related topics are somehow deprecated in Symfony3

Any help would be much appreciated. Have a good day to you all.

you should try something like this (you must adapt the code):

  ->add('User', EntityType::class, array(
    'class'    => 'xxxBundle\Entity\User',
    'choice_label' => 'username',
    'required' => true,
    'multiple' => false,
  ))

do not forget :

use Symfony\Bridge\Doctrine\Form\Type\EntityType;

More info here : http://symfony.com/doc/current/reference/forms/types/entity.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM