0 follower

CListView

Package zii.widgets
Inheritance class CListView » CBaseListView » CWidget » CBaseController » CComponent
Since 1.1
Source Code framework/zii/widgets/CListView.php
CListView displays a list of data items in terms of a list.

Unlike CGridView which displays the data items in a table, CListView allows one to use a view template to render each data item. As a result, CListView could generate more flexible rendering result.

CListView supports both sorting and pagination of the data items. The sorting and pagination can be done in AJAX mode or normal page request. A benefit of using CListView is that when the user browser disables JavaScript, the sorting and pagination automatically degenerate to normal page requests and are still functioning as expected.

CListView should be used together with a data provider, preferably a CActiveDataProvider.

The minimal code needed to use CListView is as follows:

$dataProvider=new CActiveDataProvider('Post');

$this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_post',   // refers to the partial view named '_post'
    'sortableAttributes'=>array(
        'title',
        'create_time'=>'Post Time',
    ),
));


The above code first creates a data provider for the Post ActiveRecord class. It then uses CListView to display every data item as returned by the data provider. The display is done via the partial view named '_post'. This partial view will be rendered once for every data item. In the view, one can access the current data item via variable $data. For more details, see itemView.

In order to support sorting, one has to specify the sortableAttributes property. By doing so, a list of hyperlinks that can sort the data will be displayed.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
actionPrefix string the prefix to the IDs of the actions. CWidget
afterAjaxUpdate string a javascript function that will be invoked after a successful AJAX response is received. CListView
ajaxType string the type ('GET' or 'POST') of the AJAX requests. CListView
ajaxUpdate mixed the ID of the container whose content may be updated with an AJAX response. CListView
ajaxUpdateError string a javascript function that will be invoked if an AJAX update error occurs. CListView
ajaxUrl mixed the URL for the AJAX requests should be sent to. CListView
ajaxVar string the name of the GET variable that indicates the request is an AJAX request triggered by this widget. CListView
baseScriptUrl string the base script URL for all list view resources (e.g. javascript, CSS file, images). CListView
beforeAjaxUpdate string a javascript function that will be invoked before an AJAX update occurs. CListView
controller CController Returns the controller that this widget belongs to. CWidget
cssFile string the URL of the CSS file used by this list view. CListView
dataProvider IDataProvider the data provider for the view. CBaseListView
emptyCssClass string the CSS class name for the container of the emptyText property. CBaseListView
emptyTagName string the HTML tag name for the container of the emptyText property. CBaseListView
emptyText string the message to be displayed when dataProvider does not have any data. CBaseListView
enableHistory boolean whether to leverage the {@link https://developer. CListView
enablePagination boolean whether to enable pagination. CBaseListView
enableSorting boolean whether to enable sorting. CBaseListView
htmlOptions array the HTML options for the view container tag. CBaseListView
id string Returns the ID of the widget or generates a new one if requested. CWidget
itemView string the view used for rendering each data item. CListView
itemsCssClass string the CSS class name for the container of all data item display. CBaseListView
itemsTagName string the HTML tag name for the container of all data item display. CListView
loadingCssClass string the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. CListView
owner CBaseController Returns the owner/creator of this widget. CWidget
pager array|string the configuration for the pager. CBaseListView
pagerCssClass string the CSS class name for the pager container. CBaseListView
separator string the HTML code to be displayed between any two consecutive items. CListView
skin mixed the name of the skin to be used by this widget. CWidget
sortableAttributes array list of sortable attribute names. CListView
sorterCssClass string the CSS class name for the sorter container. CListView
sorterFooter string the text shown after sort links. CListView
sorterHeader string the text shown before sort links. CListView
summaryCssClass string the CSS class name for the summary text container. CBaseListView
summaryTagName string the HTML tag name for the container of the summaryText property. CBaseListView
summaryText string the summary text template for the view. CBaseListView
tagName string the tag name for the view container. CBaseListView
template string the template to be used to control the layout of various components in the list view. CListView
updateSelector string the jQuery selector of the HTML elements that may trigger AJAX updates when they are clicked. CListView
viewData array additional data to be passed to itemView when rendering each data item. CListView
viewPath string Returns the directory containing the view files for this widget. CWidget

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CWidget
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
actions() Returns a list of actions that are used by this widget. CWidget
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
beginCache() Begins fragment caching. CBaseController
beginClip() Begins recording a clip. CBaseController
beginContent() Begins the rendering of content that is to be decorated by the specified view. CBaseController
beginWidget() Creates a widget and executes it. CBaseController
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
createWidget() Creates a widget and initializes it. CBaseController
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
endCache() Ends fragment caching. CBaseController
endClip() Ends recording a clip. CBaseController
endContent() Ends the rendering of content. CBaseController
endWidget() Ends the execution of the named widget. CBaseController
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getController() Returns the controller that this widget belongs to. CWidget
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getId() Returns the ID of the widget or generates a new one if requested. CWidget
getOwner() Returns the owner/creator of this widget. CWidget
getViewFile() Looks for the view script file according to the view name. CWidget
getViewPath() Returns the directory containing the view files for this widget. CWidget
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
init() Initializes the list view. CListView
raiseEvent() Raises an event. CComponent
registerClientScript() Registers necessary client scripts. CListView
render() Renders a view. CWidget
renderContent() Renders the main content of the view. CBaseListView
renderEmptyText() Renders the empty message when there is no data. CBaseListView
renderFile() Renders a view file. CBaseController
renderInternal() Renders a view file. CBaseController
renderItems() Renders the data item list. CListView
renderKeys() Renders the key values of the data in a hidden tag. CBaseListView
renderPager() Renders the pager. CBaseListView
renderSorter() Renders the sorter. CListView
renderSummary() Renders the summary text. CBaseListView
run() Renders the view. CBaseListView
setId() Sets the ID of the widget. CWidget
widget() Creates a widget and executes it. CBaseController

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
renderSection() Renders a section. CBaseListView

Property Details

afterAjaxUpdate property
public string $afterAjaxUpdate;

a javascript function that will be invoked after a successful AJAX response is received. The function signature is function(id, data) where 'id' refers to the ID of the list view 'data' the received ajax response data.

ajaxType property (available since v1.1.14)
public string $ajaxType;

the type ('GET' or 'POST') of the AJAX requests. If not set, 'GET' will be used. You can set this to 'POST' if you are filtering by many fields at once and have a problem with GET query string length. Note that in POST mode direct links and enableHistory feature may not work correctly!

ajaxUpdate property
public mixed $ajaxUpdate;

the ID of the container whose content may be updated with an AJAX response. Defaults to null, meaning the container for this list view instance. If it is set false, it means sorting and pagination will be performed in normal page requests instead of AJAX requests. If the sorting and pagination should trigger the update of multiple containers' content in AJAX fashion, these container IDs may be listed here (separated with comma).

ajaxUpdateError property (available since v1.1.13)
public string $ajaxUpdateError;

a javascript function that will be invoked if an AJAX update error occurs.

The function signature is function(xhr, textStatus, errorThrown, errorMessage)

  • xhr is the XMLHttpRequest object.
  • textStatus is a string describing the type of error that occurred. Possible values (besides null) are "timeout", "error", "notmodified" and "parsererror"
  • errorThrown is an optional exception object, if one occurred.
  • errorMessage is the CGridView default error message derived from xhr and errorThrown. Usefull if you just want to display this error differently. CGridView by default displays this error with an javascript.alert()
Note: This handler is not called for JSONP requests, because they do not use an XMLHttpRequest.

Example (add in a call to CGridView):
 ...
 'ajaxUpdateError'=>'function(xhr,ts,et,err,id){ $("#"+id).text(err); }',
 ...

ajaxUrl property (available since v1.1.8)
public mixed $ajaxUrl;

the URL for the AJAX requests should be sent to. CHtml::normalizeUrl() will be called on this property. If not set, the current page URL will be used for AJAX requests.

ajaxVar property
public string $ajaxVar;

the name of the GET variable that indicates the request is an AJAX request triggered by this widget. Defaults to 'ajax'. This is effective only when ajaxUpdate is not false.

baseScriptUrl property
public string $baseScriptUrl;

the base script URL for all list view resources (e.g. javascript, CSS file, images). Defaults to null, meaning using the integrated list view resources (which are published as assets).

beforeAjaxUpdate property
public string $beforeAjaxUpdate;

a javascript function that will be invoked before an AJAX update occurs. The function signature is function(id) where 'id' refers to the ID of the list view.

cssFile property
public string $cssFile;

the URL of the CSS file used by this list view. Defaults to null, meaning using the integrated CSS file. If this is set false, you are responsible to explicitly include the necessary CSS file in your page.

enableHistory property (available since v1.1.11)
public boolean $enableHistory;

whether to leverage the DOM history object. Set this property to true to persist state of list across page revisits. Note, there are two limitations for this feature: - this feature is only compatible with browsers that support HTML5. - expect unexpected functionality (e.g. multiple ajax calls) if there is more than one grid/list on a single page with enableHistory turned on.

itemView property
public string $itemView;

the view used for rendering each data item. This property value will be passed as the first parameter to either CController::renderPartial or CWidget::render to render each data item. In the corresponding view template, the following variables can be used in addition to those declared in viewData:

  • $this: refers to the owner of this list view widget. For example, if the widget is in the view of a controller, then $this refers to the controller.
  • $data: refers to the data item currently being rendered.
  • $index: refers to the zero-based index of the data item currently being rendered.
  • $widget: refers to this list view widget instance.

itemsTagName property (available since v1.1.4)
public string $itemsTagName;

the HTML tag name for the container of all data item display. Defaults to 'div'.

loadingCssClass property (available since v1.1.1)
public string $loadingCssClass;

the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. Defaults to 'list-view-loading'.

separator property (available since v1.1.7)
public string $separator;

the HTML code to be displayed between any two consecutive items.

sortableAttributes property
public array $sortableAttributes;

list of sortable attribute names. In order for an attribute to be sortable, it must also appear as a sortable attribute in the IDataProvider::sort property of dataProvider.

See Also

sorterCssClass property
public string $sorterCssClass;

the CSS class name for the sorter container. Defaults to 'sorter'.

sorterFooter property
public string $sorterFooter;

the text shown after sort links. Defaults to empty.

sorterHeader property
public string $sorterHeader;

the text shown before sort links. Defaults to 'Sort by: '.

template property
public string $template;

the template to be used to control the layout of various components in the list view. These tokens are recognized: {summary}, {sorter}, {items} and {pager}. They will be replaced with the summary text, the sort links, the data item list, and the pager.

updateSelector property (available since v1.1.7)
public string $updateSelector;

the jQuery selector of the HTML elements that may trigger AJAX updates when they are clicked. If not set, the pagination links and the sorting links will trigger AJAX updates.

viewData property
public array $viewData;

additional data to be passed to itemView when rendering each data item. This array will be extracted into local PHP variables that can be accessed in the itemView.

Method Details

init() method
public void init()
Source Code: framework/zii/widgets/CListView.php#207 (show)
public function init()
{
    if(
$this->itemView===null)
        throw new 
CException(Yii::t('zii','The property "itemView" cannot be empty.'));
    
parent::init();

    if(!isset(
$this->htmlOptions['class']))
        
$this->htmlOptions['class']='list-view';

    if(
$this->baseScriptUrl===null)
        
$this->baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets')).'/listview';

    if(
$this->cssFile!==false)
    {
        if(
$this->cssFile===null)
            
$this->cssFile=$this->baseScriptUrl.'/styles.css';
        
Yii::app()->getClientScript()->registerCssFile($this->cssFile);
    }
}

Initializes the list view. This method will initialize required property values and instantiate columns objects.

registerClientScript() method
public void registerClientScript()
Source Code: framework/zii/widgets/CListView.php#230 (show)
public function registerClientScript()
{
    
$id=$this->getId();

    if(
$this->ajaxUpdate===false)
        
$ajaxUpdate=array();
    else
        
$ajaxUpdate=array_unique(preg_split('/\s*,\s*/',$this->ajaxUpdate.','.$id,-1,PREG_SPLIT_NO_EMPTY));
    
$options=array(
        
'ajaxUpdate'=>$ajaxUpdate,
        
'ajaxVar'=>$this->ajaxVar,
        
'pagerClass'=>$this->pagerCssClass,
        
'loadingClass'=>$this->loadingCssClass,
        
'sorterClass'=>$this->sorterCssClass,
        
'enableHistory'=>$this->enableHistory
    
);
    if(
$this->ajaxUrl!==null)
        
$options['url']=CHtml::normalizeUrl($this->ajaxUrl);
    if(
$this->ajaxType!==null)
        
$options['ajaxType']=strtoupper($this->ajaxType);
    if(
$this->updateSelector!==null)
        
$options['updateSelector']=$this->updateSelector;
    foreach(array(
'beforeAjaxUpdate''afterAjaxUpdate''ajaxUpdateError') as $event)
    {
        if(
$this->$event!==null)
        {
            if(
$this->$event instanceof CJavaScriptExpression)
                
$options[$event]=$this->$event;
            else
                
$options[$event]=new CJavaScriptExpression($this->$event);
        }
    }

    
$options=CJavaScript::encode($options);
    
$cs=Yii::app()->getClientScript();
    
$cs->registerCoreScript('jquery');
    
$cs->registerCoreScript('bbq');
    if(
$this->enableHistory)
        
$cs->registerCoreScript('history');
    
$cs->registerScriptFile($this->baseScriptUrl.'/jquery.yiilistview.js',CClientScript::POS_END);
    
$cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiListView($options);");
}

Registers necessary client scripts.

renderItems() method
public void renderItems()
Source Code: framework/zii/widgets/CListView.php#276 (show)
public function renderItems()
{
    echo 
CHtml::openTag($this->itemsTagName,array('class'=>$this->itemsCssClass))."\n";
    
$data=$this->dataProvider->getData();
    if((
$n=count($data))>0)
    {
        
$owner=$this->getOwner();
        
$viewFile=$owner->getViewFile($this->itemView);
        
$j=0;
        foreach(
$data as $i=>$item)
        {
            
$data=$this->viewData;
            
$data['index']=$i;
            
$data['data']=$item;
            
$data['widget']=$this;
            
$owner->renderFile($viewFile,$data);
            if(
$j++ < $n-1)
                echo 
$this->separator;
        }
    }
    else
        
$this->renderEmptyText();
    echo 
CHtml::closeTag($this->itemsTagName);
}

Renders the data item list.

renderSorter() method
public void renderSorter()
Source Code: framework/zii/widgets/CListView.php#304 (show)
public function renderSorter()
{
    if(
$this->dataProvider->getItemCount()<=|| !$this->enableSorting || empty($this->sortableAttributes))
        return;
    echo 
CHtml::openTag('div',array('class'=>$this->sorterCssClass))."\n";
    echo 
$this->sorterHeader===null Yii::t('zii','Sort by: ') : $this->sorterHeader;
    echo 
"<ul>\n";
    
$sort=$this->dataProvider->getSort();
    foreach(
$this->sortableAttributes as $name=>$label)
    {
        echo 
"<li>";
        if(
is_integer($name))
            echo 
$sort->link($label);
        else
            echo 
$sort->link($name,$label);
        echo 
"</li>\n";
    }
    echo 
"</ul>";
    echo 
$this->sorterFooter;
    echo 
CHtml::closeTag('div');
}

Renders the sorter.