Yii Sortable Model Class Reference. Yii Framework

SortableCGridView

Package Yii Sortable Model
Inheritance class SortableCGridView » CGridView » CBaseListView » CWidget » CBaseController » CComponent
Since 1.0
Source Code extensions//widgets/SortableCGridView.php
CGridView widget extended to allow drag and drop sorting of records. With it, users will be able to drag and drop with the mouse the rows of the grid to change records order. New order will be automatically saved in the database through an Ajax call.

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. CGridView
ajaxUpdate mixed the ID of the container whose content may be updated with an AJAX response. CGridView
ajaxUpdateError string a javascript function that will be invoked if an AJAX update error occurs. CGridView
ajaxUrl mixed the URL for the AJAX requests should be sent to. CGridView
ajaxVar string the name of the GET variable that indicates the request is an AJAX request triggered by this widget. CGridView
allItemsInOnePage boolean whether to show all items in one page, disabling completely pagination. SortableCGridView
baseScriptUrl string the base script URL for all grid view resources (e. CGridView
beforeAjaxUpdate string a javascript function that will be invoked before an AJAX update occurs. CGridView
blankDisplay string the text to be displayed in an empty grid cell. CGridView
columns array grid column configuration. CGridView
controller CController Returns the controller that this widget belongs to. CWidget
cssFile string the URL of the CSS file used by this grid view. CGridView
dataProvider CActiveDataProvider the data provider for the view. SortableCGridView
descSort boolean whether to show records in a descendant order. SortableCGridView
emptyText string the message to be displayed when dataProvider does not have any data. CBaseListView
enableDragDropSorting boolean whether to enable the drag and drop sorting, which is the essence of this widget. SortableCGridView
enablePagination boolean whether to enable pagination. CBaseListView
enableSorting boolean whether to enable sorting. CBaseListView
errorMessage string a message to show when there is an error in drag and drop sorting. SortableCGridView
filter CModel the model instance that keeps the user-entered filter data. CGridView
filterCssClass string the CSS class name for the table row element containing all filter input fields. CGridView
filterPosition string whether the filters should be displayed in the grid view. CGridView
formatter CFormatter the formatter instance. CGridView
hasFooter boolean whether the table should render a footer. CGridView
hideHeader boolean whether to hide the header cells of the grid. CGridView
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
idField string the field name in the database table which stores the id for the record. SortableCGridView
itemsCssClass string the CSS class name for the container of all data item display. CBaseListView
jqueryUiSortableOptions array options passed to initialize Jquery Ui Sortable. SortableCGridView
loadingCssClass string the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. CGridView
nullDisplay string the text to be displayed in a data cell when a data value is null. CGridView
orderField string the field name in the database table which stores the order for the record. SortableCGridView
orderUrl string the action name that will be used to trigger drag and drop sorting (through the AjaxSortingAction located in the "actions" directory in this extension). SortableCGridView
owner CBaseController Returns the owner/creator of this widget. CWidget
pager array the configuration for the pager. CBaseListView
pagerCssClass string the CSS class name for the pager container. CBaseListView
rowCssClass array the CSS class names for the table body rows. CGridView
rowCssClassExpression string a PHP expression that is evaluated for every table body row and whose result is used as the CSS class name for the row. CGridView
selectableRows integer the number of table body rows that can be selected. CGridView
selectionChanged string a javascript function that will be invoked after the row selection is changed. CGridView
showTableOnEmpty boolean whether to display the table even when there is no data. CGridView
skin mixed the name of the skin to be used by this widget. CWidget
successMessage string a message to show when drag and drop sorting is completed successfully. SortableCGridView
summaryCssClass string the CSS class name for the summary text container. 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 sections in the view. CBaseListView
updateAfterSorting boolean whether to update grid content after sorting. SortableCGridView
updateSelector string the jQuery selector of the HTML elements that may trigger AJAX updates when they are clicked. CGridView
viewPath string Returns the directory containing the view files for this widget. CWidget

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
sortScript string Returns the javascript code responsable of handling the drag and drop sorting through an Ajax request SortableCGridView

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
getFormatter() Returns the formatter instance. Defaults to the 'format' application component. CGridView
getHasFooter() Returns whether the table should render a footer. This is true if any of the columns has a true CGridColumn::hasFooter value. CGridView
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 grid view. SortableCGridView
raiseEvent() Raises an event. CComponent
registerClientScript() Registers necessary client scripts. SortableCGridView
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
renderFilter() Renders the filter. CGridView
renderInternal() Renders a view file. CBaseController
renderItems() Renders the data items for the grid view. CGridView
renderKeys() Renders the key values of the data in a hidden tag. CBaseListView
renderPager() Renders the pager. CBaseListView
renderSummary() Renders the summary text. CBaseListView
renderTableBody() Renders the table body. CGridView
renderTableFooter() Renders the table footer. CGridView
renderTableHeader() Renders the table header. CGridView
renderTableRow() Renders a table body row. SortableCGridView
run() Renders the view. CBaseListView
setFormatter() Sets the formatter instance CGridView
setId() Sets the ID of the widget. CWidget
widget() Creates a widget and executes it. CBaseController

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
createDataColumn() Creates a CDataColumn based on a shortcut column specification string. CGridView
getSortScript() Returns the javascript code responsable of handling the drag and drop sorting through an Ajax request SortableCGridView
initColumns() Creates column objects and initializes them. CGridView
renderSection() Renders a section. CBaseListView

Property Details

allItemsInOnePage property
public boolean $allItemsInOnePage;

whether to show all items in one page, disabling completely pagination. Defaults to true

dataProvider property
public CActiveDataProvider $dataProvider;

the data provider for the view.

descSort property
public boolean $descSort;

whether to show records in a descendant order. Defaults to false

enableDragDropSorting property
public boolean $enableDragDropSorting;

whether to enable the drag and drop sorting, which is the essence of this widget. If it's set to true sorting by clicking in columns names is disabled (so $enableSorting property has no effect) and items are showed ordered by the field defined in $orderField. If it's set to false, the widget defaults to a normal CGridView and the rest of this extension widget properties are ignored. Defaults to true

errorMessage property
public string $errorMessage;

a message to show when there is an error in drag and drop sorting. Defaults to 'An error has occured while sorting'

idField property
public string $idField;

the field name in the database table which stores the id for the record. Defaults to 'id'

jqueryUiSortableOptions property
public array $jqueryUiSortableOptions;

options passed to initialize Jquery Ui Sortable. Look at http://jqueryui.com/demos/sortable/ for the available options. Keys must be options name and values options values

orderField property
public string $orderField;

the field name in the database table which stores the order for the record. This should be a positive integer field. Defaults to 'order'

orderUrl property
public string $orderUrl;

the action name that will be used to trigger drag and drop sorting (through the AjaxSortingAction located in the "actions" directory in this extension). Defaults to 'order'. This must be defined in the "actions" method of the controller in which this widget is called. For example: "public function actions() {return array('order' => array('class' => 'ext.yiisortablemodel.actions.AjaxSortingAction'))}. If needed, its acces rules have to be defined, too"

sortScript property read-only
protected string getSortScript()

Returns the javascript code responsable of handling the drag and drop sorting through an Ajax request

successMessage property
public string $successMessage;

a message to show when drag and drop sorting is completed successfully. If it's an empty string, no message is showed. Defaults to empty string

updateAfterSorting property
public boolean $updateAfterSorting;

whether to update grid content after sorting. Useful to update rows classes which depends on row positions, as during sorting they have been changed. Defaults to true

Method Details

getSortScript() method
protected string getSortScript()
{return} string drag and drop sorting javascript code
Source Code: extensions//widgets/SortableCGridView.php#L132 (show)
   protected function getSortScript()
   {
  return 
'
     var grid_id = '
.Cjavascript::encode($this->getId()).';
     var grid_selector = '
.Cjavascript::encode('#'.$this->getId()).';
     var tbody_selector = '
.Cjavascript::encode('#'.$this->getId().' tbody').';
     /*apply sortable*/
     $(tbody_selector).sortable('
.CJavascript::encode($this->jqueryUiSortableOptions).');
     /*helper to keep each table cell width while dragging*/
     $(tbody_selector).sortable("option", "helper", function(e, ui) {
        ui.children().each(function() {
           $(this).width($(this).width());
        });
        return ui;
     });
     /*add dragged row index before moving as an attribute. Used to know if item is moved forward or backward*/
     $(tbody_selector).bind("sortstart", function(event, ui) {
        ui.item.attr("data-prev-index", ui.item.index());
     });
     /*trigger ajax sorting when grid is updated*/
     $(tbody_selector).bind("sortupdate", function(event, ui) {
        $(grid_selector).addClass('
.CJavascript::encode($this->loadingCssClass).');
        var data = {};
        data["dragged_item_id"] = parseInt(ui.item.attr("data-id"));
        var prev_index = parseInt(ui.item.attr("data-prev-index"));
        var new_index = parseInt(ui.item.index());
        /*which item place take dragged item*/
        if (prev_index < new_index) {
           data["replacement_item_id"] = ui.item.prev().attr("data-id");
        } else {
           data["replacement_item_id"] = ui.item.next().attr("data-id");
        }
        data["model"] = '
.Cjavascript::encode($this->dataProvider->modelClass).';
        data["order_field"] = '
.Cjavascript::encode($this->orderField).';
        ui.item.removeAttr("data-prev-index");
        '
.CHtml::ajax(array(
           
'type' => 'POST',
           
'url' => Yii::App()->controller->createAbsoluteUrl($this->orderUrl),
           
'data' => 'js:data',
           
'success' => 'js:function() {
              $(grid_selector).removeClass('
.CJavascript::encode($this->loadingCssClass).');
              /*update the whole grid again to update row class values*/
              if ("'
.(string)$this->updateAfterSorting.'") {
                 $.fn.yiiGridView.update(grid_id);
              }
              if ("'
.(string)$this->successMessage.'") {
                 alert('
.CJavascript::encode($this->successMessage).');
              }
            }
           '
,
           
'error' => 'js:function() {
              $(grid_selector).removeClass('
.CJavascript::encode($this->loadingCssClass).');
              alert('
.CJavascript::encode($this->errorMessage).');
              $.fn.yiiGridView.update(grid_id);
           }
           '
        
)).'
     });
  '
;
   }

Returns the javascript code responsable of handling the drag and drop sorting through an Ajax request

init() method
public void init()
Source Code: extensions//widgets/SortableCGridView.php#L81 (show)
   public function init()
   {
  if (
$this->enableDragDropSorting === true) {
     
/*To use this widget, data provider must be an instance of CActiveDataProvider*/
     
if (!($this->dataProvider instanceof CActiveDataProvider)) {
        throw new 
CException(Yii::t('zii''Data provider must be an instance of CActiveDataProvider'));
     }
     if (
$this->allItemsInOnePage === true) {
        
$this->dataProvider->pagination false;
     }
     
$this->enableSorting false;
     if (
$this->descSort !== true) {
        
$sort_direction 'ASC';
     } else {
        
$sort_direction 'DESC';
     }
     
$this->dataProvider->setSort(array('defaultOrder' => '`'.$this->orderField.'`'.$sort_direction));
  }

  
parent::init();
   }

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

registerClientScript() method
public void registerClientScript()
Source Code: extensions//widgets/SortableCGridView.php#L196 (show)
   public function registerClientScript()
   {
  
//Call parent
  
parent::registerClientScript();
  if (
$this->enableDragDropSorting === true) {
     
$cs=Yii::app()->getClientScript();
     
//Register jquery-ui
     
$cs->registerCoreScript('jquery.ui');
     
//Register sort script
     
$cs->registerScript(__CLASS__.'-'.$this->id
        
/*Call sort script when document is ready and each time grid is updated*/
        
$this->getSortScript().'
        $("body").ajaxSuccess(function(e, xhr, settings) {
           if (settings.url === $.fn.yiiGridView.getUrl('
.Cjavascript::encode($this->getId()).')) {
              '
.$this->getSortScript().'
           }
        });
  '
);
  }
   }

Registers necessary client scripts.

renderTableRow() method
public void renderTableRow(integer $row)
$row integer the row number (zero-based).
Source Code: extensions//widgets/SortableCGridView.php#L107 (show)
   public function renderTableRow($row)
   {
  
$data=$this->dataProvider->data[$row];
  echo 
'<tr';
  if(
$this->rowCssClassExpression !== null) {
     echo 
' class="'.$this->evaluateExpression($this->rowCssClassExpression,array('row'=>$row,'data'=>$data)).'"';
  } else if(
is_array($this->rowCssClass) && ($n=count($this->rowCssClass))>0) {
     echo 
' class="'.$this->rowCssClass[$row%$n].'"';
  }
  
/*Render the record id as its 'data-id' atribute. This information will be used to sort*/
  
if ($this->enableDragDropSorting === true) {
     echo 
' data-id="'.CHtml::value($data$this->idField).'"';
  }
  echo 
'>';
  foreach(
$this->columns as $column) {
     
$column->renderDataCell($row);
  }
  echo 
"</tr>\n";
   }

Renders a table body row.

Copyright © 2008-2011 by Yii Software LLC
All Rights Reserved.