I'm trying to wrap up jqGrid into a widget and I'm stuck on where it's best to define the columns.
The options are to put it in the view like so:
View code: <div class="yiiForm"> <?php $this->beginWidget("application.widgets.jqGrid.jqGrid", array( "gridId"=>"browser", "pagerId"=>"pager", "dataUrl" => $this->createUrl("artistData"), "sortColumn" => "artistName", "rows" => 40, "columns" => array( array("id" => "artistName", "name" => "Artist Name"), array("id" => "artistType", "name" => "Artist Type"), array("id" => "artistKey", "name" => "Artist Key"), ) )); ?> <table id="browser"></table> <div id="pager" class="scroll" style="text-align:center;"></div> <?php $this->endWidget(); ?> </div><!-- yiiForm -->
or to shove the column definition into the action on the controller:
Controller code: <?php class BrowserController extends CController { public function actionArtist() { $this->render("artist"); } public function artistColumns() { return array( array("id" => "artistName", "name" => "Artist Name"), array("id" => "artistType", "name" => "Artist Type"), array("id" => "artistKey", "name" => "Artist Key"), ); } public function actionArtistData() { Yii::import("application.widgets.jqGrid.jqGrid"); $criteria = new CDbCriteria; $count = ArtistRecord::model()->count($criteria); jqGrid::applyCriteria($criteria); $artists = ArtistRecord::model()->findAll($criteria); $this->renderDynamicInternal( array("jqGrid", "renderData"), array($artists, $count, $this->artistColumns()) ); } ?> View code: <div class="yiiForm"> <?php $this->beginWidget("application.widgets.jqGrid.jqGrid", array( "gridId"=>"browser", "pagerId"=>"pager", "dataUrl" => $this->createUrl("artistData"), "sortColumn" => "artistName", "rows" => 40, "columns" => $this->artistColumns() )); ?> <table id="browser"></table> <div id="pager" class="scroll" style="text-align:center;"></div> <?php $this->endWidget(); ?> </div><!-- yiiForm -->
The advantage of the latter is that if we have a model with more columns than we want to display, we can pass the column definition to the script which builds the json data, allowing that script to reduce the data which is returned to the jqGrid control on each sort, page, etc. It just doesn't feel quite right to have that definition in the controller rather than the view because defining which columns are to be displayed is essentially the domain of the view.
Also, is that way too much information to be passing to the beginWidget call?
Once I'm done, I'll wrap the thing up and put it up here for people to download and use.