Package | system.web.helpers |
---|---|
Inheritance | class CHtml |
Since | 1.0 |
Source Code | framework/web/helpers/CHtml.php |
array('class' => 'my-class', 'target' => '_blank')
as htmlOptions
it will result in the html attributes rendered like this: class="my-class" target="_blank"
.Property | Type | Description | Defined By |
---|---|---|---|
afterRequiredLabel | string | the HTML code to be appended to the required label. | CHtml |
beforeRequiredLabel | string | the HTML code to be prepended to the required label. | CHtml |
cdataScriptAndStyleContents | boolean | whether to add a CDATA wrapper around <script> and <style> contents. |
CHtml |
closeSingleTags | boolean | whether to close single tags. | CHtml |
count | integer | the counter for generating automatic input field names. | CHtml |
errorContainerTag | string | the tag name for the error container tag. | CHtml |
errorCss | string | the CSS class for highlighting error inputs. | CHtml |
errorMessageCss | string | the CSS class for displaying error messages (see error). | CHtml |
errorSummaryCss | string | the CSS class for displaying error summaries (see errorSummary). | CHtml |
liveEvents | Sets the default style for attaching jQuery event handlers. | CHtml | |
renderSpecialAttributesValue | boolean | whether to render special attributes value. | CHtml |
requiredCss | string | the CSS class for required labels. | CHtml |
setScriptType | boolean | whether to add type="javascript" to <script> tags. |
CHtml |
Method | Description | Defined By |
---|---|---|
activeCheckBox() | Generates a check box for a model attribute. | CHtml |
activeCheckBoxList() | Generates a check box list for a model attribute. | CHtml |
activeColorField() | Generates a color picker field input for a model attribute. | CHtml |
activeDateField() | Generates a date field input for a model attribute. | CHtml |
activeDateTimeField() | Generates a datetime field input for a model attribute. | CHtml |
activeDateTimeLocalField() | Generates a datetime-local field input for a model attribute. | CHtml |
activeDropDownList() | Generates a drop down list for a model attribute. | CHtml |
activeEmailField() | Generates an email field input for a model attribute. | CHtml |
activeFileField() | Generates a file input for a model attribute. | CHtml |
activeHiddenField() | Generates a hidden input for a model attribute. | CHtml |
activeId() | Generates input field ID for a model attribute. | CHtml |
activeLabel() | Generates a label tag for a model attribute. | CHtml |
activeLabelEx() | Generates a label tag for a model attribute. | CHtml |
activeListBox() | Generates a list box for a model attribute. | CHtml |
activeName() | Generates input field name for a model attribute. | CHtml |
activeNumberField() | Generates a number field input for a model attribute. | CHtml |
activePasswordField() | Generates a password field input for a model attribute. | CHtml |
activeRadioButton() | Generates a radio button for a model attribute. | CHtml |
activeRadioButtonList() | Generates a radio button list for a model attribute. | CHtml |
activeRangeField() | Generates a range field input for a model attribute. | CHtml |
activeSearchField() | Generates a search field input for a model attribute. | CHtml |
activeTelField() | Generates a telephone field input for a model attribute. | CHtml |
activeTextArea() | Generates a text area input for a model attribute. | CHtml |
activeTextField() | Generates a text field input for a model attribute. | CHtml |
activeTimeField() | Generates a time field input for a model attribute. | CHtml |
activeUrlField() | Generates a url field input for a model attribute. | CHtml |
activeWeekField() | Generates a week field input for a model attribute. | CHtml |
ajax() | Generates the JavaScript that initiates an AJAX request. | CHtml |
ajaxButton() | Generates a push button that can initiate AJAX requests. | CHtml |
ajaxLink() | Generates a link that can initiate AJAX requests. | CHtml |
ajaxSubmitButton() | Generates a push button that can submit the current form in POST method. | CHtml |
asset() | Generates the URL for the published assets. | CHtml |
beginForm() | Generates an opening form tag. | CHtml |
button() | Generates a button. | CHtml |
cdata() | Encloses the given string within a CDATA tag. | CHtml |
checkBox() | Generates a check box. | CHtml |
checkBoxList() | Generates a check box list. | CHtml |
closeTag() | Generates a close HTML element. | CHtml |
colorField() | Generates a color picker field input. | CHtml |
css() | Encloses the given CSS content with a CSS tag. | CHtml |
cssFile() | Links to the specified CSS file. | CHtml |
dateField() | Generates a date field input. | CHtml |
dateTimeField() | Generates a datetime field input. | CHtml |
dateTimeLocalField() | Generates a local datetime field input. | CHtml |
decode() | Decodes special HTML entities back to the corresponding characters. | CHtml |
dropDownList() | Generates a drop down list. | CHtml |
emailField() | Generates an email field input. | CHtml |
encode() | Encodes special characters into HTML entities. | CHtml |
encodeArray() | Encodes special characters in an array of strings into HTML entities. | CHtml |
endForm() | Generates a closing form tag. | CHtml |
error() | Displays the first validation error for a model attribute. | CHtml |
errorSummary() | Displays a summary of validation errors for one or several models. | CHtml |
fileField() | Generates a file input. | CHtml |
form() | Generates an opening form tag. | CHtml |
getIdByName() | Generates a valid HTML ID based on name. | CHtml |
htmlButton() | Generates a button using HTML button tag. | CHtml |
image() | Generates an image tag. | CHtml |
imageButton() | Generates an image submit button. | CHtml |
label() | Generates a label tag. | CHtml |
link() | Generates a hyperlink tag. | CHtml |
linkButton() | Generates a link submit button. | CHtml |
linkTag() | Generates a link tag that can be inserted in the head section of HTML page. | CHtml |
listBox() | Generates a list box. | CHtml |
listData() | Generates the data suitable for list-based HTML elements. | CHtml |
listOptions() | Generates the list options. | CHtml |
mailto() | Generates a mailto link. | CHtml |
metaTag() | Generates a meta tag that can be inserted in the head section of HTML page. | CHtml |
modelName() | Generates HTML name for given model. | CHtml |
normalizeUrl() | Normalizes the input parameter to be a valid URL. | CHtml |
numberField() | Generates a number field input. | CHtml |
openTag() | Generates an open HTML element. | CHtml |
pageStateField() | Generates a hidden field for storing persistent page states. | CHtml |
passwordField() | Generates a password field input. | CHtml |
radioButton() | Generates a radio button. | CHtml |
radioButtonList() | Generates a radio button list. | CHtml |
rangeField() | Generates a range field input. | CHtml |
refresh() | Registers a 'refresh' meta tag. | CHtml |
renderAttributes() | Renders the HTML tag attributes. | CHtml |
resetButton() | Generates a reset button. | CHtml |
resolveName() | Generates input name for a model attribute. | CHtml |
resolveNameID() | Generates input name and ID for a model attribute. | CHtml |
resolveValue() | Evaluates the attribute value of the model. | CHtml |
script() | Encloses the given JavaScript within a script tag. | CHtml |
scriptFile() | Includes a JavaScript file. | CHtml |
searchField() | Generates a search field input. | CHtml |
setModelNameConverter() | Set generator used in the CHtml::modelName() method. You can use the `null` value to restore default | CHtml |
statefulForm() | Generates a stateful form tag. | CHtml |
submitButton() | Generates a submit button. | CHtml |
tag() | Generates an HTML element. | CHtml |
telField() | Generates a telephone field input. | CHtml |
textArea() | Generates a text area input. | CHtml |
textField() | Generates a text field input. | CHtml |
timeField() | Generates a time field input. | CHtml |
urlField() | Generates a URL field input. | CHtml |
value() | Evaluates the value of the specified attribute for the given model. | CHtml |
weekField() | Generates a week field input. | CHtml |
Method | Description | Defined By |
---|---|---|
activeInputField() | Generates an input HTML tag for a model attribute. | CHtml |
addErrorCss() | Appends errorCss to the 'class' attribute. | CHtml |
clientChange() | Generates the JavaScript with the specified client changes. | CHtml |
inputField() | Generates an input HTML tag. | CHtml |
the HTML code to be appended to the required label.
the HTML code to be prepended to the required label.
whether to add a CDATA wrapper around <script>
and <style>
contents. Defaults to true. Can be set to false for HTML5.
whether to close single tags. Defaults to true. Can be set to false for HTML5.
the counter for generating automatic input field names.
the tag name for the error container tag. Defaults to 'div'.
the CSS class for highlighting error inputs. Form inputs will be appended with this CSS class if they have input errors.
the CSS class for displaying error messages (see error).
the CSS class for displaying error summaries (see errorSummary).
Sets the default style for attaching jQuery event handlers.
If set to true (default), event handlers are delegated.
Event handlers are attached to the document body and can process events
from descendant elements that are added to the document at a later time.
If set to false, event handlers are directly bound.
Event handlers are attached directly to the DOM element, that must already exist
on the page. Elements injected into the page at a later time will not be processed.
You can override this setting for a particular element by setting the htmlOptions delegate attribute
(see clientChange).
For more information about attaching jQuery event handler see https://api.jquery.com/on/
whether to render special attributes value. Defaults to true. Can be set to false for HTML5.
the CSS class for required labels. Defaults to 'required'.
whether to add type="javascript"
to <script>
tags. Defaults to true. Can be set to false for HTML5.
public static string activeCheckBox(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) A special option named 'uncheckValue' is available that can be used to specify the value returned when the checkbox is not checked. By default, this value is '0'. Internally, a hidden field is rendered so that when the checkbox is not checked, we can still obtain the posted uncheck value. If 'uncheckValue' is set as NULL, the hidden field will not be rendered. |
{return} | string | the generated check box |
public static function activeCheckBox($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
if(!isset($htmlOptions['value']))
$htmlOptions['value']=1;
if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
$htmlOptions['checked']='checked';
self::clientChange('click',$htmlOptions);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck='0';
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
if(!empty($htmlOptions['disabled']))
$hiddenOptions['disabled']=$htmlOptions['disabled'];
$hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
}
Generates a check box for a model attribute. The attribute is assumed to take either true or false value. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeCheckBoxList(CModel $model, string $attribute, array $data, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$data | array | value-label pairs used to generate the check box list. Note, the values will be automatically HTML-encoded, while the labels will not. |
$htmlOptions | array | additional HTML options. The options will be applied to
each checkbox input. The following special options are recognized:
|
{return} | string | the generated check box list |
public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
$selection=self::resolveValue($model,$attribute);
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
$name=$htmlOptions['name'];
unset($htmlOptions['name']);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck='';
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
if(!empty($htmlOptions['disabled']))
$hiddenOptions['disabled']=$htmlOptions['disabled'];
$hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
}
Generates a check box list for a model attribute. The model attribute value is used as the selection. If the attribute has input error, the input field's CSS class will be appended with errorCss. Note that a check box list allows multiple selection, like listBox. As a result, the corresponding POST value is an array. In case no selection is made, the corresponding POST value is an empty string.
public static string activeColorField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeColorField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('color',$model,$attribute,$htmlOptions);
}
Generates a color picker field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeDateField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeDateField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('date',$model,$attribute,$htmlOptions);
}
Generates a date field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeDateTimeField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeDateTimeField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('datetime',$model,$attribute,$htmlOptions);
}
Generates a datetime field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeDateTimeLocalField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeDateTimeLocalField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('datetime-local',$model,$attribute,$htmlOptions);
}
Generates a datetime-local field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeDropDownList(CModel $model, string $attribute, array $data, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$data | array | data for generating the list options (value=>display) You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method. |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special
attributes are recognized. See clientChange and tag for more details.
In addition, the following options are also supported:
|
{return} | string | the generated drop down list |
public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
$selection=self::resolveValue($model,$attribute);
$options="\n".self::listOptions($selection,$data,$htmlOptions);
self::clientChange('change',$htmlOptions);
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
$hidden='';
if(!empty($htmlOptions['multiple']))
{
if(substr($htmlOptions['name'],-2)!=='[]')
$htmlOptions['name'].='[]';
if(isset($htmlOptions['unselectValue']))
{
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
if(!empty($htmlOptions['disabled']))
$hiddenOptions['disabled']=$htmlOptions['disabled'];
$hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
unset($htmlOptions['unselectValue']);
}
}
return $hidden . self::tag('select',$htmlOptions,$options);
}
Generates a drop down list for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeEmailField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeEmailField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('email',$model,$attribute,$htmlOptions);
}
Generates an email field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeFileField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes (see tag). |
{return} | string | the generated input field |
public static function activeFileField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
// add a hidden field so that if a model only has a file field, we can
// still use isset($_POST[$modelClass]) to detect if the input is submitted
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
if(!empty($htmlOptions['disabled']))
$hiddenOptions['disabled']=$htmlOptions['disabled'];
return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
. self::activeInputField('file',$model,$attribute,$htmlOptions);
}
Generates a file input for a model attribute. Note, you have to set the enclosing form's 'enctype' attribute to be 'multipart/form-data'. After the form is submitted, the uploaded file information can be obtained via $_FILES (see PHP documentation).
public static string activeHiddenField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. |
{return} | string | the generated input field |
public static function activeHiddenField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
}
Generates a hidden input for a model attribute.
public static string activeId(CModel|string $model, string $attribute)
| ||
$model | CModel|string | the data model |
$attribute | string | the attribute |
{return} | string | the generated input field ID |
public static function activeId($model,$attribute)
{
return self::getIdByName(self::activeName($model,$attribute));
}
Generates input field ID for a model attribute.
protected static string activeInputField(string $type, CModel $model, string $attribute, array $htmlOptions)
| ||
$type | string | the input type (e.g. 'text', 'radio') |
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes for the HTML tag |
{return} | string | the generated input tag |
protected static function activeInputField($type,$model,$attribute,$htmlOptions)
{
$htmlOptions['type']=$type;
if($type==='text'||$type==='password'||$type==='color'||$type==='date'||$type==='datetime'||
$type==='datetime-local'||$type==='email'||$type==='month'||$type==='number'||$type==='range'||
$type==='search'||$type==='tel'||$type==='time'||$type==='url'||$type==='week')
{
if(!isset($htmlOptions['maxlength']))
{
foreach($model->getValidators($attribute) as $validator)
{
if($validator instanceof CStringValidator && $validator->max!==null)
{
$htmlOptions['maxlength']=$validator->max;
break;
}
}
}
elseif($htmlOptions['maxlength']===false)
unset($htmlOptions['maxlength']);
}
if($type==='file')
unset($htmlOptions['value']);
elseif(!isset($htmlOptions['value']))
$htmlOptions['value']=self::resolveValue($model,$attribute);
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
return self::tag('input',$htmlOptions);
}
Generates an input HTML tag for a model attribute. This method generates an input HTML tag based on the given data model and attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss. This enables highlighting the incorrect input.
public static string activeLabel(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. The following special options are recognized:
|
{return} | string | the generated label tag |
public static function activeLabel($model,$attribute,$htmlOptions=array())
{
$inputName=self::resolveName($model,$attribute);
if(isset($htmlOptions['for']))
{
$for=$htmlOptions['for'];
unset($htmlOptions['for']);
}
else
$for=self::getIdByName($inputName);
if(isset($htmlOptions['label']))
{
if(($label=$htmlOptions['label'])===false)
return '';
unset($htmlOptions['label']);
}
else
$label=$model->getAttributeLabel($attribute);
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
return self::label($label,$for,$htmlOptions);
}
Generates a label tag for a model attribute. The label text is the attribute label and the label is associated with the input for the attribute (see CModel::getAttributeLabel. If the attribute has input error, the label's CSS class will be appended with errorCss.
public static string activeLabelEx(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. |
{return} | string | the generated label tag |
public static function activeLabelEx($model,$attribute,$htmlOptions=array())
{
$realAttribute=$attribute;
self::resolveName($model,$attribute); // strip off square brackets if any
if (!isset($htmlOptions['required']))
$htmlOptions['required']=$model->isAttributeRequired($attribute);
return self::activeLabel($model,$realAttribute,$htmlOptions);
}
Generates a label tag for a model attribute. This is an enhanced version of activeLabel. It will render additional CSS class and mark when the attribute is required. In particular, it calls CModel::isAttributeRequired to determine if the attribute is required. If so, it will add a CSS class CHtml::requiredCss to the label, and decorate the label with CHtml::beforeRequiredLabel and CHtml::afterRequiredLabel.
public static string activeListBox(CModel $model, string $attribute, array $data, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$data | array | data for generating the list options (value=>display) You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method. |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special
attributes are recognized. See clientChange and tag for more details.
In addition, the following options are also supported:
|
{return} | string | the generated list box |
public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
{
if(!isset($htmlOptions['size']))
$htmlOptions['size']=4;
return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
}
Generates a list box for a model attribute. The model attribute value is used as the selection. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeName(CModel|string $model, string $attribute)
| ||
$model | CModel|string | the data model |
$attribute | string | the attribute |
{return} | string | the generated input field name |
public static function activeName($model,$attribute)
{
$a=$attribute; // because the attribute name may be changed by resolveName
return self::resolveName($model,$a);
}
Generates input field name for a model attribute. Unlike resolveName, this method does NOT modify the attribute name.
public static string activeNumberField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeNumberField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('number',$model,$attribute,$htmlOptions);
}
Generates a number field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activePasswordField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activePasswordField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('password',$model,$attribute,$htmlOptions);
}
Generates a password field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeRadioButton(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) A special option named 'uncheckValue' is available that can be used to specify the value returned when the radio button is not checked. By default, this value is '0'. Internally, a hidden field is rendered so that when the radio button is not checked, we can still obtain the posted uncheck value. If 'uncheckValue' is set as NULL, the hidden field will not be rendered. |
{return} | string | the generated radio button |
public static function activeRadioButton($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
if(!isset($htmlOptions['value']))
$htmlOptions['value']=1;
if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
$htmlOptions['checked']='checked';
self::clientChange('click',$htmlOptions);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck='0';
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
if(!empty($htmlOptions['disabled']))
$hiddenOptions['disabled']=$htmlOptions['disabled'];
$hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
// add a hidden field so that if the radio button is not selected, it still submits a value
return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
}
Generates a radio button for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeRadioButtonList(CModel $model, string $attribute, array $data, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$data | array | value-label pairs used to generate the radio button list. Note, the values will be automatically HTML-encoded, while the labels will not. |
$htmlOptions | array | additional HTML options. The options will be applied to
each radio button input. The following special options are recognized:
|
{return} | string | the generated radio button list |
public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
$selection=self::resolveValue($model,$attribute);
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
$name=$htmlOptions['name'];
unset($htmlOptions['name']);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck='';
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
if(!empty($htmlOptions['disabled']))
$hiddenOptions['disabled']=$htmlOptions['disabled'];
$hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
}
Generates a radio button list for a model attribute. The model attribute value is used as the selection. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeRangeField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeRangeField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('range',$model,$attribute,$htmlOptions);
}
Generates a range field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeSearchField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeSearchField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('search',$model,$attribute,$htmlOptions);
}
Generates a search field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeTelField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeTelField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('tel',$model,$attribute,$htmlOptions);
}
Generates a telephone field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeTextArea(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated text area |
public static function activeTextArea($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
if(isset($htmlOptions['value']))
{
$text=$htmlOptions['value'];
unset($htmlOptions['value']);
}
else
$text=self::resolveValue($model,$attribute);
return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
}
Generates a text area input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeTextField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeTextField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('text',$model,$attribute,$htmlOptions);
}
Generates a text field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeTimeField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeTimeField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('time',$model,$attribute,$htmlOptions);
}
Generates a time field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeUrlField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeUrlField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('url',$model,$attribute,$htmlOptions);
}
Generates a url field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
public static string activeWeekField(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function activeWeekField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
self::clientChange('change',$htmlOptions);
return self::activeInputField('week',$model,$attribute,$htmlOptions);
}
Generates a week field input for a model attribute. If the attribute has input error, the input field's CSS class will be appended with errorCss.
protected static void addErrorCss(array &$htmlOptions)
| ||
$htmlOptions | array | HTML options to be modified |
protected static function addErrorCss(&$htmlOptions)
{
if(empty(self::$errorCss))
return;
if(isset($htmlOptions['class']))
$htmlOptions['class'].=' '.self::$errorCss;
else
$htmlOptions['class']=self::$errorCss;
}
Appends errorCss to the 'class' attribute.
public static string ajax(array $options)
| ||
$options | array | AJAX options. The valid options are used in the form of jQuery.ajax([settings])
as specified in the jQuery AJAX documentation.
The following special options are added for convenience:
|
{return} | string | the generated JavaScript |
public static function ajax($options)
{
Yii::app()->getClientScript()->registerCoreScript('jquery');
if(!isset($options['url']))
$options['url']=new CJavaScriptExpression('location.href');
else
$options['url']=self::normalizeUrl($options['url']);
if(!isset($options['cache']))
$options['cache']=false;
if(!isset($options['data']) && isset($options['type']))
$options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
foreach(array('beforeSend','complete','error','success') as $name)
{
if(isset($options[$name]) && !($options[$name] instanceof CJavaScriptExpression))
$options[$name]=new CJavaScriptExpression($options[$name]);
}
if(isset($options['update']))
{
if(!isset($options['success']))
$options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
unset($options['update']);
}
if(isset($options['replace']))
{
if(!isset($options['success']))
$options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
unset($options['replace']);
}
return 'jQuery.ajax('.CJavaScript::encode($options).');';
}
Generates the JavaScript that initiates an AJAX request.
public static string ajaxButton(string $label, mixed $url, array $ajaxOptions=array (
), array $htmlOptions=array (
))
| ||
$label | string | the button label |
$url | mixed | the URL for the AJAX request. If empty, it is assumed to be the current URL. See normalizeUrl for more details. |
$ajaxOptions | array | AJAX options (see ajax) |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated button |
public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
{
$ajaxOptions['url']=$url;
$htmlOptions['ajax']=$ajaxOptions;
return self::button($label,$htmlOptions);
}
Generates a push button that can initiate AJAX requests.
public static string ajaxLink(string $text, mixed $url, array $ajaxOptions=array (
), array $htmlOptions=array (
))
| ||
$text | string | the link body (it will NOT be HTML-encoded.) |
$url | mixed | the URL for the AJAX request. If empty, it is assumed to be the current URL. See normalizeUrl for more details. |
$ajaxOptions | array | AJAX options (see ajax) |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated link |
public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
{
if(!isset($htmlOptions['href']))
$htmlOptions['href']='#';
$ajaxOptions['url']=$url;
$htmlOptions['ajax']=$ajaxOptions;
self::clientChange('click',$htmlOptions);
return self::tag('a',$htmlOptions,$text);
}
Generates a link that can initiate AJAX requests.
public static string ajaxSubmitButton(string $label, mixed $url, array $ajaxOptions=array (
), array $htmlOptions=array (
))
| ||
$label | string | the button label |
$url | mixed | the URL for the AJAX request. If empty, it is assumed to be the current URL. See normalizeUrl for more details. |
$ajaxOptions | array | AJAX options (see ajax) |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated button |
public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
{
$ajaxOptions['type']='POST';
$htmlOptions['type']='submit';
return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
}
Generates a push button that can submit the current form in POST method.
public static string asset(string $path, boolean $hashByName=false)
| ||
$path | string | the path of the asset to be published |
$hashByName | boolean | whether the published directory should be named as the hashed basename. If false, the name will be the hashed dirname of the path being published. Defaults to false. Set true if the path being published is shared among different extensions. |
{return} | string | the asset URL |
public static function asset($path,$hashByName=false)
{
return Yii::app()->getAssetManager()->publish($path,$hashByName);
}
Generates the URL for the published assets.
public static string beginForm(mixed $action='', string $method='post', array $htmlOptions=array (
))
| ||
$action | mixed | the form action URL (see normalizeUrl for details about this parameter.) |
$method | string | form method (e.g. post, get) |
$htmlOptions | array | additional HTML attributes (see tag). |
{return} | string | the generated form tag. |
public static function beginForm($action='',$method='post',$htmlOptions=array())
{
$htmlOptions['action']=$url=self::normalizeUrl($action);
if(strcasecmp($method,'get')!==0 && strcasecmp($method,'post')!==0)
{
$customMethod=$method;
$method='post';
}
else
$customMethod=false;
$htmlOptions['method']=$method;
$form=self::tag('form',$htmlOptions,false,false);
$hiddens=array();
if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
{
foreach(explode('&',substr(preg_replace('/#.+$/','',$url),$pos+1)) as $pair)
{
if(($pos=strpos($pair,'='))!==false)
$hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
else
$hiddens[]=self::hiddenField(urldecode($pair),'',array('id'=>false));
}
}
$request=Yii::app()->request;
if($request->enableCsrfValidation && !strcasecmp($method,'post'))
$hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
if($customMethod!==false)
$hiddens[]=self::hiddenField('_method',$customMethod);
if($hiddens!==array())
$form.="\n".implode("\n",$hiddens);
return $form;
}
Generates an opening form tag. Note, only the open tag is generated. A close tag should be placed manually at the end of the form.
public static string button(string $label='button', array $htmlOptions=array (
))
| ||
$label | string | the button label |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated button tag |
public static function button($label='button',$htmlOptions=array())
{
if(!isset($htmlOptions['name']))
{
if(!array_key_exists('name',$htmlOptions))
$htmlOptions['name']=self::ID_PREFIX.self::$count++;
}
if(!isset($htmlOptions['type']))
$htmlOptions['type']='button';
if(!isset($htmlOptions['value']) && $htmlOptions['type']!='image')
$htmlOptions['value']=$label;
self::clientChange('click',$htmlOptions);
return self::tag('input',$htmlOptions);
}
Generates a button.
public static string cdata(string $text)
| ||
$text | string | the string to be enclosed |
{return} | string | the CDATA tag with the enclosed content. |
public static function cdata($text)
{
return '<![CDATA[' . $text . ']]>';
}
Encloses the given string within a CDATA tag.
public static string checkBox(string $name, boolean $checked=false, array $htmlOptions=array (
))
| ||
$name | string | the input name |
$checked | boolean | whether the check box is checked |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) Since version 1.1.2, a special option named 'uncheckValue' is available that can be used to specify the value returned when the checkbox is not checked. When set, a hidden field is rendered so that when the checkbox is not checked, we can still obtain the posted uncheck value. If 'uncheckValue' is not set or set to NULL, the hidden field will not be rendered. |
{return} | string | the generated check box |
public static function checkBox($name,$checked=false,$htmlOptions=array())
{
if($checked)
$htmlOptions['checked']='checked';
else
unset($htmlOptions['checked']);
$value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
self::clientChange('click',$htmlOptions);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck=null;
if($uncheck!==null)
{
// add a hidden field so that if the check box is not checked, it still submits a value
if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
$uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
else
$uncheckOptions=array('id'=>false);
if(!empty($htmlOptions['disabled']))
$uncheckOptions['disabled']=$htmlOptions['disabled'];
$hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
}
else
$hidden='';
// add a hidden field so that if the check box is not checked, it still submits a value
return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
}
Generates a check box.
public static string checkBoxList(string $name, mixed $select, array $data, array $htmlOptions=array (
))
| ||
$name | string | name of the check box list. You can use this name to retrieve the selected value(s) once the form is submitted. |
$select | mixed | selection of the check boxes. This can be either a string for single selection or an array for multiple selections. |
$data | array | value-label pairs used to generate the check box list. Note, the values will be automatically HTML-encoded, while the labels will not. |
$htmlOptions | array | additional HTML options. The options will be applied to
each checkbox input. The following special options are recognized:
|
{return} | string | the generated check box list |
public static function checkBoxList($name,$select,$data,$htmlOptions=array())
{
$template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
$separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
$container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
if(substr($name,-2)!=='[]')
$name.='[]';
if(isset($htmlOptions['checkAll']))
{
$checkAllLabel=$htmlOptions['checkAll'];
$checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
}
unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
$labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
unset($htmlOptions['labelOptions']);
$items=array();
$baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
unset($htmlOptions['baseID']);
$id=0;
$checkAll=true;
foreach($data as $value=>$labelTitle)
{
$checked=!is_array($select) && !strcmp($value,(string)$select) || is_array($select) && in_array($value,$select);
$checkAll=$checkAll && $checked;
$htmlOptions['value']=$value;
$htmlOptions['id']=$baseID.'_'.$id++;
$option=self::checkBox($name,$checked,$htmlOptions);
$beginLabel=self::openTag('label',$labelOptions);
$label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
$endLabel=self::closeTag('label');
$items[]=strtr($template,array(
'{input}'=>$option,
'{beginLabel}'=>$beginLabel,
'{label}'=>$label,
'{labelTitle}'=>$labelTitle,
'{endLabel}'=>$endLabel,
));
}
if(isset($checkAllLabel))
{
$htmlOptions['value']=1;
$htmlOptions['id']=$id=$baseID.'_all';
$option=self::checkBox($id,$checkAll,$htmlOptions);
$beginLabel=self::openTag('label',$labelOptions);
$label=self::label($checkAllLabel,$id,$labelOptions);
$endLabel=self::closeTag('label');
$item=strtr($template,array(
'{input}'=>$option,
'{beginLabel}'=>$beginLabel,
'{label}'=>$label,
'{labelTitle}'=>$checkAllLabel,
'{endLabel}'=>$endLabel,
));
if($checkAllLast)
$items[]=$item;
else
array_unshift($items,$item);
$name=strtr($name,array('['=>'\\[',']'=>'\\]'));
$js=<<<EOD
jQuery('#$id').click(function() {
jQuery("input[name='$name']").prop('checked', this.checked);
});
jQuery("input[name='$name']").click(function() {
jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
});
jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
EOD;
$cs=Yii::app()->getClientScript();
$cs->registerCoreScript('jquery');
$cs->registerScript($id,$js);
}
if(empty($container))
return implode($separator,$items);
else
return self::tag($container,array('id'=>$baseID),implode($separator,$items));
}
Generates a check box list. A check box list allows multiple selection, like listBox. As a result, the corresponding POST value is an array.
protected static void clientChange(string $event, array &$htmlOptions)
| ||
$event | string | event name (without 'on') |
$htmlOptions | array | HTML attributes which may contain the following special attributes
specifying the client change behaviors:
|
protected static function clientChange($event,&$htmlOptions)
{
if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
return;
if(isset($htmlOptions['live']))
{
$live=$htmlOptions['live'];
unset($htmlOptions['live']);
}
else
$live = self::$liveEvents;
if(isset($htmlOptions['return']) && $htmlOptions['return'])
$return='return true';
else
$return='return false';
if(isset($htmlOptions['on'.$event]))
{
$handler=trim($htmlOptions['on'.$event],';').';';
unset($htmlOptions['on'.$event]);
}
else
$handler='';
if(isset($htmlOptions['id']))
$id=$htmlOptions['id'];
else
$id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
$cs=Yii::app()->getClientScript();
$cs->registerCoreScript('jquery');
if(isset($htmlOptions['submit']))
{
$cs->registerCoreScript('yii');
$request=Yii::app()->getRequest();
if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
$htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
if(isset($htmlOptions['params']))
$params=CJavaScript::encode($htmlOptions['params']);
else
$params='{}';
if($htmlOptions['submit']!=='')
$url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
else
$url='';
$handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
}
if(isset($htmlOptions['ajax']))
$handler.=self::ajax($htmlOptions['ajax'])."{$return};";
if(isset($htmlOptions['confirm']))
{
$confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
if($handler!=='')
$handler="if($confirm) {".$handler."} else return false;";
else
$handler="return $confirm;";
}
if($live)
$cs->registerScript('Yii.CHtml.#' . $id,"jQuery('body').on('$event','#$id',function(){{$handler}});");
else
$cs->registerScript('Yii.CHtml.#' . $id,"jQuery('#$id').on('$event', function(){{$handler}});");
unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
}
Generates the JavaScript with the specified client changes.
public static string closeTag(string $tag)
| ||
$tag | string | the tag name |
{return} | string | the generated HTML element tag |
public static function closeTag($tag)
{
return '</'.$tag.'>';
}
Generates a close HTML element.
public static string colorField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function colorField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('color',$name,$value,$htmlOptions);
}
Generates a color picker field input.
public static string css(string $text, string $media='')
| ||
$text | string | the CSS content |
$media | string | the media that this CSS should apply to. |
{return} | string | the CSS properly enclosed |
public static function css($text,$media='')
{
if($media!=='')
$media=' media="'.$media.'"';
if(self::$cdataScriptAndStyleContents)
$text="/*<![CDATA[*/\n{$text}\n/*]]>*/";
return "<style type=\"text/css\"{$media}>\n{$text}\n</style>";
}
Encloses the given CSS content with a CSS tag.
public static string cssFile(string $url, string $media='')
| ||
$url | string | the CSS URL |
$media | string | the media that this CSS should apply to. |
{return} | string | the CSS link. |
public static function cssFile($url,$media='')
{
return CHtml::linkTag('stylesheet','text/css',$url,$media!=='' ? $media : null);
}
Links to the specified CSS file.
public static string dateField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function dateField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('date',$name,$value,$htmlOptions);
}
Generates a date field input.
public static string dateTimeField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function dateTimeField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('datetime',$name,$value,$htmlOptions);
}
Generates a datetime field input.
public static string dateTimeLocalField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function dateTimeLocalField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('datetime-local',$name,$value,$htmlOptions);
}
Generates a local datetime field input.
public static string decode(string $text)
| ||
$text | string | data to be decoded |
{return} | string | the decoded data |
public static function decode($text)
{
return htmlspecialchars_decode($text,ENT_QUOTES);
}
Decodes special HTML entities back to the corresponding characters. This is the opposite of encode().
public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array (
))
| ||
$name | string | the input name |
$select | string | the selected value |
$data | array | data for generating the list options (value=>display). You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method. |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special
attributes are recognized. See clientChange and tag for more details.
In addition, the following options are also supported specifically for dropdown list:
|
{return} | string | the generated drop down list |
public static function dropDownList($name,$select,$data,$htmlOptions=array())
{
$htmlOptions['name']=$name;
if(!isset($htmlOptions['id']))
$htmlOptions['id']=self::getIdByName($name);
elseif($htmlOptions['id']===false)
unset($htmlOptions['id']);
self::clientChange('change',$htmlOptions);
$options="\n".self::listOptions($select,$data,$htmlOptions);
$hidden='';
if(!empty($htmlOptions['multiple']))
{
if(substr($htmlOptions['name'],-2)!=='[]')
$htmlOptions['name'].='[]';
if(isset($htmlOptions['unselectValue']))
{
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
if(!empty($htmlOptions['disabled']))
$hiddenOptions['disabled']=$htmlOptions['disabled'];
$hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
unset($htmlOptions['unselectValue']);
}
}
// add a hidden field so that if the option is not selected, it still submits a value
return $hidden . self::tag('select',$htmlOptions,$options);
}
Generates a drop down list.
public static string emailField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function emailField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('email',$name,$value,$htmlOptions);
}
Generates an email field input.
public static string encode(string $text)
| ||
$text | string | data to be encoded |
{return} | string | the encoded data |
public static function encode($text)
{
return htmlspecialchars((string)$text,ENT_QUOTES,Yii::app()->charset);
}
Encodes special characters into HTML entities. The application charset will be used for encoding.
public static array encodeArray(array $data)
| ||
$data | array | data to be encoded |
{return} | array | the encoded data |
public static function encodeArray($data)
{
$d=array();
foreach($data as $key=>$value)
{
if(is_string($key))
$key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
if(is_string($value))
$value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
elseif(is_array($value))
$value=self::encodeArray($value);
$d[$key]=$value;
}
return $d;
}
Encodes special characters in an array of strings into HTML entities. Both the array keys and values will be encoded if needed. If a value is an array, this method will also encode it recursively. The application charset will be used for encoding.
public static string endForm()
| ||
{return} | string | the generated tag |
public static function endForm()
{
return '</form>';
}
Generates a closing form tag.
public static string error(CModel $model, string $attribute, array $htmlOptions=array (
))
| ||
$model | CModel | the data model |
$attribute | string | the attribute name |
$htmlOptions | array | additional HTML attributes to be rendered in the container tag. |
{return} | string | the error display. Empty if no errors are found. |
public static function error($model,$attribute,$htmlOptions=array())
{
self::resolveName($model,$attribute); // turn [a][b]attr into attr
$error=$model->getError($attribute);
if (!isset($htmlOptions['encode']) || $htmlOptions['encode'])
$error=self::encode($error);
if($error!='')
{
if(!isset($htmlOptions['class']))
$htmlOptions['class']=self::$errorMessageCss;
return self::tag(self::$errorContainerTag,$htmlOptions,$error);
}
else
return '';
}
Displays the first validation error for a model attribute.
public static string errorSummary(mixed $model, string $header=NULL, string $footer=NULL, array $htmlOptions=array (
))
| ||
$model | mixed | the models whose input errors are to be displayed. This can be either a single model or an array of models. |
$header | string | a piece of HTML code that appears in front of the errors |
$footer | string | a piece of HTML code that appears at the end of the errors |
$htmlOptions | array | additional HTML attributes to be rendered in the container div tag. A special option named 'firstError' is recognized, which when set true, will make the error summary to show only the first error message of each attribute. If this is not set or is false, all error messages will be displayed. This option has been available since version 1.1.3. Another special option named 'encode' is recognized, which when set false, will disable the CHtml::encode encoding of all error messages. If this is not set or is true, all error messages will be encoded by CHtml::encode. This option has been available since version 1.1.23. |
{return} | string | the error summary. Empty if no errors are found. |
public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
{
$content='';
if(!is_array($model))
$model=array($model);
if(isset($htmlOptions['firstError']))
{
$firstError=$htmlOptions['firstError'];
unset($htmlOptions['firstError']);
}
else
$firstError=false;
foreach($model as $m)
{
foreach($m->getErrors() as $errors)
{
foreach($errors as $error)
{
if($error!='')
{
if (!isset($htmlOptions['encode']) || $htmlOptions['encode'])
$error=self::encode($error);
$content.= '<li>'.$error."</li>\n";
}
if($firstError)
break;
}
}
}
if($content!=='')
{
if($header===null)
$header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
if(!isset($htmlOptions['class']))
$htmlOptions['class']=self::$errorSummaryCss;
return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
}
else
return '';
}
Displays a summary of validation errors for one or several models.
public static string fileField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes (see tag). |
{return} | string | the generated input field |
public static function fileField($name,$value='',$htmlOptions=array())
{
return self::inputField('file',$name,$value,$htmlOptions);
}
Generates a file input. Note, you have to set the enclosing form's 'enctype' attribute to be 'multipart/form-data'. After the form is submitted, the uploaded file information can be obtained via $_FILES[$name] (see PHP documentation).
public static string form(mixed $action='', string $method='post', array $htmlOptions=array (
))
| ||
$action | mixed | the form action URL (see normalizeUrl for details about this parameter.) |
$method | string | form method (e.g. post, get) |
$htmlOptions | array | additional HTML attributes (see tag). |
{return} | string | the generated form tag. |
public static function form($action='',$method='post',$htmlOptions=array())
{
return self::beginForm($action,$method,$htmlOptions);
}
Generates an opening form tag. This is a shortcut to beginForm.
public static string getIdByName(string $name)
| ||
$name | string | name from which to generate HTML ID |
{return} | string | the ID generated based on name. |
public static function getIdByName($name)
{
return str_replace(array('[]','][','[',']',' '),array('','_','_','','_'),$name);
}
Generates a valid HTML ID based on name.
public static string hiddenField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes (see tag). |
{return} | string | the generated input field |
public static function hiddenField($name,$value='',$htmlOptions=array())
{
return self::inputField('hidden',$name,$value,$htmlOptions);
}
Generates a hidden input.
public static string htmlButton(string $label='button', array $htmlOptions=array (
))
| ||
$label | string | the button label. Note that this value will be directly inserted in the button element without being HTML-encoded. |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated button tag |
public static function htmlButton($label='button',$htmlOptions=array())
{
if(!isset($htmlOptions['name']))
$htmlOptions['name']=self::ID_PREFIX.self::$count++;
if(!isset($htmlOptions['type']))
$htmlOptions['type']='button';
self::clientChange('click',$htmlOptions);
return self::tag('button',$htmlOptions,$label);
}
Generates a button using HTML button tag. This method is similar to button except that it generates a 'button' tag instead of 'input' tag.
public static string image(string $src, string $alt='', array $htmlOptions=array (
))
| ||
$src | string | the image URL |
$alt | string | the alternative text display |
$htmlOptions | array | additional HTML attributes (see tag). |
{return} | string | the generated image tag |
public static function image($src,$alt='',$htmlOptions=array())
{
$htmlOptions['src']=$src;
$htmlOptions['alt']=$alt;
return self::tag('img',$htmlOptions);
}
Generates an image tag.
public static string imageButton(string $src, array $htmlOptions=array (
))
| ||
$src | string | the image URL |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated button tag |
public static function imageButton($src,$htmlOptions=array())
{
$htmlOptions['src']=$src;
$htmlOptions['type']='image';
return self::button('submit',$htmlOptions);
}
Generates an image submit button.
protected static string inputField(string $type, string $name, string $value, array $htmlOptions)
| ||
$type | string | the input type (e.g. 'text', 'radio') |
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes for the HTML tag (see tag). |
{return} | string | the generated input tag |
protected static function inputField($type,$name,$value,$htmlOptions)
{
$htmlOptions['type']=$type;
$htmlOptions['value']=$value;
$htmlOptions['name']=$name;
if(!isset($htmlOptions['id']))
$htmlOptions['id']=self::getIdByName($name);
elseif($htmlOptions['id']===false)
unset($htmlOptions['id']);
return self::tag('input',$htmlOptions);
}
Generates an input HTML tag. This method generates an input HTML tag based on the given input name and value.
public static string label(string $label, string $for, array $htmlOptions=array (
))
| ||
$label | string | label text. Note, you should HTML-encode the text if needed. |
$for | string | the ID of the HTML element that this label is associated with. If this is false, the 'for' attribute for the label tag will not be rendered. |
$htmlOptions | array | additional HTML attributes.
The following HTML option is recognized:
|
{return} | string | the generated label tag |
public static function label($label,$for,$htmlOptions=array())
{
if($for===false)
unset($htmlOptions['for']);
else
$htmlOptions['for']=$for;
if(isset($htmlOptions['required']))
{
if($htmlOptions['required'])
{
if(isset($htmlOptions['class']))
$htmlOptions['class'].=' '.self::$requiredCss;
else
$htmlOptions['class']=self::$requiredCss;
$label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
}
unset($htmlOptions['required']);
}
return self::tag('label',$htmlOptions,$label);
}
Generates a label tag.
public static string link(string $text, mixed $url='#', array $htmlOptions=array (
))
| ||
$text | string | link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. |
$url | mixed | a URL or an action route that can be used to create a URL. See normalizeUrl for more details about how to specify this parameter. |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated hyperlink |
public static function link($text,$url='#',$htmlOptions=array())
{
if($url!=='')
$htmlOptions['href']=self::normalizeUrl($url);
self::clientChange('click',$htmlOptions);
return self::tag('a',$htmlOptions,$text);
}
Generates a hyperlink tag.
public static string linkButton(string $label='submit', array $htmlOptions=array (
))
| ||
$label | string | the button label |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated button tag |
public static function linkButton($label='submit',$htmlOptions=array())
{
if(!isset($htmlOptions['submit']))
$htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
return self::link($label,'#',$htmlOptions);
}
Generates a link submit button.
public static string linkTag(string $relation=NULL, string $type=NULL, string $href=NULL, string $media=NULL, array $options=array (
))
| ||
$relation | string | rel attribute of the link tag. If null, the attribute will not be generated. |
$type | string | type attribute of the link tag. If null, the attribute will not be generated. |
$href | string | href attribute of the link tag. If null, the attribute will not be generated. |
$media | string | media attribute of the link tag. If null, the attribute will not be generated. |
$options | array | other options in name-value pairs |
{return} | string | the generated link tag |
public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
{
if($relation!==null)
$options['rel']=$relation;
if($type!==null)
$options['type']=$type;
if($href!==null)
$options['href']=$href;
if($media!==null)
$options['media']=$media;
return self::tag('link',$options);
}
Generates a link tag that can be inserted in the head section of HTML page. Do not confuse this method with link(). The latter generates a hyperlink.
public static string listBox(string $name, mixed $select, array $data, array $htmlOptions=array (
))
| ||
$name | string | the input name |
$select | mixed | the selected value(s). This can be either a string for single selection or an array for multiple selections. |
$data | array | data for generating the list options (value=>display) You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method. |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special
attributes are also recognized. See clientChange and tag for more details.
In addition, the following options are also supported specifically for list box:
|
{return} | string | the generated list box |
public static function listBox($name,$select,$data,$htmlOptions=array())
{
if(!isset($htmlOptions['size']))
$htmlOptions['size']=4;
if(!empty($htmlOptions['multiple']))
{
if(substr($name,-2)!=='[]')
$name.='[]';
}
return self::dropDownList($name,$select,$data,$htmlOptions);
}
Generates a list box.
public static array listData(array $models, mixed $valueField, mixed $textField, mixed $groupField='')
| ||
$models | array | a list of model objects. This parameter can also be an array of associative arrays (e.g. results of CDbCommand::queryAll). |
$valueField | mixed | the attribute name or anonymous function (PHP 5.3+) for list option values |
$textField | mixed | the attribute name or anonymous function (PHP 5.3+) for list option texts |
$groupField | mixed | the attribute name or anonymous function (PHP 5.3+) for list option group names. If empty, no group will be generated. |
{return} | array | the list data that can be used in dropDownList, listBox, etc. |
public static function listData($models,$valueField,$textField,$groupField='')
{
$listData=array();
if($groupField==='')
{
foreach($models as $model)
{
$value=self::value($model,$valueField);
$text=self::value($model,$textField);
$listData[$value]=$text;
}
}
else
{
foreach($models as $model)
{
$group=self::value($model,$groupField);
$value=self::value($model,$valueField);
$text=self::value($model,$textField);
if($group===null)
$listData[$value]=$text;
else
$listData[$group][$value]=$text;
}
}
return $listData;
}
Generates the data suitable for list-based HTML elements.
The generated data can be used in dropDownList, listBox, checkBoxList,
radioButtonList, and their active-versions (such as activeDropDownList).
Note, this method does not HTML-encode the generated data. You may call encodeArray to
encode it if needed.
Please refer to the value method on how to specify value field, text field and group field.
You can also pass anonymous functions as second, third and fourth arguments which calculates
text field value (PHP 5.3+ only) since 1.1.13. Your anonymous function should receive one argument,
which is the model, the current <option> tag is generated from.
CHtml::listData($posts,'id',function($post) { return CHtml::encode($post->title); });
public static string listOptions(mixed $selection, array $listData, array &$htmlOptions)
| ||
$selection | mixed | the selected value(s). This can be either a string for single selection or an array for multiple selections. |
$listData | array | the option data (see listData) |
$htmlOptions | array | additional HTML attributes. The following two special attributes are recognized:
|
{return} | string | the generated list options |
public static function listOptions($selection,$listData,&$htmlOptions)
{
$raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
$content='';
if(isset($htmlOptions['prompt']))
{
$content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'<','>'=>'>'))."</option>\n";
unset($htmlOptions['prompt']);
}
if(isset($htmlOptions['empty']))
{
if(!is_array($htmlOptions['empty']))
$htmlOptions['empty']=array(''=>$htmlOptions['empty']);
foreach($htmlOptions['empty'] as $value=>$label)
$content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'<','>'=>'>'))."</option>\n";
unset($htmlOptions['empty']);
}
if(isset($htmlOptions['options']))
{
$options=$htmlOptions['options'];
unset($htmlOptions['options']);
}
else
$options=array();
$key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
if(is_array($selection))
{
foreach($selection as $i=>$item)
{
if(is_object($item))
$selection[$i]=$item->$key;
}
}
elseif(is_object($selection))
$selection=$selection->$key;
foreach($listData as $key=>$value)
{
if(is_array($value))
{
$content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
$dummy=array('options'=>$options);
if(isset($htmlOptions['encode']))
$dummy['encode']=$htmlOptions['encode'];
$content.=self::listOptions($selection,$value,$dummy);
$content.='</optgroup>'."\n";
}
else
{
$attributes=array('value'=>(string)$key,'encode'=>!$raw);
if(!is_array($selection) && !strcmp($key,(string)$selection) || is_array($selection) && in_array($key,$selection))
$attributes['selected']='selected';
if(isset($options[$key]))
$attributes=array_merge($attributes,$options[$key]);
$content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
}
}
unset($htmlOptions['key']);
return $content;
}
Generates the list options.
public static string mailto(string $text, string $email='', array $htmlOptions=array (
))
| ||
$text | string | link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. |
string | email address. If this is empty, the first parameter (link body) will be treated as the email address. | |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated mailto link |
public static function mailto($text,$email='',$htmlOptions=array())
{
if($email==='')
$email=$text;
return self::link($text,'mailto:'.$email,$htmlOptions);
}
Generates a mailto link.
public static string metaTag(string $content, string $name=NULL, string $httpEquiv=NULL, array $options=array (
))
| ||
$content | string | content attribute of the meta tag |
$name | string | name attribute of the meta tag. If null, the attribute will not be generated |
$httpEquiv | string | http-equiv attribute of the meta tag. If null, the attribute will not be generated |
$options | array | other options in name-value pairs (e.g. 'scheme', 'lang') |
{return} | string | the generated meta tag |
public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
{
if($name!==null)
$options['name']=$name;
if($httpEquiv!==null)
$options['http-equiv']=$httpEquiv;
$options['content']=$content;
return self::tag('meta',$options);
}
Generates a meta tag that can be inserted in the head section of HTML page.
public static string modelName(CModel|string $model)
| ||
$model | CModel|string | the data model or the model class name |
{return} | string | the generated HTML name value |
public static function modelName($model)
{
if(is_callable(self::$_modelNameConverter))
return call_user_func(self::$_modelNameConverter,$model);
$className=is_object($model) ? get_class($model) : (string)$model;
return trim(str_replace('\\','_',$className),'_');
}
Generates HTML name for given model.
public static string normalizeUrl(mixed $url)
| ||
$url | mixed | the parameter to be used to generate a valid URL |
{return} | string | the normalized URL |
public static function normalizeUrl($url)
{
if(is_array($url))
{
if(isset($url[0]))
{
if(($c=Yii::app()->getController())!==null)
$url=$c->createUrl($url[0],array_splice($url,1));
else
$url=Yii::app()->createUrl($url[0],array_splice($url,1));
}
else
$url='';
}
return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
}
Normalizes the input parameter to be a valid URL.
If the input parameter is an empty string, the currently requested URL will be returned.
If the input parameter is a non-empty string, it is treated as a valid URL and will
be returned without any change.
If the input parameter is an array, it is treated as a controller route and a list of
GET parameters, and the CController::createUrl method will be invoked to
create a URL. In this case, the first array element refers to the controller route,
and the rest key-value pairs refer to the additional GET parameters for the URL.
For example, array('post/list', 'page'=>3)
may be used to generate the URL
/index.php?r=post/list&page=3
.
public static string numberField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function numberField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('number',$name,$value,$htmlOptions);
}
Generates a number field input.
public static string openTag(string $tag, array $htmlOptions=array (
))
| ||
$tag | string | the tag name |
$htmlOptions | array | the element attributes. The values will be HTML-encoded using encode(). If an 'encode' attribute is given and its value is false, the rest of the attribute values will NOT be HTML-encoded. Since version 1.1.5, attributes whose value is null will not be rendered. |
{return} | string | the generated HTML element tag |
public static function openTag($tag,$htmlOptions=array())
{
return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
}
Generates an open HTML element.
public static string pageStateField(string $value)
| ||
$value | string | the persistent page states in serialized format |
{return} | string | the generated hidden field |
public static function pageStateField($value)
{
return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
}
Generates a hidden field for storing persistent page states. This method is internally used by statefulForm.
public static string passwordField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function passwordField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('password',$name,$value,$htmlOptions);
}
Generates a password field input.
public static string radioButton(string $name, boolean $checked=false, array $htmlOptions=array (
))
| ||
$name | string | the input name |
$checked | boolean | whether the radio button is checked |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) Since version 1.1.2, a special option named 'uncheckValue' is available that can be used to specify the value returned when the radio button is not checked. When set, a hidden field is rendered so that when the radio button is not checked, we can still obtain the posted uncheck value. If 'uncheckValue' is not set or set to NULL, the hidden field will not be rendered. |
{return} | string | the generated radio button |
public static function radioButton($name,$checked=false,$htmlOptions=array())
{
if($checked)
$htmlOptions['checked']='checked';
else
unset($htmlOptions['checked']);
$value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
self::clientChange('click',$htmlOptions);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck=null;
if($uncheck!==null)
{
// add a hidden field so that if the radio button is not selected, it still submits a value
if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
$uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
else
$uncheckOptions=array('id'=>false);
if(!empty($htmlOptions['disabled']))
$uncheckOptions['disabled']=$htmlOptions['disabled'];
$hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
}
else
$hidden='';
// add a hidden field so that if the radio button is not selected, it still submits a value
return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
}
Generates a radio button.
public static string radioButtonList(string $name, string $select, array $data, array $htmlOptions=array (
))
| ||
$name | string | name of the radio button list. You can use this name to retrieve the selected value(s) once the form is submitted. |
$select | string | selection of the radio buttons. |
$data | array | value-label pairs used to generate the radio button list. Note, the values will be automatically HTML-encoded, while the labels will not. |
$htmlOptions | array | additional HTML options. The options will be applied to
each radio button input. The following special options are recognized:
|
{return} | string | the generated radio button list |
public static function radioButtonList($name,$select,$data,$htmlOptions=array())
{
$template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
$separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
$container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
$labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
unset($htmlOptions['labelOptions']);
if(isset($htmlOptions['empty']))
{
if(!is_array($htmlOptions['empty']))
$htmlOptions['empty']=array(''=>$htmlOptions['empty']);
$data=CMap::mergeArray($htmlOptions['empty'],$data);
unset($htmlOptions['empty']);
}
$items=array();
$baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
unset($htmlOptions['baseID']);
$id=0;
foreach($data as $value=>$labelTitle)
{
$checked=!strcmp($value,(string)$select);
$htmlOptions['value']=$value;
$htmlOptions['id']=$baseID.'_'.$id++;
$option=self::radioButton($name,$checked,$htmlOptions);
$beginLabel=self::openTag('label',$labelOptions);
$label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
$endLabel=self::closeTag('label');
$items[]=strtr($template,array(
'{input}'=>$option,
'{beginLabel}'=>$beginLabel,
'{label}'=>$label,
'{labelTitle}'=>$labelTitle,
'{endLabel}'=>$endLabel,
));
}
if(empty($container))
return implode($separator,$items);
else
return self::tag($container,array('id'=>$baseID),implode($separator,$items));
}
Generates a radio button list. A radio button list is like a check box list, except that it only allows single selection.
public static string rangeField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function rangeField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('range',$name,$value,$htmlOptions);
}
Generates a range field input.
public static void refresh(integer $seconds, string $url='')
| ||
$seconds | integer | the number of seconds to wait before refreshing the page |
$url | string | the URL to which the page should be redirected to. If empty, it means the current page. |
public static function refresh($seconds,$url='')
{
$content="$seconds";
if($url!=='')
$content.=';url='.self::normalizeUrl($url);
Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
}
Registers a 'refresh' meta tag. This method can be invoked anywhere in a view. It will register a 'refresh' meta tag with CClientScript so that the page can be refreshed in the specified seconds.
public static string renderAttributes(array $htmlOptions)
| ||
$htmlOptions | array | attributes to be rendered |
{return} | string | the rendering result |
public static function renderAttributes($htmlOptions)
{
static $specialAttributes=array(
'autofocus'=>1,
'autoplay'=>1,
'async'=>1,
'checked'=>1,
'controls'=>1,
'declare'=>1,
'default'=>1,
'defer'=>1,
'disabled'=>1,
'formnovalidate'=>1,
'hidden'=>1,
'ismap'=>1,
'itemscope'=>1,
'loop'=>1,
'multiple'=>1,
'muted'=>1,
'nohref'=>1,
'noresize'=>1,
'novalidate'=>1,
'open'=>1,
'readonly'=>1,
'required'=>1,
'reversed'=>1,
'scoped'=>1,
'seamless'=>1,
'selected'=>1,
'typemustmatch'=>1,
);
if($htmlOptions===array())
return '';
$html='';
if(isset($htmlOptions['encode']))
{
$raw=!$htmlOptions['encode'];
unset($htmlOptions['encode']);
}
else
$raw=false;
foreach($htmlOptions as $name=>$value)
{
if(isset($specialAttributes[$name]))
{
if($value===false && $name==='async') {
$html .= ' ' . $name.'="false"';
}
elseif($value)
{
$html .= ' ' . $name;
if(self::$renderSpecialAttributesValue)
$html .= '="' . $name . '"';
}
}
elseif($value!==null)
$html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
}
return $html;
}
Renders the HTML tag attributes. Since version 1.1.5, attributes whose value is null will not be rendered. Special attributes, such as 'checked', 'disabled', 'readonly', will be rendered properly based on their corresponding boolean value.
public static string resetButton(string $label='reset', array $htmlOptions=array (
))
| ||
$label | string | the button label |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated button tag |
public static function resetButton($label='reset',$htmlOptions=array())
{
$htmlOptions['type']='reset';
return self::button($label,$htmlOptions);
}
Generates a reset button.
public static string resolveName(CModel|string $model, string &$attribute)
| ||
$model | CModel|string | the data model |
$attribute | string | the attribute |
{return} | string | the input name |
public static function resolveName($model,&$attribute)
{
$modelName=self::modelName($model);
if(($pos=strpos((string)$attribute,'['))!==false)
{
if($pos!==0) // e.g. name[a][b]
return $modelName.'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
{
$sub=substr($attribute,0,$pos+1);
$attribute=substr($attribute,$pos+1);
return $modelName.$sub.'['.$attribute.']';
}
if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
{
$name=$modelName.'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
$attribute=$matches[1];
return $name;
}
}
return $modelName.'['.$attribute.']';
}
Generates input name for a model attribute. Note, the attribute name may be modified after calling this method if the name contains square brackets (mainly used in tabular input) before the real attribute name.
public static void resolveNameID(CModel|string $model, string &$attribute, array &$htmlOptions)
| ||
$model | CModel|string | the data model |
$attribute | string | the attribute |
$htmlOptions | array | the HTML options |
public static function resolveNameID($model,&$attribute,&$htmlOptions)
{
if(!isset($htmlOptions['name']))
$htmlOptions['name']=self::resolveName($model,$attribute);
if(!isset($htmlOptions['id']))
$htmlOptions['id']=self::getIdByName($htmlOptions['name']);
elseif($htmlOptions['id']===false)
unset($htmlOptions['id']);
}
Generates input name and ID for a model attribute. This method will update the HTML options by setting appropriate 'name' and 'id' attributes. This method may also modify the attribute name if the name contains square brackets (mainly used in tabular input).
public static mixed resolveValue(CModel $model, string $attribute)
| ||
$model | CModel | the data model |
$attribute | string | the attribute name |
{return} | mixed | the attribute value |
public static function resolveValue($model,$attribute)
{
if(($pos=strpos($attribute,'['))!==false)
{
if($pos===0) // [a]name[b][c], should ignore [a]
{
if(preg_match('/\](\w+(\[.+)?)/',$attribute,$matches))
$attribute=$matches[1]; // we get: name[b][c]
if(($pos=strpos($attribute,'['))===false)
return $model->$attribute;
}
$name=substr($attribute,0,$pos);
$value=$model->$name;
foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
{
if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
$value=$value[$id];
else
return null;
}
return $value;
}
else
return $model->$attribute;
}
Evaluates the attribute value of the model. This method can recognize the attribute name written in array format. For example, if the attribute name is 'name[a][b]', the value "$model->name['a']['b']" will be returned.
public static string script(string $text, array $htmlOptions=array (
))
| ||
$text | string | the JavaScript to be enclosed |
$htmlOptions | array | additional HTML attributes (see tag) |
{return} | string | the enclosed JavaScript |
public static function script($text,array $htmlOptions=array())
{
$defaultHtmlOptions=array();
if(self::$setScriptType)
$defaultHtmlOptions['type']='text/javascript';
$htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
if(self::$cdataScriptAndStyleContents)
$text="/*<![CDATA[*/\n{$text}\n/*]]>*/";
return self::tag('script',$htmlOptions,"\n{$text}\n");
}
Encloses the given JavaScript within a script tag.
public static string scriptFile(string $url, array $htmlOptions=array (
))
| ||
$url | string | URL for the JavaScript file |
$htmlOptions | array | additional HTML attributes (see tag) |
{return} | string | the JavaScript file tag |
public static function scriptFile($url,array $htmlOptions=array())
{
$defaultHtmlOptions=array();
if(self::$setScriptType)
$defaultHtmlOptions['type']='text/javascript';
$defaultHtmlOptions['src']=$url;
$htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
return self::tag('script',$htmlOptions,'');
}
Includes a JavaScript file.
public static string searchField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function searchField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('search',$name,$value,$htmlOptions);
}
Generates a search field input.
public static void setModelNameConverter(callable|null $converter)
| ||
$converter | callable|null | the new generator, the model or class name will be passed to this callback and result must be a valid value for HTML name attribute. |
public static function setModelNameConverter($converter)
{
if(is_callable($converter))
self::$_modelNameConverter=$converter;
elseif($converter===null)
self::$_modelNameConverter=null;
else
throw new CException(Yii::t('yii','The $converter argument must be a valid callback or null.'));
}
Set generator used in the CHtml::modelName() method. You can use the `null` value to restore default generator.
public static string statefulForm(mixed $action='', string $method='post', array $htmlOptions=array (
))
| ||
$action | mixed | the form action URL (see normalizeUrl for details about this parameter.) |
$method | string | form method (e.g. post, get) |
$htmlOptions | array | additional HTML attributes (see tag). |
{return} | string | the generated form tag. |
public static function statefulForm($action='',$method='post',$htmlOptions=array())
{
return self::form($action,$method,$htmlOptions)."\n".
self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
}
Generates a stateful form tag. A stateful form tag is similar to form except that it renders an additional hidden field for storing persistent page states. You should use this method to generate a form tag if you want to access persistent page states when the form is submitted.
public static string submitButton(string $label='submit', array $htmlOptions=array (
))
| ||
$label | string | the button label |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated button tag |
public static function submitButton($label='submit',$htmlOptions=array())
{
$htmlOptions['type']='submit';
return self::button($label,$htmlOptions);
}
Generates a submit button.
public static string tag(string $tag, array $htmlOptions=array (
), mixed $content=false, boolean $closeTag=true)
| ||
$tag | string | the tag name |
$htmlOptions | array | the element attributes. The values will be HTML-encoded using encode(). If an 'encode' attribute is given and its value is false, the rest of the attribute values will NOT be HTML-encoded. Since version 1.1.5, attributes whose value is null will not be rendered. |
$content | mixed | the content to be enclosed between open and close element tags. It will not be HTML-encoded. If false, it means there is no body content. |
$closeTag | boolean | whether to generate the close tag. |
{return} | string | the generated HTML element tag |
public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
{
$html='<' . $tag . self::renderAttributes($htmlOptions);
if($content===false)
return $closeTag && self::$closeSingleTags ? $html.' />' : $html.'>';
else
return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
}
Generates an HTML element.
public static string telField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function telField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('tel',$name,$value,$htmlOptions);
}
Generates a telephone field input.
public static string textArea(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated text area |
public static function textArea($name,$value='',$htmlOptions=array())
{
$htmlOptions['name']=$name;
if(!isset($htmlOptions['id']))
$htmlOptions['id']=self::getIdByName($name);
elseif($htmlOptions['id']===false)
unset($htmlOptions['id']);
self::clientChange('change',$htmlOptions);
return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
}
Generates a text area input.
public static string textField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function textField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('text',$name,$value,$htmlOptions);
}
Generates a text field input.
public static string timeField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function timeField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('time',$name,$value,$htmlOptions);
}
Generates a time field input.
public static string urlField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function urlField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('url',$name,$value,$htmlOptions);
}
Generates a URL field input.
public static mixed value(mixed $model, mixed $attribute, mixed $defaultValue=NULL)
| ||
$model | mixed | the model. This can be either an object or an array. |
$attribute | mixed | the attribute name (use dot to concatenate multiple attributes) or anonymous function (PHP 5.3+). Remember that functions created by "create_function" are not supported by this method. Also note that numeric value is meaningless when first parameter is object typed. |
$defaultValue | mixed | the default value to return when the attribute does not exist. |
{return} | mixed | the attribute value. |
public static function value($model,$attribute,$defaultValue=null)
{
if(is_scalar($attribute) || $attribute===null)
foreach(explode('.',(string)$attribute) as $name)
{
if(is_object($model))
{
if ((version_compare(PHP_VERSION, '7.2.0', '>=')
&& is_numeric($name))
|| !isset($model->$name)
)
{
return $defaultValue;
}
else
{
$model=$model->$name;
}
}
elseif(is_array($model) && isset($model[$name]))
$model=$model[$name];
else
return $defaultValue;
}
else
return call_user_func($attribute,$model);
return $model;
}
Evaluates the value of the specified attribute for the given model.
The attribute name can be given in a dot syntax. For example, if the attribute
is "author.firstName", this method will return the value of "$model->author->firstName".
A default value (passed as the last parameter) will be returned if the attribute does
not exist or is broken in the middle (e.g. $model->author is null).
The model can be either an object or an array. If the latter, the attribute is treated
as a key of the array. For the example of "author.firstName", if would mean the array value
"$model['author']['firstName']".
Anonymous function could also be used for attribute calculation since 1.1.13
($attribute parameter; PHP 5.3+ only) as follows:
$taskClosedSecondsAgo=CHtml::value($closedTask,function($model) { return time()-$model->closed_at; });Your anonymous function should receive one argument, which is the model, the current value is calculated from. This feature could be used together with the listData. Please refer to its documentation for more details.
public static string weekField(string $name, string $value='', array $htmlOptions=array (
))
| ||
$name | string | the input name |
$value | string | the input value |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.) |
{return} | string | the generated input field |
public static function weekField($name,$value='',$htmlOptions=array())
{
self::clientChange('change',$htmlOptions);
return self::inputField('week',$name,$value,$htmlOptions);
}
Generates a week field input.
Using CHtml::listData();
To use
CHtml::listData()
, make sure to return the posts you want to show, not just the model class itself.CHtml::listData(MyModel::model()->findAll(), 'MyModelID', 'Value');
About what's encoded
It is important to note that all given
$htmlOptions
will be encoded (unless you set$htmlOptions['encode'] = false
).And also that if a
$content
is given totag()
(for examplelink()
's$text
attribute) that content will not encoded.See the code
tag()
andrenderAttributes()
.submitButton or htmlButton?
As documentation states, the only difference between these two functions is that first generates button using input tag, while second - using button tag. And the only difference (at least known to me) between these two tags is that you should avoid using submit buttons (as good as reset buttons - both build upon input tag) outside forms. As this is against strict rules of XHTML 1.0.
In other words: if you just want to draw a clickable button that will work exactly as a link - it is better to use htmlButton function for this purpose and submitButton function - anywhere inside any form.
Rendering DIVs with CHtml::tag
Make sure you render empty DIV tags like this:
echo CHtml::tag('div', $this->htmlOptions, "");
$content must not be null, otherwise Yii would render
which may break your layout.
With the above command it renders
AjaxLink & CSRF Validation
I ran into a problem trying to get my ajaxLink to work, as I kept running into a CHttpException 400 error. But this same implementation had worked before, so I did not understand why it wasn't functioning.
The culprit was my enabling of Cross-Site Request Forgery Validation to "true" in my main config file.
To enable my ajaxLink to work while still having this validation in my config file, I simply added the following to my params in my 'data' array:
'data'=>array( 'something_something_here'=>$variable, ... Yii::app()->request->csrfTokenName => Yii::app()->request->csrfToken), 'something_something_here'=>$variable, ... ...
Note that even setting 'csrf' to true for the htmlOptions array in my ajaxLink did not work, so this solution fixed the problem.
For a more detailed discussion, see the CSRF study from Stanford
ajaxSubmitButton ajax options
You can map basically every event (and even validate on the fly).
<?php echo CHtml::ajaxSubmitButton( 'Send', CHtml::normalizeUrl(array('site/ajaxSubmit')), array( 'error'=>'js:function(){ alert(\'error\'); }', //if you add a return false in this, it will not submit. 'beforeSend'=>'js:function(){ alert(\'beforeSend\'); }', 'success'=>'js:function(data){ alert(\'success, data from server: \'+data); }', 'complete'=>'js:function(){ alert(\'complete\'); }', //'update'=>'#where_to_put_the_response', ) ); ?>
ajaxSubmitButton not working with validation
After playing around with a form, which I wanted to submit via Ajax, I soon discovered that "afterValidate" has no effect and the form was being submitted even with validation errors.
I found the answer here:
http://code.google.com/p/yii/issues/detail?id=2008
NOTE: Comment 7 & 8 gave the answer.
The solution is to use a normal submit button and have the afterValidate function perform the Ajax post if no errors exist.
Trigger onchange submit on form input element: the Yii way
The documentation is not 100% clear, but you simply have to set the 'submit' property of the htmlOptions. Example:
echo CHtml::dropDownList('fooBar', .., .., array( 'submit' => '', // set empty );
Which will generate code in the jQuery onready handler:
$('body').on('change','#fooBar',function(){jQuery.yii.submitForm(this,'',{});
Ajax update
I think ajax update must be here, i spent a lot of time searching for this...
<div id="forAjaxRefresh"></div> <?php echo CHtml::ajaxLink('clickMe', array('ajax'), array('update'=>'#forAjaxRefresh'));?>
Here the complete wiki: Ajax Update
Signup or Login in order to comment.