簡體   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