/framework/web/helpers/CHtml.php
PHP | 2221 lines | 1107 code | 109 blank | 1005 comment | 138 complexity | 6b2e4e429e880392769792b7690aba10 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, BSD-2-Clause, GPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * CHtml class file.
- *
- * @author Qiang Xue <qiang.xue@gmail.com>
- * @link http://www.yiiframework.com/
- * @copyright Copyright © 2008-2011 Yii Software LLC
- * @license http://www.yiiframework.com/license/
- */
- /**
- * CHtml is a static class that provides a collection of helper methods for creating HTML views.
- *
- * @author Qiang Xue <qiang.xue@gmail.com>
- * @version $Id$
- * @package system.web.helpers
- * @since 1.0
- */
- class CHtml
- {
- const ID_PREFIX='yt';
- /**
- * @var string the CSS class for displaying error summaries (see {@link errorSummary}).
- */
- public static $errorSummaryCss='errorSummary';
- /**
- * @var string the CSS class for displaying error messages (see {@link error}).
- */
- public static $errorMessageCss='errorMessage';
- /**
- * @var string the CSS class for highlighting error inputs. Form inputs will be appended
- * with this CSS class if they have input errors.
- */
- public static $errorCss='error';
- /**
- * @var string the CSS class for required labels. Defaults to 'required'.
- * @see label
- */
- public static $requiredCss='required';
- /**
- * @var string the HTML code to be prepended to the required label.
- * @see label
- */
- public static $beforeRequiredLabel='';
- /**
- * @var string the HTML code to be appended to the required label.
- * @see label
- */
- public static $afterRequiredLabel=' <span class="required">*</span>';
- /**
- * @var integer the counter for generating automatic input field names.
- */
- public static $count=0;
- /**
- * 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 {@link clientChange}).
- *
- * For more information about attaching jQuery event handler see {@link http://api.jquery.com/on/}
- * @since 1.1.9
- * @see clientChange
- */
- public static $liveEvents = true;
- /**
- * Encodes special characters into HTML entities.
- * The {@link CApplication::charset application charset} will be used for encoding.
- * @param string $text data to be encoded
- * @return string the encoded data
- * @see http://www.php.net/manual/en/function.htmlspecialchars.php
- */
- public static function encode($text)
- {
- return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
- }
- /**
- * Decodes special HTML entities back to the corresponding characters.
- * This is the opposite of {@link encode()}.
- * @param string $text data to be decoded
- * @return string the decoded data
- * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
- * @since 1.1.8
- */
- public static function decode($text)
- {
- return htmlspecialchars_decode($text,ENT_QUOTES);
- }
- /**
- * 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 {@link CApplication::charset application charset} will be used for encoding.
- * @param array $data data to be encoded
- * @return array the encoded data
- * @see http://www.php.net/manual/en/function.htmlspecialchars.php
- */
- 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);
- else if(is_array($value))
- $value=self::encodeArray($value);
- $d[$key]=$value;
- }
- return $d;
- }
- /**
- * Generates an HTML element.
- * @param string $tag the tag name
- * @param array $htmlOptions the element attributes. The values will be HTML-encoded using {@link 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.
- * @param mixed $content 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.
- * @param boolean $closeTag 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 ? $html.' />' : $html.'>';
- else
- return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
- }
- /**
- * Generates an open HTML element.
- * @param string $tag the tag name
- * @param array $htmlOptions the element attributes. The values will be HTML-encoded using {@link 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 a close HTML element.
- * @param string $tag the tag name
- * @return string the generated HTML element tag
- */
- public static function closeTag($tag)
- {
- return '</'.$tag.'>';
- }
- /**
- * Encloses the given string within a CDATA tag.
- * @param string $text the string to be enclosed
- * @return string the CDATA tag with the enclosed content.
- */
- public static function cdata($text)
- {
- return '<![CDATA[' . $text . ']]>';
- }
- /**
- * Generates a meta tag that can be inserted in the head section of HTML page.
- * @param string $content content attribute of the meta tag
- * @param string $name name attribute of the meta tag. If null, the attribute will not be generated
- * @param string $httpEquiv http-equiv attribute of the meta tag. If null, the attribute will not be generated
- * @param array $options 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 link tag that can be inserted in the head section of HTML page.
- * Do not confuse this method with {@link link()}. The latter generates a hyperlink.
- * @param string $relation rel attribute of the link tag. If null, the attribute will not be generated.
- * @param string $type type attribute of the link tag. If null, the attribute will not be generated.
- * @param string $href href attribute of the link tag. If null, the attribute will not be generated.
- * @param string $media media attribute of the link tag. If null, the attribute will not be generated.
- * @param array $options 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);
- }
- /**
- * Encloses the given CSS content with a CSS tag.
- * @param string $text the CSS content
- * @param string $media 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.'"';
- return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
- }
- /**
- * Registers a 'refresh' meta tag.
- * This method can be invoked anywhere in a view. It will register a 'refresh'
- * meta tag with {@link CClientScript} so that the page can be refreshed in
- * the specified seconds.
- * @param integer $seconds the number of seconds to wait before refreshing the page
- * @param string $url the URL to which the page should be redirected to. If empty, it means the current page.
- * @since 1.1.1
- */
- public static function refresh($seconds, $url='')
- {
- $content="$seconds";
- if($url!=='')
- $content.=';'.self::normalizeUrl($url);
- Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
- }
- /**
- * Links to the specified CSS file.
- * @param string $url the CSS URL
- * @param string $media the media that this CSS should apply to.
- * @return string the CSS link.
- */
- public static function cssFile($url,$media='')
- {
- if($media!=='')
- $media=' media="'.$media.'"';
- return '<link rel="stylesheet" type="text/css" href="'.self::encode($url).'"'.$media.' />';
- }
- /**
- * Encloses the given JavaScript within a script tag.
- * @param string $text the JavaScript to be enclosed
- * @return string the enclosed JavaScript
- */
- public static function script($text)
- {
- return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
- }
- /**
- * Includes a JavaScript file.
- * @param string $url URL for the JavaScript file
- * @return string the JavaScript file tag
- */
- public static function scriptFile($url)
- {
- return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
- }
- /**
- * Generates an opening form tag.
- * This is a shortcut to {@link beginForm}.
- * @param mixed $action the form action URL (see {@link normalizeUrl} for details about this parameter.)
- * @param string $method form method (e.g. post, get)
- * @param array $htmlOptions additional HTML attributes (see {@link 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.
- * Note, only the open tag is generated. A close tag should be placed manually
- * at the end of the form.
- * @param mixed $action the form action URL (see {@link normalizeUrl} for details about this parameter.)
- * @param string $method form method (e.g. post, get)
- * @param array $htmlOptions additional HTML attributes (see {@link tag}).
- * @return string the generated form tag.
- * @see endForm
- */
- public static function beginForm($action='',$method='post',$htmlOptions=array())
- {
- $htmlOptions['action']=$url=self::normalizeUrl($action);
- $htmlOptions['method']=$method;
- $form=self::tag('form',$htmlOptions,false,false);
- $hiddens=array();
- if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
- {
- foreach(explode('&',substr($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));
- }
- }
- $request=Yii::app()->request;
- if($request->enableCsrfValidation && !strcasecmp($method,'post'))
- $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
- if($hiddens!==array())
- $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
- return $form;
- }
- /**
- * Generates a closing form tag.
- * @return string the generated tag
- * @see beginForm
- */
- public static function endForm()
- {
- return '</form>';
- }
- /**
- * Generates a stateful form tag.
- * A stateful form tag is similar to {@link 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.
- * @param mixed $action the form action URL (see {@link normalizeUrl} for details about this parameter.)
- * @param string $method form method (e.g. post, get)
- * @param array $htmlOptions additional HTML attributes (see {@link 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 hidden field for storing persistent page states.
- * This method is internally used by {@link statefulForm}.
- * @param string $value 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 hyperlink tag.
- * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag.
- * @param mixed $url a URL or an action route that can be used to create a URL.
- * See {@link normalizeUrl} for more details about how to specify this parameter.
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated hyperlink
- * @see normalizeUrl
- * @see clientChange
- */
- 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 mailto link.
- * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag.
- * @param string $email email address. If this is empty, the first parameter (link body) will be treated as the email address.
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated mailto link
- * @see clientChange
- */
- public static function mailto($text,$email='',$htmlOptions=array())
- {
- if($email==='')
- $email=$text;
- return self::link($text,'mailto:'.$email,$htmlOptions);
- }
- /**
- * Generates an image tag.
- * @param string $src the image URL
- * @param string $alt the alternative text display
- * @param array $htmlOptions additional HTML attributes (see {@link 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 a button.
- * @param string $label the button label
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated button tag
- * @see clientChange
- */
- 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['value']=$label;
- self::clientChange('click',$htmlOptions);
- return self::tag('input',$htmlOptions);
- }
- /**
- * Generates a button using HTML button tag.
- * This method is similar to {@link button} except that it generates a 'button'
- * tag instead of 'input' tag.
- * @param string $label the button label. Note that this value will be directly inserted in the button element
- * without being HTML-encoded.
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated button tag
- * @see clientChange
- */
- 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 submit button.
- * @param string $label the button label
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated button tag
- * @see clientChange
- */
- public static function submitButton($label='submit',$htmlOptions=array())
- {
- $htmlOptions['type']='submit';
- return self::button($label,$htmlOptions);
- }
- /**
- * Generates a reset button.
- * @param string $label the button label
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated button tag
- * @see clientChange
- */
- public static function resetButton($label='reset',$htmlOptions=array())
- {
- $htmlOptions['type']='reset';
- return self::button($label,$htmlOptions);
- }
- /**
- * Generates an image submit button.
- * @param string $src the image URL
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated button tag
- * @see clientChange
- */
- public static function imageButton($src,$htmlOptions=array())
- {
- $htmlOptions['src']=$src;
- $htmlOptions['type']='image';
- return self::button('submit',$htmlOptions);
- }
- /**
- * Generates a link submit button.
- * @param string $label the button label
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated button tag
- * @see clientChange
- */
- 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 label tag.
- * @param string $label label text. Note, you should HTML-encode the text if needed.
- * @param string $for 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.
- * @param array $htmlOptions additional HTML attributes.
- * The following HTML option is recognized:
- * <ul>
- * <li>required: if this is set and is true, the label will be styled
- * with CSS class 'required' (customizable with CHtml::$requiredCss),
- * and be decorated with {@link CHtml::beforeRequiredLabel} and
- * {@link CHtml::afterRequiredLabel}.</li>
- * </ul>
- * @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 text field input.
- * @param string $name the input name
- * @param string $value the input value
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated input field
- * @see clientChange
- * @see inputField
- */
- public static function textField($name,$value='',$htmlOptions=array())
- {
- self::clientChange('change',$htmlOptions);
- return self::inputField('text',$name,$value,$htmlOptions);
- }
- /**
- * Generates a hidden input.
- * @param string $name the input name
- * @param string $value the input value
- * @param array $htmlOptions additional HTML attributes (see {@link tag}).
- * @return string the generated input field
- * @see inputField
- */
- public static function hiddenField($name,$value='',$htmlOptions=array())
- {
- return self::inputField('hidden',$name,$value,$htmlOptions);
- }
- /**
- * Generates a password field input.
- * @param string $name the input name
- * @param string $value the input value
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated input field
- * @see clientChange
- * @see inputField
- */
- public static function passwordField($name,$value='',$htmlOptions=array())
- {
- self::clientChange('change',$htmlOptions);
- return self::inputField('password',$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).
- * @param string $name the input name
- * @param string $value the input value
- * @param array $htmlOptions additional HTML attributes (see {@link tag}).
- * @return string the generated input field
- * @see inputField
- */
- public static function fileField($name,$value='',$htmlOptions=array())
- {
- return self::inputField('file',$name,$value,$htmlOptions);
- }
- /**
- * Generates a text area input.
- * @param string $name the input name
- * @param string $value the input value
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated text area
- * @see clientChange
- * @see inputField
- */
- public static function textArea($name,$value='',$htmlOptions=array())
- {
- $htmlOptions['name']=$name;
- if(!isset($htmlOptions['id']))
- $htmlOptions['id']=self::getIdByName($name);
- else if($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 radio button.
- * @param string $name the input name
- * @param boolean $checked whether the radio button is checked
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link 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
- * @see clientChange
- * @see inputField
- */
- 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);
- $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 check box.
- * @param string $name the input name
- * @param boolean $checked whether the check box is checked
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link 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
- * @see clientChange
- * @see inputField
- */
- 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 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);
- $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
- }
- else
- $hidden='';
- // add a hidden field so that if the checkbox is not selected, it still submits a value
- return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
- }
- /**
- * Generates a drop down list.
- * @param string $name the input name
- * @param string $select the selected value
- * @param array $data data for generating the list options (value=>display).
- * You may use {@link listData} to generate this data.
- * Please refer to {@link 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.
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are recognized. See {@link clientChange} and {@link tag} for more details.
- * In addition, the following options are also supported specifically for dropdown list:
- * <ul>
- * <li>encode: boolean, specifies whether to encode the values. Defaults to true.</li>
- * <li>prompt: string, specifies the prompt text shown as the first list option. Its value is empty. Note, the prompt text will NOT be HTML-encoded.</li>
- * <li>empty: string, specifies the text corresponding to empty selection. Its value is empty.
- * The 'empty' option can also be an array of value-label pairs.
- * Each pair will be used to render a list option at the beginning. Note, the text label will NOT be HTML-encoded.</li>
- * <li>options: array, specifies additional attributes for each OPTION tag.
- * The array keys must be the option values, and the array values are the extra
- * OPTION tag attributes in the name-value pairs. For example,
- * <pre>
- * array(
- * 'value1'=>array('disabled'=>true, 'label'=>'value 1'),
- * 'value2'=>array('label'=>'value 2'),
- * );
- * </pre>
- * </li>
- * </ul>
- * @return string the generated drop down list
- * @see clientChange
- * @see inputField
- * @see listData
- */
- public static function dropDownList($name,$select,$data,$htmlOptions=array())
- {
- $htmlOptions['name']=$name;
- if(!isset($htmlOptions['id']))
- $htmlOptions['id']=self::getIdByName($name);
- else if($htmlOptions['id']===false)
- unset($htmlOptions['id']);
- self::clientChange('change',$htmlOptions);
- $options="\n".self::listOptions($select,$data,$htmlOptions);
- return self::tag('select',$htmlOptions,$options);
- }
- /**
- * Generates a list box.
- * @param string $name the input name
- * @param mixed $select the selected value(s). This can be either a string for single selection or an array for multiple selections.
- * @param array $data data for generating the list options (value=>display)
- * You may use {@link listData} to generate this data.
- * Please refer to {@link 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.
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized. See {@link clientChange} and {@link tag} for more details.
- * In addition, the following options are also supported specifically for list box:
- * <ul>
- * <li>encode: boolean, specifies whether to encode the values. Defaults to true.</li>
- * <li>prompt: string, specifies the prompt text shown as the first list option. Its value is empty. Note, the prompt text will NOT be HTML-encoded.</li>
- * <li>empty: string, specifies the text corresponding to empty selection. Its value is empty.
- * The 'empty' option can also be an array of value-label pairs.
- * Each pair will be used to render a list option at the beginning. Note, the text label will NOT be HTML-encoded.</li>
- * <li>options: array, specifies additional attributes for each OPTION tag.
- * The array keys must be the option values, and the array values are the extra
- * OPTION tag attributes in the name-value pairs. For example,
- * <pre>
- * array(
- * 'value1'=>array('disabled'=>true, 'label'=>'value 1'),
- * 'value2'=>array('label'=>'value 2'),
- * );
- * </pre>
- * </li>
- * </ul>
- * @return string the generated list box
- * @see clientChange
- * @see inputField
- * @see listData
- */
- public static function listBox($name,$select,$data,$htmlOptions=array())
- {
- if(!isset($htmlOptions['size']))
- $htmlOptions['size']=4;
- if(isset($htmlOptions['multiple']))
- {
- if(substr($name,-2)!=='[]')
- $name.='[]';
- }
- return self::dropDownList($name,$select,$data,$htmlOptions);
- }
- /**
- * Generates a check box list.
- * A check box list allows multiple selection, like {@link listBox}.
- * As a result, the corresponding POST value is an array.
- * @param string $name name of the check box list. You can use this name to retrieve
- * the selected value(s) once the form is submitted.
- * @param mixed $select selection of the check boxes. This can be either a string
- * for single selection or an array for multiple selections.
- * @param array $data value-label pairs used to generate the check box list.
- * Note, the values will be automatically HTML-encoded, while the labels will not.
- * @param array $htmlOptions addtional HTML options. The options will be applied to
- * each checkbox input. The following special options are recognized:
- * <ul>
- * <li>template: string, specifies how each checkbox is rendered. Defaults
- * to "{input} {label}", where "{input}" will be replaced by the generated
- * check box input tag while "{label}" be replaced by the corresponding check box label.</li>
- * <li>separator: string, specifies the string that separates the generated check boxes.</li>
- * <li>checkAll: string, specifies the label for the "check all" checkbox.
- * If this option is specified, a 'check all' checkbox will be displayed. Clicking on
- * this checkbox will cause all checkboxes checked or unchecked.</li>
- * <li>checkAllLast: boolean, specifies whether the 'check all' checkbox should be
- * displayed at the end of the checkbox list. If this option is not set (default)
- * or is false, the 'check all' checkbox will be displayed at the beginning of
- * the checkbox list.</li>
- * <li>labelOptions: array, specifies the additional HTML attributes to be rendered
- * for every label tag in the list.</li>
- * <li>container: string, specifies the checkboxes enclosing tag. Defaults to 'span'.
- * If the value is an empty string, no enclosing tag will be generated</li>
- * </ul>
- * @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']:"<br/>\n";
- $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=self::getIdByName($name);
- $id=0;
- $checkAll=true;
- foreach($data as $value=>$label)
- {
- $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
- $checkAll=$checkAll && $checked;
- $htmlOptions['value']=$value;
- $htmlOptions['id']=$baseID.'_'.$id++;
- $option=self::checkBox($name,$checked,$htmlOptions);
- $label=self::label($label,$htmlOptions['id'],$labelOptions);
- $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
- }
- if(isset($checkAllLabel))
- {
- $htmlOptions['value']=1;
- $htmlOptions['id']=$id=$baseID.'_all';
- $option=self::checkBox($id,$checkAll,$htmlOptions);
- $label=self::label($checkAllLabel,$id,$labelOptions);
- $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
- if($checkAllLast)
- $items[]=$item;
- else
- array_unshift($items,$item);
- $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
- $js=<<<EOD
- $('#$id').click(function() {
- $("input[name='$name']").prop('checked', this.checked);
- });
- $("input[name='$name']").click(function() {
- $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
- });
- $('#$id').prop('checked', !$("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 radio button list.
- * A radio button list is like a {@link checkBoxList check box list}, except that
- * it only allows single selection.
- * @param string $name name of the radio button list. You can use this name to retrieve
- * the selected value(s) once the form is submitted.
- * @param string $select selection of the radio buttons.
- * @param array $data value-label pairs used to generate the radio button list.
- * Note, the values will be automatically HTML-encoded, while the labels will not.
- * @param array $htmlOptions addtional HTML options. The options will be applied to
- * each radio button input. The following special options are recognized:
- * <ul>
- * <li>template: string, specifies how each radio button is rendered. Defaults
- * to "{input} {label}", where "{input}" will be replaced by the generated
- * radio button input tag while "{label}" will be replaced by the corresponding radio button label.</li>
- * <li>separator: string, specifies the string that separates the generated radio buttons. Defaults to new line (<br/>).</li>
- * <li>labelOptions: array, specifies the additional HTML attributes to be rendered
- * for every label tag in the list.</li>
- * <li>container: string, specifies the radio buttons enclosing tag. Defaults to 'span'.
- * If the value is an empty string, no enclosing tag will be generated</li>
- * </ul>
- * @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']:"<br/>\n";
- $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
- unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
- $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
- unset($htmlOptions['labelOptions']);
- $items=array();
- $baseID=self::getIdByName($name);
- $id=0;
- foreach($data as $value=>$label)
- {
- $checked=!strcmp($value,$select);
- $htmlOptions['value']=$value;
- $htmlOptions['id']=$baseID.'_'.$id++;
- $option=self::radioButton($name,$checked,$htmlOptions);
- $label=self::label($label,$htmlOptions['id'],$labelOptions);
- $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
- }
- if(empty($container))
- return implode($separator,$items);
- else
- return self::tag($container,array('id'=>$baseID),implode($separator,$items));
- }
- /**
- * Generates a link that can initiate AJAX requests.
- * @param string $text the link body (it will NOT be HTML-encoded.)
- * @param mixed $url the URL for the AJAX request. If empty, it is assumed to be the current URL. See {@link normalizeUrl} for more details.
- * @param array $ajaxOptions AJAX options (see {@link ajax})
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated link
- * @see normalizeUrl
- * @see ajax
- */
- 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 push button that can initiate AJAX requests.
- * @param string $label the button label
- * @param mixed $url the URL for the AJAX request. If empty, it is assumed to be the current URL. See {@link normalizeUrl} for more details.
- * @param array $ajaxOptions AJAX options (see {@link ajax})
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link 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 submit the current form in POST method.
- * @param string $label the button label
- * @param mixed $url the URL for the AJAX request. If empty, it is assumed to be the current URL. See {@link normalizeUrl} for more details.
- * @param array $ajaxOptions AJAX options (see {@link ajax})
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link 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 the JavaScript that initiates an AJAX request.
- * @param array $options AJAX options. The valid options are specified in the jQuery ajax documentation.
- * The following special options are added for convenience:
- * <ul>
- * <li>update: string, specifies the selector whose HTML content should be replaced
- * by the AJAX request result.</li>
- * <li>replace: string, specifies the selector whose target should be replaced
- * by the AJAX request result.</li>
- * </ul>
- * Note, if you specify the 'success' option, the above options will be ignored.
- * @return string the generated JavaScript
- * @see http://docs.jquery.com/Ajax/jQuery.ajax#options
- */
- 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 URL for the published assets.
- * @param string $path the path of the asset to be published
- * @param boolean $hashByName 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);
- }
- /**
- * 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 {@link 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, <code>array('post/list', 'page'=>3)</code> may be used to generate the URL
- * <code>/index.php?r=post/list&page=3</code>.
- *
- * @param mixed $url 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;
- }
- /**
- * Generates an input HTML tag.
- * This method generates an input HTML tag based on the given input name and value.
- * @param string $type the input type (e.g. 'text', 'radio')
- * @param string $name the input name
- * @param string $value the input value
- * @param array $htmlOptions additional HTML attributes for the HTML tag (see {@link 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);
- else if($htmlOptions['id']===false)
- unset($htmlOptions['id']);
- return self::tag('input',$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 {@link CModel::getAttributeLabel}.
- * If the attribute has input error, the label's CSS class will be appended with {@link errorCss}.
- * @param CModel $model the data model
- * @param string $attribute the attribute
- * @param array $htmlOptions additional HTML attributes. The following special options are recognized:
- * <ul>
- * <li>required: if this is set and is true, the label will be styled
- * with CSS class 'required' (customizable with CHtml::$requiredCss),
- * and be decorated with {@link CHtml::beforeRequiredLabel} and
- * {@link CHtml::afterRequiredLabel}.</li>
- * <li>label: this specifies the label to be displayed. If this is not set,
- * {@link CModel::getAttributeLabel} will be called to get the label for display.
- * If the label is specified as false, no label will be rendered.</li>
- * </ul>
- * @return string the generated label tag
- */
- public static function activeLabel($model,$attribute,$htmlOptions=array())
- {
- if(isset($htmlOptions['for']))
- {
- $for=$htmlOptions['for'];
- unset($htmlOptions['for']);
- }
- else
- $for=self::getIdByName(self::resolveName($model,$attribute));
- 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.
- * This is an enhanced version of {@link activeLabel}. It will render additional
- * CSS class and mark when the attribute is required.
- * In particular, it calls {@link CModel::isAttributeRequired} to determine
- * if the attribute is required.
- * If so, it will add a CSS class {@link CHtml::requiredCss} to the label,
- * and decorate the label with {@link CHtml::beforeRequiredLabel} and
- * {@link CHtml::afterRequiredLabel}.
- * @param CModel $model the data model
- * @param string $attribute the attribute
- * @param array $htmlOptions 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
- $htmlOptions['required']=$model->isAttributeRequired($attribute);
- return self::activeLabel($model,$realAttribute,$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 {@link errorCss}.
- * @param CModel $model the data model
- * @param string $attribute the attribute
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated input field
- * @see clientChange
- * @see activeInputField
- */
- 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 url field input for a model attribute.
- * If the attribute has input error, the input field's CSS class will
- * be appended with {@link errorCss}.
- * @param CModel $model the data model
- * @param string $attribute the attribute
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated input field
- * @see clientChange
- * @see activeInputField
- * @since 1.1.11
- */
- 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 an email field input for a model attribute.
- * If the attribute has input error, the input field's CSS class will
- * be appended with {@link errorCss}.
- * @param CModel $model the data model
- * @param string $attribute the attribute
- * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
- * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
- * @return string the generated input field
- * @see clientChange
- * @see activeInputField
- * @since 1.1.11
- */
- public static function activeEmailField($model,$attribute,$htmlOptions=array())
- {
- self::resolveNameID($model,$attribute,$htmlOpt…
Large files files are truncated, but you can click here to view the full file