我有一個物體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()
這使用戶在串列中選擇現有地址。那不是表單型別的嵌入。
有沒有人有想法?
uj5u.com熱心網友回復:
我找到的解決方案如下:
像這樣創建地址欄位
<?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 %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380552.html
