【问题标题】:Custom nested form type easyadmin自定义嵌套表单类型 easyadmin
【发布时间】:2022-01-11 20:05:39
【问题描述】:

我有一个实体 User 和一个实体 Address,它们是 OneToOne 关系。我想在 EasyAdmin 的 User Crud 中显示地址类型,但我找不到像 Symfony ->add('address', AddressType::class) 这样的方法。 我尝试了以下选项:

CollectionField::new('address')
            ->setEntryIsComplex(true)
            ->setEntryType(AddressType::class)
            ->setFormTypeOptions([
                'by_reference' => false,
                'required' => true
            ]),

但这使得用户可以添加任意数量的地址,尽管我只想要一个。

AssociationField::new('address')->hideOnIndex()

这使用户在列表中选择现有地址。这不是表单类型的嵌入。

有人有想法吗?

【问题讨论】:

  • 尝试使用 AssociationField 而不是 CollectionField
  • 正如我在帖子中所说,AssociationField 允许用户在列表中选择现有地址。它不显示表单:/
  • 即使->setEntryType(AddressType::class)?
  • setEntryType() 对于 AssociationField 不存在
  • 对不起,这里是->setFormType()

标签: forms symfony nested embed easyadmin


【解决方案1】:

我找到的解决方法如下:

像这样创建地址字段

<?php

namespace App\Field;

use App\Form\AddressType;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\FieldTrait;

final class AddressField implements FieldInterface
{
    use FieldTrait;

    public static function new(string $propertyName, ?string $label = 'Address'): self
    {
        return (new self())
            ->setProperty($propertyName)
            ->setLabel($label)
            // this template is used in 'index' and 'detail' pages
            ->setTemplatePath('admin/field/address.html.twig')
            // this is used in 'edit' and 'new' pages to edit the field contents
            // you can use your own form types too
            ->setFormType(AddressType::class)
            ->addCssClass('field-address')
        ;
    }
}

然后在你的 User Crud Controller 中使用它

public function configureFields(string $pageName): iterable
{
  // Other fields

  yield AddressField::new('address'); // Your new address field
}

templates/admin/field/address.html.twig 模板会是这样的

{% if field.value is defined %}  
  <dl class="row justify-content-center">
    <dt class="col-3 text-right">City</dt>
    <dd class="col-9">{{ field.value.city }}</dd>
    <dt class="col-3 text-right">Address 1</dt>
    <dd class="col-9">{{ field.value.address1 }}</dd>
    <dt class="col-3 text-right">Address 2</dt>
    dd class="col-9">{{ field.value.address2 }}</dd>
  </dl>
{% endif %}

【讨论】:

  • 非常感谢,我没有想到这个解决方案!它就像一个魅力!
猜你喜欢
  • 2020-11-07
  • 2018-11-03
  • 2019-02-18
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多