Berjumpa lagi dengan artikel Yii, kali ini kita bahas Gii, Yii Code Generator.
Yii Code Generator Gii merupakan fasilitas yang disediakan oleh Yii untuk membuat operasi CRUD (Create Update Delete). Jika aplikasi yang digunakan hanya bersifat CRUD sederhana, maka penggunaan Yii Gii ini dapat mempercepat pembuatan software.
Ikuti saja ya, ntar lihat keajaiban yang belum pernah terjadi di framework lain
Gii, Yii Code Generator
Langkah-langkah :
Kita konfigurasi dulu main.php yang ada di dalam folder protected/config/main.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
<?php return array( 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=>'Capella CMS Indonesia', 'preload'=>array( ), 'import'=>array( 'application.models.*', 'application.components.*', 'ext.fpdf.*' ), 'modules'=>array( 'gii'=>array( 'class'=>'system.gii.GiiModule', 'password'=>'123456', 'ipFilters'=>array('127.0.0.1','::1'), ), ), 'components'=>array( 'user'=>array( 'allowAutoLogin'=>true, ), 'widgetFactory' => array( 'widgets' => array( 'CLinkPager' => array( 'header' => '<div class="pagination pagination-centered">', 'footer' => '</div>', 'nextPageLabel' => 'Next', 'prevPageLabel' => 'Prev', 'cssFile'=>false, 'selectedPageCssClass' => 'active', 'hiddenPageCssClass' => 'disabled', 'htmlOptions' => array( 'class' => 'pagination', ) ), 'CGridView' => array( 'htmlOptions' => array( 'class' => 'table-responsive' ), 'pagerCssClass' => 'dataTables_paginate paging_bootstrap', 'itemsCssClass' => 'table table-striped table-hover', 'cssFile' => false, 'summaryCssClass' => 'dataTables_info', 'summaryText' => 'Showing {start} to {end} of {count} entries', 'template' => '{pager}{items}{summary}{pager}', ), ) ), 'urlManager'=>array( 'urlFormat'=>'path', 'showScriptName'=>false, 'caseSensitive'=>false, 'rules'=>array( ''=>'site/index', '<module:[\w-]+>/<controller:[\w-]+>/<action:[\w-]+>/<name:[\w-]+>'=>'<module>/<controller>/<action>' ) ), 'db'=>array( 'connectionString' => 'mysql:host=localhost;port=5000;dbname=capellacms', 'emulatePrepare' => true, 'username' => 'capellacms', 'password' => 'capellacms', 'charset' => 'utf8', 'initSQLs'=>array('set names utf8'), 'schemaCachingDuration' => 3600, ), 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), ), ), /*'errorHandler'=>array( 'errorAction' => 'site/error' ),*/ ), 'params'=>array( 'allowedext'=>array("xls","csv","xlsx","vsd","pdf","gdb","doc","docx","jpg","gif","png","rar","zip","jpeg"), ), ); |
cari bagian modules gii
1 2 3 4 5 6 7 |
'modules'=>array( 'gii'=>array( 'class'=>'system.gii.GiiModule', 'password'=>'123456', 'ipFilters'=>array('127.0.0.1','::1'), ), ), |
Ok, setelah kita setting, maka kita test di browser : http://localhost/test/index.php?r=gii
masukkan password : 123456, klik Enter
Sesuai konsep MVC (Model View Controller), maka kita ikuti langkah-langkah dulu
Model
Sebelum membuat model, kita buat dulu yuk tabelnya
1 2 3 4 5 6 7 8 9 |
CREATE TABLE `identitytype` ( `identitytypeid` INT(11) NOT NULL AUTO_INCREMENT, `identitytypename` VARCHAR(50) NOT NULL, `recordstatus` TINYINT(4) NOT NULL, PRIMARY KEY (`identitytypeid`), UNIQUE INDEX `uq_identitytypename` (`identitytypename`) ) COLLATE='utf8_general_ci' ENGINE=InnoDB; |
kemudian kita pilih menu Model Generator di Gii
masukkan nama tabel, kemudian klik preview
Klik Generate
nah jika ada error seperti itu, maka set hak akses, biasanya terjadi di linux atau macos
nah, jika dibuka file identitytype.php di protected/models
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
<?php /** * This is the model class for table "identitytype". * * The followings are the available columns in table 'identitytype': * @property integer $identitytypeid * @property string $identitytypename * @property integer $recordstatus */ class Identitytype extends CActiveRecord { /** * Returns the static model of the specified AR class. * @return Identitytype the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'identitytype'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('identitytypename, recordstatus', 'required'), array('recordstatus', 'numerical', 'integerOnly'=>true), array('identitytypename', 'length', 'max'=>50), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('identitytypeid, identitytypename, recordstatus', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'identitytypeid' => Catalogsys::model()->getCatalog('identitytypeID'), 'identitytypename' => Catalogsys::model()->getCatalog('IdentityType'), 'recordstatus' => Catalogsys::model()->getCatalog('RecordStatus'), ); } private function comparedb($criteria) { if (isset($_GET['identitytypename'])) { $criteria->compare('identitytypename',$_GET['identitytypename'],true); } } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $this->comparedb($criteria); $criteria->compare('identitytypeid',$this->identitytypeid); $criteria->compare('identitytypename',$this->identitytypename,true); return new CActiveDataProvider(get_class($this), array( 'pagination'=>array( 'pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']), ), 'criteria'=>$criteria, )); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function searchwstatus() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $this->comparedb($criteria); $criteria->condition='recordstatus=1'; $criteria->compare('identitytypeid',$this->identitytypeid); $criteria->compare('identitytypename',$this->identitytypename,true); return new CActiveDataProvider(get_class($this), array( 'pagination'=>array( 'pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']), ), 'criteria'=>$criteria, )); } } |
View dan Controller
Klik Crud Generator
Masukkan nama model yang tadi dibuat
Klik Preview
Klik Generate
File IdentitytypeController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
<?php class IdentitytypeController extends Controller { protected $menuname = 'identitytype'; public function actionCreate() { parent::actionCreate(); $this->GetSMessage('insertsuccess'); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate() { parent::actionUpdate(); $id=$_POST['id']; $model=$this->loadModel($id[0]); if ($model != null) { if ($this->CheckDataLock($this->menuname, $id[0]) == false) { $this->InsertLock($this->menuname, $id[0]); echo CJSON::encode(array( 'status'=>'success', 'identitytypeid'=>$model->identitytypeid, 'identitytypename'=>$model->identitytypename, 'recordstatus'=>$model->recordstatus, )); Yii::app()->end(); } } } public function actionCancelWrite() { $this->DeleteLockCloseForm($this->menuname, $_POST['Identitytype'], $_POST['Identitytype']['identitytypeid']); } public function actionWrite() { parent::actionWrite(); if(isset($_POST['Identitytype'])) { $messages = $this->ValidateData( array(array($_POST['Identitytype']['identitytypename'],'emptyidentitytypename','emptystring'), ) ); if ($messages == '') { $connection=Yii::app()->db; $transaction=$connection->beginTransaction(); try { if ((int)$_POST['Identitytype']['identitytypeid'] > 0) { $sql = 'call UpdateIdentityType(:vid,:videntitytypename, :vrecordstatus,:vcreatedby)'; $command=$connection->createCommand($sql); $command->bindvalue(':vid',$_POST['Identitytype']['identitytypeid'],PDO::PARAM_STR); } else { $sql = 'call InsertIdentityType(:videntitytypename, :vrecordstatus,:vcreatedby)'; $command=$connection->createCommand($sql); } $command->bindvalue(':videntitytypename',$_POST['Identitytype']['identitytypename'],PDO::PARAM_STR); $command->bindvalue(':vrecordstatus',$_POST['Identitytype']['recordstatus'],PDO::PARAM_STR); $command->bindvalue(':vcreatedby', Yii::app()->user->name,PDO::PARAM_STR); $command->execute(); $transaction->commit(); $this->DeleteLock($this->menuname, $_POST['Identitytype']['identitytypeid']); $this->GetSMessage('insertsuccess'); } catch (Exception $e) { $transaction->rollBack(); $this->GetMessage($e->getMessage()); } } } } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete() { parent::actionDelete(); $id=$_POST['id']; $connection=Yii::app()->db; $transaction=$connection->beginTransaction(); try { $sql = 'call DeleteIdentityType(:vid,:vcreatedby)'; $command=$connection->createCommand($sql); foreach($id as $ids) { $command->bindvalue(':vid',$ids,PDO::PARAM_STR); $command->bindvalue(':vcreatedby',Yii::app()->user->name,PDO::PARAM_STR); $command->execute(); } $transaction->commit(); $this->GetSMessage('insertsuccess'); } catch (Exception $e) { $transaction->rollback(); $this->GetMessage($e->getMessage()); } } /** * Lists all models. */ public function actionIndex() { parent::actionIndex(); $model=new Identitytype('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Identitytype'])) $model->attributes=$_GET['Identitytype']; if (isset($_GET['pageSize'])) { Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']); unset($_GET['pageSize']); // would interfere with pager and repetitive page size change } $this->render('index',array( 'model'=>$model, )); } public function actionUpload() { parent::actionUpload(); $folder=$_SERVER['DOCUMENT_ROOT'].Yii::app()->request->baseUrl.'/upload/';// folder for uploaded files $allowedExtensions = array("csv"); $sizeLimit = (int)Yii::app()->params['sizeLimit'];// maximum file size in bytes $uploader = new qqFileUploader($allowedExtensions, $sizeLimit); $result = $uploader->handleUpload($folder,true); $row = 0; if (($handle = fopen($folder.$uploader->file->getName(), "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if ($row>0) { $model=Absstatus::model()->findByPk((int)$data[0]); if ($model=== null) { $model = new Absstatus(); } $model->absstatusid = (int)$data[0]; $model->shortstat = $data[1]; $model->longstat = $data[2]; $model->isin = (int)$data[3]; $model->priority = (int)$data[4]; $model->recordstatus = (int)$data[5]; try { if(!$model->save()) { $errormessage=$model->getErrors(); if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array( 'status'=>'failure', 'div'=>$errormessage )); } } } catch (Exception $e) { $errormessage=$e->getMessage(); if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array( 'status'=>'failure', 'div'=>$errormessage )); } } } $row++; } fclose($handle); } $result=htmlspecialchars(json_encode($result), ENT_NOQUOTES); echo $result; } public function actionDownload() { parent::actionDownload(); $sql = "select identitytypename from identitytype a "; if ($_GET['id'] !== '') { $sql = $sql . "where a.identitytypeid in (".$_GET['id'].")"; } $command=$this->connection->createCommand($sql); $dataReader=$command->queryAll(); $this->pdf->title='Identity Type List'; $this->pdf->AddPage('P'); $this->pdf->colalign = array('C'); $this->pdf->setwidths(array(90)); $this->pdf->colheader = array('Identity Type'); $this->pdf->rowheader(); $this->pdf->coldetailalign = array('L'); foreach($dataReader as $row1) { $this->pdf->row(array($row1['identitytypename'])); } // me-render ke browser $this->pdf->Output(); } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model=Identitytype::model()->findByPk((int)$id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param CModel the model to be validated */ protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='identitytype-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } } |
File view\identitytype\index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
<?php $pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']); ?> <script type="text/javascript"> // here is the magic function adddata() { <?php echo CHtml::ajax(array( 'url'=>array('identitytype/create'), 'data'=> "js:$(this).serialize()", 'type'=>'post', 'dataType'=>'json', 'success'=>"function(data) { if (data.status == 'success') { $('#Identitytype_identitytypeid').val(''); $('#Identitytype_identitytypename').val(''); // Here is the trick: on submit-> once again this function! $('#createdialog').dialog('open'); } else { toastr.error(data.div); } } ", ))?>; return false; } </script> <script type="text/javascript"> function editdata() { <?php echo CHtml::ajax(array( 'url'=>array('identitytype/update'), 'data'=> array('id'=>'js:$.fn.yiiGridView.getSelection("datagrid")'), 'type'=>'post', 'dataType'=>'json', 'success'=>"function(data) { if (data.status == 'success') { $('#Identitytype_identitytypeid').val(data.identitytypeid); $('#Identitytype_identitytypename').val(data.identitytypename); if (data.recordstatus == '1') { document.forms[1].elements[6].checked=true; } else { document.forms[1].elements[6].checked=false; } // Here is the trick: on submit-> once again this function! $('#createdialog').dialog('open'); } else { toastr.error(data.div); } } ", ))?>; return false; } </script> <script type="text/javascript"> function deletedata() { <?php echo CHtml::ajax(array( 'url'=>array('identitytype/delete'), 'data'=> array('id'=>'js:$.fn.yiiGridView.getSelection("datagrid")'), 'type'=>'post', 'dataType'=>'json', 'success'=>"function(data) { if (data.status == 'success') { $.fn.yiiGridView.update('datagrid'); } else { toastr.error(data.div);; } } ", ))?>; $.fn.yiiGridView.update('datagrid'); return false; } </script> <script type="text/javascript"> function refreshdata() { $.fn.yiiGridView.update('datagrid'); return false; } </script> <script type="text/javascript"> function helpdata() { $('#helpdialog').dialog('open'); return false; } </script> <script type="text/javascript"> function helpmodifdata() { $('#helpmodifdialog').dialog('open'); return false; } </script> <script type="text/javascript"> function searchdata() { $('#searchdialog').dialog('open'); return false; } </script> <script type="text/javascript"> function downloaddata() { window.open('download?id='+$.fn.yiiGridView.getSelection("datagrid")); } </script> <?php $this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog 'id'=>'createdialog', 'options'=>array( 'title'=>'Form Dialog', 'autoOpen'=>false, 'modal'=>true, 'width'=>'auto', 'height'=>'auto', ), ));?> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?> <?php $this->endWidget();?> <?php $this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog 'id'=>'searchdialog', 'options'=>array( 'title'=>'Search Dialog', 'autoOpen'=>false, 'modal'=>true, 'width'=>'auto', 'height'=>'auto', ), ));?> <?php echo $this->renderPartial('_search'); ?> <?php $this->endWidget();?> <?php $this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog 'id'=>'helpdialog', 'options'=>array( 'title'=>'Help', 'autoOpen'=>false, 'modal'=>true, 'width'=>'auto', 'height'=>'auto', ), ));?> <?php echo $this->renderPartial('_help'); ?> <?php $this->endWidget();?> <?php $this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog 'id'=>'helpmodifdialog', 'options'=>array( 'title'=>'Help', 'autoOpen'=>false, 'modal'=>true, 'width'=>'auto', 'height'=>'auto', ), ));?> <?php echo $this->renderPartial('_helpmodif'); ?> <?php $this->endWidget();?> <?php $this->widget( 'booster.widgets.TbPanel', array( 'title' => Catalogsys::model()->getCatalog('IdentityType'), 'headerIcon' => 'home', 'content' => $this->renderpartial('_viewindex',array('model'=>$model,'pageSize'=>$pageSize),true) ) ); ?> |
Recent Comments