【问题标题】:Symfony 1.4 style form field with errorsSymfony 1.4 样式的表单字段有错误
【发布时间】:2013-04-18 04:04:02
【问题描述】:

我想在发生错误时更改我的字段的背景颜色。

在 Java Struts 中,我可以这样做:

<s:textfield name="parameter" cssClass="normal_css_class" cssErrorClass="class_on_error" cssErrorStyle="style_on error"/>

我希望能够执行上述操作。当字段参数有错误时,标签会渲染字段 cssErrorClass。不再需要额外的 Javascript。

目前我的模板中有以下(非常脏的)代码:

<?php if($form['bill_to']->hasError()): ?>
  <?php echo $form['bill_to']->render(array('style' => 'background-color: red')) ?>
<?php else: ?>
  <?php echo $form['bill_to']->render() ?>
<?php endif; ?>
<?php echo $form['bill_to']->renderError() ?>

上面的代码有效,但是有没有办法实现它,所以我只需要调用:

<?php echo $form['bill_to']->render() ?>

然后它会执行样式的设置?我正在考虑重写 render() 方法,但我不确定这是否是正确的方法。

【问题讨论】:

    标签: php validation symfony-1.4


    【解决方案1】:

    您可以像这样扩展 sfWidgetFormSchemaFormatter 类:

    class sfWidgetFormSchemaFormatterCustom extends sfWidgetFormSchemaFormatter
    {
        protected
            $rowFormat                  = "<div class=\"%row_class%\">%label% %field% %hidden_fields% %help%</div>",
            $helpFormat                 = "%help%",
            $errorRowFormat             = "",
            $errorListFormatInARow      = "\n%errors%\n",
            $errorRowFormatInARow       = "<span class=\"error\">%error%</span>\n",
            $namedErrorRowFormatInARow  = "%error%\n",
            $decoratorFormat            = "%content%";
    
    
        public function formatRow($label, $field, $errors = array(), $help = '', $hiddenFields = null)
        {
            $row = parent::formatRow(
                $label,
                $field,
                $errors,
                $help,
                $hiddenFields
            );
    
            return strtr($row, array(
                '%row_class%' => (count($errors) > 0) ? ' error' : '',
            ));
        }
    }// decorator class
    

    并将其应用到它的 configure() 方法中的表单,如下所示:

    class myForm extends sfForm
    {
        public function configure()
        {
            // ....
    
    
            $formatter = new sfWidgetFormSchemaFormatterCustom($this->widgetSchema);
            $this->widgetSchema->addFormFormatter('custom', $formatter);
            $this->widgetSchema->setFormFormatterName('custom');
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可能想研究表单格式化程序,请参阅http://www.symfony-project.org/api/1_4/sfWidgetFormSchemaFormatter

      当您在 sfForm 的 configure 方法中时,可以使用 $this-&gt;getWidgetSchema()-&gt;getFormFormatter() 获得一个 formformatter 对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-04
        相关资源
        最近更新 更多