【问题标题】:Symfony3: is it possible to change the name of a form?Symfony3:是否可以更改表单的名称?
【发布时间】:2016-08-28 14:28:13
【问题描述】:

使用 Symfony 2.7,您可以使用 getName() 方法在 EntityType 类中自定义表单的名称
现在已弃用。 Symfony 3.0 还有其他方法吗?
我有自定义原型 entry_rows 用于我需要以不同形式使用的集合。
由于行的名称基于表单的名称,因此我需要更改后者以便将它们与不同的表单一起使用。

【问题讨论】:

  • 我认为依赖自定义表单名称不是一个好主意。为什么你不能改变你的收藏?我经常使用集合,但我没有遇到这个问题。
  • @StephanVierkant 为什么这是个坏主意?如果您知道它可能导致的某些问题,请告诉我,因为我将使用 Matteo 的答案。我不想更改我的收藏,因为我有两个表单:formA 和 myCollection 字段,formB 也有 myCollection 字段。所以在我的原型自定义表单中,如果我写一个像_formA_myCollection_entry_row这样的块,当我调用我的formB时它不会被识别,因为这次它会被称为_formB_myCollection_entry_row。希望我很清楚......

标签: php forms symfony symfony-forms


【解决方案1】:

您应该实现getBlockPrefix 方法,而不是迁移指南here 中所述的getName

例如:

/**
 * Returns the prefix of the template block name for this type.
 *
 * The block prefix defaults to the underscored short class name with
 * the "Type" suffix removed (e.g. "UserProfileType" => "user_profile").
 *
 * @return string The prefix of the template block name
 */
public function getBlockPrefix()
{
    return "form_name";
}

希望有帮助

【讨论】:

  • 这正是我所需要的!你解决了我的问题!我不知道表单名称现在称为blockPrefix,这是我在官方文档中没有找到的。感谢您提供迁移指南链接,下次我在寻找 3.0 之前的功能时会尝试查看它。
【解决方案2】:

根据表单的构建方式,设置表单名称的方法有多种。

如果您是通过$this->createForm(CustomType::class) 创建表单:

$formFactory = $this->get('form.factory');
$form = $formFactory->createNamed('custom_form_name', CustomType::class);

如果你是直接通过$this->createFormBuilder()从控制器构建表单:

$formFactory = $this->get('form.factory');
$form = $formFactory->createNamedBuilder('custom_form_name', CustomType::class);

查看FormFactoryFormBuilder API 了解更多信息。

【讨论】:

  • 感谢您的回答,我选择了 Matteo's,因为它更适合我的特殊需求,但我相信您的答案对其他人会有所帮助。
  • @Roubi 你是完全正确的,它完全符合你的问题
  • 感谢您的回答。我在一个页面上重复使用相同的排序通用表单三次,并且需要一种方法来为字段设置唯一 ID。这种方法非常适合。
【解决方案3】:

你可以试试,去掉字段名前缀

public function getBlockPrefix()
{
    return null;
}

【讨论】:

    猜你喜欢
    • 2012-07-03
    • 2011-01-21
    • 2018-10-12
    • 2019-06-28
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多