繁体   English   中英

Symfony3:将表单绑定到实体类

[英]Symfony3: Binding Form to Entity Classes

我正在使用内置的Symfony3服务创建表单:
1)在AppBundle\\Form创建扩展AbstractType新类
2)在我的控制器中创建一个表单对象(使用createForm()
3)将对象直接推到树枝层(通过createView()

在我的实体方向上,我有两个类,已经由ORM映射到数据库。 第一个是User ,第二个是UserAttribute 通过OneToMany注释, UserUserAttribute相关。 关系看起来像:


class UserAttr
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;
    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="userAttr" )
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

User端:

class User
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;
    /**
     * @ORM\OneToMany(targetEntity="UserAttr", mappedBy="user")
     * @ORM\JoinColumn(nullable=false)
     */
    private $userAttr;

当我添加新字段(使用$builder->add() )时,如果它们与User类属性相关联,则一切正常。 但是,如果我对UserAttribute属性执行相同的操作UserAttribute无法找到该属性的get / set方法。 我知道-我可以通过class User extends UserAttribute来修复它,但这可能不是重点。 Symfony必须为此提供另一种解决方案,可能我错过了一些东西。

谢谢你的时间 !

// SOLVED | there should be defined an EntityClassType as below:
$builder->add('credit',EntityType::class,array(
                'class' => UserAttr::class
            ));

您具有从User实体到UserAttr One-To-Many关联。 因此,一个用户可能有多个积分。

选项1 :

考虑到这一点,您必须在UserFormType中使用一个collection字段类型,这是一个冗长的过程。

$builder->add('userAttr', CollectionType::class, array(
    'label' => false,
    'allow_add' => true,
    'allow_delete' => true,
    'entry_type' => UserAttrType::class
));

然后创建另一个FormType: UserAttrType来表示UserAttr ,您可以在其中将credit字段作为UserAttr的属性。

$builder
    ->add('credit', TextType::class, array(
        'label' => 'Credit',
    ))

这样,表单将相应地加载并提交,当用户表单被更新时,信用额度也将被更新。 这是收藏文档的链接。 这就是嵌入收集表格的方法

选项2:

但是,如果您想进一步简化它,请在credit字段中添加mapped = falsedoc )。 这将忽略当前错误。 但是,您必须手动从Form对象收集credit值,并将其值设置为“提交处理程序”中的相应UserAttr对象。

希望能帮助到你!

暂无
暂无

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

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