简体   繁体   English

Symfony3:形式:使用相关模型条目填充选择

[英]Symfony3: form: populate select with related model entries

I have two models, topic and user . 我有两个模型, topicuser 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. 主要关注点 :我想(使用symfony形式)为主题模型创建一个创建形式。 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: 我创建了一个TopicType类,它将构建主题创建表单:

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? 考虑到我无法在TopicType上下文中访问实体管理器 ,我如何检索用户列表并填充选择?
  • Could I pass a $users array in the controller as a parameter when invoking createForm method ? 调用createForm方法时,可以在控制器中传递$users数组作为参数吗? 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 我知道这个问题看起来很相似,但是我在相关主题中找到的所有解决方案在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 此处提供更多信息: http : //symfony.com/doc/current/reference/forms/types/entity.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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