1

编辑。总结:我只想要 SomeForm 将我的 DoctrineForms 扩展为不包括某些字段。它们不可编辑。我想在代码中某处设置的固定值。希望这应该是足够的信息,你不需要阅读这篇文章的其余部分......

你好呀。这是我的情况:

  • 我有由学说生成的 SomeModel
  • 我的前端和后端应用程序中都有这个模型的 CRUD 屏幕
  • 这两个 CRUD 屏幕之间的唯一区别(除了审美差异)是在前端,一个特定的字段是 FIXED。即管理员可以根据需要更改该值,但普通用户不能。该值将只是我在代码中定义的常量。此字段不应显示在前端添加/编辑屏幕中。

我想知道的是,这样做的“正确”方法是什么?我可以想出几种方法来破解它,但无论我做什么都感觉像是一个尴尬的解决方法。

有没有合适的方法来扩展我的表单类(BaseFormDoctrine)或其他合适的地方?

编辑:正如下面评论中所指出的,我实际上使用的是与“CRUD”不同的学说:生成模块。

另外:虽然我还没有理想地解决这个问题,但我想我知道解决方案在哪里,我只需要更深入地研究 symfony 表单: http ://www.symfony-project.org/forms/1_4/en/02 -表单验证

4

1 回答 1

3

在您的 /lib/form 文件夹中创建另一个表单来扩展您的正常表单,然后覆盖相应的字段。以下将从表单中删除该字段,使其根本不显示。

<?php

class FrontendSomeModelForm extends SomeModelForm {

  public function configure()
  {
    unset($this["some_field"]);
  }

}

或者,如果您想要呈现该值,但不允许对其进行编辑,您可以执行以下操作:

<?php

class FrontendSomeModelForm extends SomeModelForm {

  public function configure()
  {
    $this->setWidget("some_field", new sfWidgetFormPlain());
  }

}

然后创建一个sfWidgetFormPlain只输出值的小部件并将其粘贴到 symfony 可以找到它的地方(lib/form/widget 或其他东西)。

<?php

class sfWidgetFormPlain extends sfWidgetForm
{
  /**
   * Constructor.
   *
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetForm
   */
  protected function configure($options = array(), $attributes = array())
  {
      $this->addOption('value');
  }

  /**
   * @param  string $name        The element name
   * @param  string $value       The value displayed in this widget
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
    //optional - for easy css styling
    $attributes['class'] = 'plain';

    return $this->renderContentTag('div', $value, $attributes);
  }
}

然后,您使用此表单而不是普通表单来处理您不想编辑的表单。查看 symfony 文档以了解如何执行此操作,具体取决于您是在模块中显示它,还是通过管理生成器显示它。

于 2011-04-05T11:44:01.060 回答