Currently the maximum length for a text field is set in 3 places:
-
in the data base (i.e. name varchar(255) NOT NULL )
-
in the AR rules (i.e. array(‘name’,‘length’,‘max’=>255) )
-
in the view (i.e. CHtml::activeTextField($model,‘name’,array(‘maxlength’=>255)) )
Contrary to that the "required" property is set in only 2 places
-
in the data base (i.e. name varchar(255) NOT NULL )
-
in the AR rules (i.e. array(‘name’,‘required’) )
When using MyCHtml::activeLabelEx($model, ‘name’), then the method CModel::isAttributeRequired() is called to determine if a “*” should be displayed next to the label. (CModel::isAttributeRequired() checks the AR rules.)
I suggest the following Yii enhancement:
The maxlength attribute for inpute fields should also be determined from the rules, this could be done like this:
Add a new method to CModel:
public function getAttributeMaxLength($attribute,$scenario='') {
$validators=$this->getValidatorsForAttribute($attribute,$scenario);
foreach($validators as $validator) {
if($validator instanceof CStringValidator)
return $validator->max;
}
return null;
}
Change 2 methods in CHtml:
public static function activeTextField($model,$attribute,$htmlOptions=array()) {
if(!isset($htmlOptions['maxlength']) && ($maxlength = $model->getAttributeMaxLength($attribute))) {
$htmlOptions['maxlength'] = $maxlength;
}
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('text',$model,$attribute,$htmlOptions);
}
public static function activePasswordField($model,$attribute,$htmlOptions=array()) {
if(!isset($htmlOptions['maxlength']) && ($maxlength = $model->getAttributeMaxLength($attribute))) {
$htmlOptions['maxlength'] = $maxlength;
}
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('password',$model,$attribute,$htmlOptions);
}
I am already using this, it works well and saves a lot of writing when doing some changes to AR attributes. It would be nice if it was incorporated into the Yii core.
What do you think?