forms - 在 symfony 中为子表单添加表单域
问题描述
Symfony 4.1
这是我的个人表单类型:
class PersonalType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', TextType::class, [
'required' => true,
'attr' => [
'placeholder' => 'First name'
],
])
//......
这是我的 ClientType 使用 PersonalType 作为子表单
class ClientType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$client = $builder->getData();
$builder
->add('personalDetails', PersonalType::class, [
'data' => $client
])
//....
我已经向子表单类型添加了一个事件侦听器,但是它没有被调用,所以我将事件侦听器移到了 ClientType。
我想向 PersonalType 添加一个字段,我这样做了:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$client = $event->getData();
$form = $event->getForm();
$form->add('title', TextType::class, [
'type' => new PersonType(),
'label' => 'Title'
]
}
但我有一个错误说option "type" does not exists
我在这里想念什么?
解决方案
['type' => ...] 选项不是 Symfony 的 TextType 的有效选项。有关有效选项,请参阅此处的参考:https ://symfony.com/doc/current/reference/forms/types/text.html 。您还可以在此处查看其他内置表单类型的有效选项:https ://symfony.com/doc/current/reference/forms/types.html 。
也许您已经看到了一个自定义表单类型,它通过使用带有or的configurationOptions
方法来定义“类型”选项(参见此处:https ://symfony.com/doc/current/form/create_custom_field_type.html )。我猜这是来自您的 PersonType。TextType 不支持。setDefaults
setRequired
我不确定你到底想做什么
'type' => new PersonType(),
线。如果您只是想将“title”字段添加到您的 PersonType,并且由于某种原因您想使用事件侦听器而不是直接在 PersonType 类中执行此操作(在大多数情况下这将是最简单的选项),它感觉只是删除那条线就足以让它工作?
推荐阅读
- scala - Scala 将 Map[A, Seq[Future[Option[B]]]] 转换为 Future[Map[A, Seq[B]]]?
- python - Selenium WebDriverException
- docker - 获取“本地主机拒绝连接”。尝试访问容器化的 .netcore3.1 WeatherForecast 应用程序时
- ruby-on-rails - 将活动存储输出写入临时文件
- azure - Azure Artifacts - 需要创建组织范围的源
- javascript - 使用参数调用 PHP 中的特定函数
- excel - 应用程序定义或对象定义的错误(逗号)VBA
- c# - 有没有办法让客户端连接到现有的 WCF Web Http 服务而不使用 .Net Core 2 中的 WebHttpBinding?
- laravel - Laravel 反应认证脚手架
- regex - Laravel 中管理员和非管理员的路由区分