You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.
In this simple example I'll demonstrate how to extend CActiveForm class to overload some drawing functions to achieve some commonly used fixes in forms.
The colon ¶
Here is overloaded version of CActiveForm.labelEx that adds colon (:) at the end of text of label with respecting CHtml::$afterRequiredLabel and CHtml::$beforeRequiredLabel
class MyActiveForm extends CActiveForm
{
public function labelEx2($model, $attribute, $htmlOptions = array())
{
if ($model->isAttributeRequired($attribute))
{
$arl = CHtml::$afterRequiredLabel;
$brl = CHtml::$beforeRequiredLabel;
$label = CHtml::activeLabelEx($model, $attribute, $htmlOptions);
$label = str_replace($arl, '', $label);
$label = str_replace($brl, '', $label);
$label_text = strip_tags($label);
$label_html = str_replace($label_text, '', $label);
$label_html = str_replace('</label>', '', $label_html);
return $label_html.$brl.$label_text.':'.$arl.'</label>';
}
else return str_replace('</label>', ':</label>', CHtml::activeLabelEx($model, $attribute, $htmlOptions));
}
Textual information of maximum number of characters ¶
And here is overloaded version of CActiveForm.textField that adds simple span after input box with information on how many characters may be entered to it, with respecting plural form of number endings:
public function textFieldEx($model, $attribute, $htmlOptions = array())
{
if(isset($htmlOptions['maxlength']))
{
$max = $htmlOptions['maxlength'];
$transl = Yii::t('classes', 'MyActiveForm_textFieldEx_begin', array('{size}'=>$max));
$transl.= CChoiceFormat::format(Yii::t('classes', 'MyActiveForm_textFieldEx_expr'), $max);
$transl.= Yii::t('classes', 'MyActiveForm_textFieldEx_end');
$textFieldAdd = ' <span class="text_field_add">'.$transl.'</span>';
}
return CHtml::activePasswordField($model, $attribute, $htmlOptions).$textFieldAdd;
}
This utilizes my own approach to Yii::t() where second parameter isn't English text (as in yii.php and zii.php files in original framework) but actually a placeholder, label or pattern to be exchanged. Therefore you have to create your own classes.php and put there something similar to:
return array
(
'MyActiveForm_textFieldEx_begin' => '(enter up to {size} ',
'MyActiveForm_textFieldEx_expr' => 'n==1#char|n>1#chars',
'MyActiveForm_textFieldEx_end' => ')',
);
I understand that the above code is far from perfect. It was written very quickly, so everyone please feel free to edit and correct it.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.