覆盖子表单symfony中的父表单标签

时间:2017-03-03 16:02:09

标签: symfony symfony-forms

我的父表单类型有一个字段“title”,带有通用标签“Title”。 假设我有五个子表单,其中三个需要更改标签。我怎么做。我疯了。

class ParentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', TextType::class, [
            'label' => 'generics.title',
        ]);
    }
}

class ChildType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // I thought I could change the label of parent around here
        // without removing and adding it again

        $builder->add('description', TextareaType::class, [
            'label' => 'generics.description',
        ]);
    }

    public function getParent()
    {
        return ParentType::class;
    }
}

我不想在树枝上解决这个问题。

如何在ParentType中添加自定义titleLabel选项并在子配置configureOptions()方法中进行设置?

1 个答案:

答案 0 :(得分:0)

您可以使用“模板方法模式”。 在ParentType中编写名为 getTitle 的模板方法。 并指定此方法调用作为标签选项。

protected function getTitle() 
{
    return 'generics.title'
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
   $builder->add('title', TextType::class, [
       'label' => $this->getTitle(),
   ]);
}

从ParentType派生ChildType并在ChildType中编写具体的 getTitle

class ChildType extends ParentType {
    protected function getTitle() 
    {
      return 'concrete label';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder->add('description', TextareaType::class, [
        'label' => 'generics.description',
        ]);
    }
}
相关问题