Add MAXLENGTH attribute to sfWidgetFormInput

One oversight of symfony is that it does not add the MAXLENGTH attribute to the sfWidgetFormInput/sfWidgetFormInputText widget even though it knows the max length for a validator. For Propel (Doctrine too?), symfony 1.2/1.3 allows you to override the setup in BaseFormPropel in lib\form\BaseFormPropel.class.php. Overriding setup() allows you to add the MAXLENGTH attribute based on the validator.

public function setup() {
  parent::setup();
  foreach ($this->getWidgetSchema()->getFields() as $name => $widget)
  {
    $classname = get_class($widget);
    if ($classname == 'sfWidgetFormInputText') {
      if (($val = $this->getValidator($name)) && ($len = $val->getOption('max_length'))) {
        $widget->setAttribute('maxlength', $len);
      }
    }
  }
}

3 Responses to “Add MAXLENGTH attribute to sfWidgetFormInput”

  1. Kenneth Says:

    Neat. Thanks.
    Got it working in Symfony 1.4 (Doctrine) by just pasting it in.

  2. Kevin Says:

    It works, excellent post, thanks!!

    I wonder when this will be rolled into Symfony. Its such an obvious need…

  3. David Says:

    Hi!
    This also works:

    $this->widgetSchema[‘people’] = new sfWidgetFormInputText(array(), array(‘maxlength’=>3));

Leave a comment