将类添加到所有必需字段的标签

时间:2015-09-22 11:19:01

标签: symfony-1.4

我们在symfony 1.4中有一个项目,我想在所有必填字段的标签中添加一个类。控件定义为,

    $this->setWidgets([
        'userId'        => new sfWidgetFormSelect(array('choices' => $userList)),
        'dateFrom'      => new chiliWidgetFormDateTime(),
        'dateTo'        => new chiliWidgetFormDateTime(),
        'status'        => new sfWidgetFormSelect(array('choices' => [0 => 'All', 1 => 'Failed', 2 => 'Success', ])),
        'page'          => new sfWidgetFormInputHidden(),
        'maxPerPage'    => new sfWidgetFormInputHidden(),
    ]);

    $this->widgetSchema->setLabels([
        'userId'    => 'Administrator',
        'dateFrom'  => 'Login date From',
        'dateTo'    => 'Login date To',
        'status'    => 'Status'
    ]);

    $this->setValidators(array(
        'userId'      => new sfValidatorString(['required' => false]),
        'dateFrom'      => new sfValidatorDateWithTimezone(array('required' => true, 'trim' => true)),
        'dateTo'        => new sfValidatorDateWithTimezone(array('required' => true, 'trim' => true, 'modify' => '+1 day -1 second')),
        'status'        => new sfValidatorChoice(array('choices' => [0, 1, 2])),
        'page'          => new sfValidatorInteger(array('required' => true)),
        'maxPerPage'    => new sfValidatorInteger(array('required' => true)),
    ));

使用上面的代码添加验证器并添加类,似乎可用的唯一方法是使用setAttribute,如下所示,

    $this->widgetSchema->setAttribute('class','required');

这会将类添加到->setLabel()中的所有标签。但是,如何为特定领域添加此项?无论如何,对于所有形式的所有必填字段的标签,是否全局都这样做?

1 个答案:

答案 0 :(得分:0)

您可以扩展symfony的sfForm并将其用作所有表单中的基类:

class myForm extends sfForm {
    public function __construct($defaults = array(), $options = array(), $CSRFSecret = null)
    {
        parent::__construct($defaults, $options, $CSRFSecret);
        foreach($this->getValidatorSchema()->getFields() as $name => $validator) {
            if($validator->getOption('required') && isset($this->widgetSchema[$name])) {
                $widget = $this->getWidget($name);
                $class = $widget->getAttribute('class');
                if($class) {
                    $class .= ' ';
                }
                $widget->setAttribute('class', $class . 'required');
            }
        }
    }
}

对于生成的表单,如果使用doctrine,则在BaseFormDoctrine中执行相同的操作。