簡體   English   中英

Symfony數組作為表單集合

[英]Symfony array as Form Collection

我已經在Symfony中困擾了幾天了,在Google上找不到任何東西。

我有兩張桌子。

帳戶:

AppBundle\Entity\Account:
type: entity
fields:
    name:
        type: string
        nullable: true
        length: 255
oneToMany:
    towns:
        targetEntity: AppBundle\Entity\Town
        mappedBy: owner
        cascade: ['persist']

鎮:

AppBundle\Entity\Town:
type: entity
fields:
    name:
        type: string
        nullable: true
        length: 255
manyToOne:
    owner:
        targetEntity: AppBundle\Entity\Account
        inversedBy: towns

我有一個名稱數組:

$names = ['New York','Berlin'];

我想要一種表單,用戶可以在其中檢查數組中的名稱(復選框)。 當用戶選中“紐約”並提交表單時,我想要一個新的實體Townname字段中帶有“紐約”。 如果用戶取消選中“紐約”,則我希望刪除該實體。

到目前為止,我已經使用EntityTypeCollectionTypeChoiceType 我能得到的最好的是ChoiceType。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('towns', ChoiceType::class,
            [
                'choices' =>
                    [
                        new Town('New York'),
                        new Town('Berlin'),
                    ],
                'choice_label' => function (Town $town, $key, $index) {
                    return $town->getName();
                },
                'choice_value' => function (Town $town) {
                    return $town->getName();
                },
                'expanded' => TRUE,
                'multiple' => TRUE,
                'required' => FALSE,
            ]
        );
}

但是,每當用戶為任何選中的城鎮提交表單時,它將添加一個新實體,並且不會刪除未選中的城鎮...

不要使用數組,而是將城鎮存儲在數據庫中。
然后設置towns場類型EntityType

->add(
    'towns',
    EntityType::class,
    [
        'class' => Town::class,
        'multiple' => true,
        'expanded' => true,
        'required' => false,
    ]
)

將此方法添加到Town類中,以便在必須將其轉換為字符串的任何地方自動顯示名稱:

/**
 * @return string
 */
public function __toString()
{
    return $this->name;
}

如果數組的想法是過濾顯示的選擇城鎮的選項,則可以在query_builder選項中使用它:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $names = ['New York', 'Berlin']; // Or pass it from the controller in $options

    $builder
        ->add('towns',
            EntityType::class,
            [
                'class' => Town::class,
                'query_builder' => function (EntityRepository $er) use ($names) {
                    return $er->createQueryBuilder('town')
                        ->where('town.name IN (:names)')
                        ->setParameter('names', $names);
                },
                'multiple' => true,
                'expanded' => true,
                'required' => false,
            ]
        );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM