[YII] Join + CGridView + Pagination


Deskripsi
      if we have 2 table or more you can joined easily, but in Yii we must create relationship before using it.      
Howto
1. Setup Relation
    i have 2 Table with spec :
       - table 1 name : Yiitest
          field :   1. id [PK]
                     2. name
                     3. Description
   
          -----Join table using field name ------

        - table 2 name : Yiitest2
          field :   1. name [PK]
                     2. position

* Case : i need join table Yiitest to Yiitest2, and Yiitest.name based on Yiitest2.name[PK]
    How we do that ?? just create relationship
 
    Go to your model Yiitest and add this code line
    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(
'Yiitest2'=> array(self::BELONGS_TO,'Yiitest2','name'),
);
    }
 
    * Relation have been create, now we can query using CActiveDataProvider


2. Query Join with CActiveDataProvider
    Controller : 
    $dataProvider = new CActiveDataProvider('Yiitest',array(
                                                    'criteria'=>array('join'=>'right join yiitest2 x on x.name = 
                                                                                         t.name',
                                                                             'order' => 'id'),
                                                    'pagination'=>array('pageSize'=>2),));
   // send object to view
    $this->render('your_view', array('dataProvider' => $dataProvider));
   
    *look at red mark, because we use join that model using alias 't' (by default Yii).


3. Display Using CGridView with Join Field and Pagination 
   View : 
   <?php
   $this->widget('zii.widgets.grid.CGridView', array(
                                  'dataProvider'=>$dataProvider,
                                  'columns'=>array('name','description','Yiitest2.position'),
                                  'pager'=>array(
                                                          'class'=>'CLinkPager',
                                                          'header'=>'',
                                                          'prevPageLabel'=>'<',
                                                          'nextPageLabel'=>'>',
                                                          'firstPageLabel'=>'First',
                                                          'lastPageLabel'=>'Last',
                                                          ),
                                 'enablePagination' => true,));
   ?>
 
   * look at cyan mark , Why Yiitest2 ? not Yiitest ? because field position in model Yiitest2 haha ,
      simple right ?
   * if you don't want pagination just change the value to false

[YII] Pagination


Deskripsi
     This pagination Using CActiveDataProvider , zii.widgets.grid.CGridView and ClinkPager.

Howto
Controller : 
// create ActiveDataRecord Object, with option pagination
$dataProvider = new CActiveDataProvider('MODEL',array('criteria'=>array('order' => 'id'),  
                                                                                   'pagination'=>array('pageSize'=>2)
                                                                   ));
// Passing that object to view, we don't need using method getData()
$this->render('your_view', array('dataProvider' => $dataProvider,));

View :
//use widget CGridView and class CLinkPager
$this->widget('zii.widgets.grid.CGridView', array(
                                                                  'dataProvider'=>$dataProvider,
                                                                 'pager'=>array(
                                                                     'class'=>'CLinkPager',
                                                                     'header'=>'',
                                                                      'prevPageLabel'=>'<',
                                                                     'nextPageLabel'=>'>',
                                                                      'firstPageLabel'=>'First',
                                                                     'lastPageLabel'=>'Last',),
                                                                  'enablePagination' => true,
));

*look at the mark , that's the basic pagination with widget CGridView and CLinkPager.

[YII] Add CSS and JS File


Deskripsi
     Berikut adalah cara mengembed file external dari css dan js.

Howto
     1. You must have .css and js file.
   
     2. - your css file path : webroot/Yiiapp/css/[create or copy here]
         - your script file path : webroot/Yiiapp/js/[create or copy here] , if doesn't exist create
            first
   
     3. Add this script to your view
        <?php
        Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl . '/css/style.css');
        Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/test.js');
        ?>
        * no need to echo in view

     4. now your script and css will connect to view

[YII] Pretty Url


Deskripsi
     Secara pengaksesan standart YII punya format url yang mengerikan / horrible, so jadi bagaimana agar kita membuat URL yang cukup cantik dan simple pada YII. simple just follow my step

Howto
1. First access URL in YII like this :
    localhost/myYii/index.php?r=controller/action

2. i want to change like this :
    localhost/myYii/index.php/controller/action

3. Open config.php at path : webroot/YourYiiApp/protected/config/config.php
4. Find and Uncomment this string code :

              // uncomment the following to enable URLs in path-format
             'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
 ),

5. Now your url like this
    localhost/myYii/index.php/controller/action

6. it's still bad i want to remove index.php, haha ok to remove index.php we need .htaccess

7. create .htaccess at this path : webroot/myYii/[your htaccess here]

8. copy paste code below to your htaccess
 
    Options +FollowSymLinks
    IndexIgnore */*
    <IfModule mod_rewrite.c>
    RewriteEngine on

    # if a directory or a file exists, use it directly

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # otherwise forward it to index.php

   RewriteRule . index.php
   </IfModule>
 
9. now your URL like this :
     localhost/myYii/controller/action

10. How about the parameter ? , i want to passing the value from url to my action in controller , simply follow this :
      localhost/myYii/controller/action?myvar1=1&myvar2=2

11 In method  you can do this
   
     in your action on controller

     public function actionXXZZ($myvar1,$myvar2)
     {
           echo $myvar1;
     }

*beware !! the name of variable in URL must same in action parameter it's very different with Cakephp.

ok all done , hope's this help

[YII] Basic Form


Deskripsi
     Form digunakan sebagai interaksi antara user dan system, interaksi berupa inputan yang digunakan untuk berbagai macam keperluan, seperti register , login , penyimpanan data , etc.

Howto

in CONTROLLER on action Formulir :

     public function actionFormulir()
{
1 $model = new Yiitest;
2
3 if(isset($_POST['Yiitest']))
4 {
5 $model->name = $_POST['Yiitest']['name'];
6 $model->description = $_POST['Yiitest']['description'];
7 if ($model->save())
8 {
9 echo 'Berhasil disimpan';
10 }
11 else
12 {
13 echo 'Save Failure'.'<br>';
14 $error = $DbAr->getErrors();
15 echo $error['name']['0'];
16 }
17 }
18 else
19 {
20 $this->render('formulir',array('model'=>$model));
21 }
22 }

* why line 3 not true ? because the form is not recognize and the variable sent method post doesn't exist so the first execute is line 20

* look at number line 20 , we passing object model from CONTROLLER to VIEW, now we look view


in VIEW Formulir, you can learn this  :
<div class="form">
<?php $form=$this->beginWidget('CActiveForm'); ?>

    <?php echo $form->errorSummary($model); ?>

<div class="row">
        <?php echo $form->label($model,'name'); ?>
        <?php echo $form->textField($model,'name') ?>
    </div>

<div class="row">
        <?php echo $form->label($model,'Deskripsi'); ?>
        <?php echo $form->textField($model,'description') ?>
    </div>

    <div class="row submit">
        <?php echo CHtml::submitButton('Simpan'); ?>
    </div>

<?php $this->endWidget(); ?>
</div><!-- form -->

* name and description is field on database
* method default is post and the data is send to current controller and current action, that's why after you click submit button the variable will be created and line 3 in controller will be executed

[YII] Basic CRUD


Description

        Memahami basic dari Create , Read , Update, and Delete.

Skill : *  Basic SQL - DML (Data Manipulation).

           * Basic Form , Controller , Model YII

How To :
        Untuk membuat agar web yang dibuat menggunakan framework YII bisa input data , edit data , atau  delete data sebetulnya tidak harus memahami penulisan syntax SQL karena memang sudah disediakan. tetapi pemahaman untuk SQL wajib didalami jika suatu saat ada kondisi yang tidak memungkinkan untuk menggunakan library dari framework YII ini.

       Untuk bisa melakukan CRUD pada YII , bisa dihadapkan 2 pilihan langsung yaitu mengakses classnya si model secara langsung (namescope) atau merubah dulu menjadi object, terserah sih itu pilihan anda tapi kebanyakan  rata menggunakan namescope mengakses classnya si model secara langsung tapi terkadang ada case" tertentu untuk menggunakan object. tapi di tutorial ini saya lebih menggunakan object karena sudah terbiasa dengan Framework Cakephp haha, ok to the point !


Our Setup :

  - Database Name : yii
  - Table Name : yiitest
     - Field 1 : id
     - Field 2 : name
     - Field 3 : description
  - Yii Model Name : Yiitest
  - Yii Controller Name : contoh

BASIC INPUT 

example:

class contohController extends Controller
{
     ...........another code ...........
     ...........another code ...........


       public function actionInsertion()
       {

       $AbstractDB = new Yiitest

       $AbstractDB ->name='Griffindor';
       if ($AbstractDB ->save())
       {
           echo 'Save Sukses';
       }
       else
       {
echo 'Save Failure'.'<br>';
$error = $AbstractDB ->getErrors();
        print_r($error);
       }
       $this->render('Insertion');
       }
}



BASIC EDIT

class ContohController extends Controller
{
     ...........another code ...........
     ...........another code ...........


       public function actionUpdating()
       {
               $AbstractDB = new Yiitest;
                // $AbstractDB ->updateByPk(PK_VALUE, array('FIELD'=>'NEW_VALUE'));
$AbstractDB ->updateByPk(1, array('description'=>'sukses bro'));
unset($DbAr);
       }
}




BASIC DELETE

class ContohController extends Controller
{
     ...........another code ...........
     ...........another code ...........


       public function actionDeleting()
       {
$AbstractDB =Yiitest::model();
$store= $AbstractDB ->find("name=:values",array(':values'=>'ravenclaw'));
$AbstractDB ->deleteByPk($store['id']);
               // hey look at ':values' the values refers to  ':values'=>'ravenclaw'
       }
}



BASIC READ
example:
class ContohController extends AppController
{
   ...........another code ...........
   ...........another code ...........


 public function actionReading()

 {
     // to get data from database we use CActiveDataProvider Class
     $dataProvider = new CActiveDataProvider('Yiitest');
     $resultSet = $dataProvider->getData();
     foreach ($resultSet as $datax)
     {
          echo $datax['id'].' '.$datax['name'].' '.$datax['description'].'<br>';
     }
  }
}

if you want datalist for value object Html like a list box you use this :

class ContohController extends AppController
{
   ...........another code ...........
   ...........another code ...........


 public function actionReading()

 {
     // to get data from database we use CActiveDataProvider Class
     $data = Yiitest::model()->findAll();
     $datacache = CHtml::listData($data,'id','name');
     print_r ($datacache);
     // the data looks like this 
     //Array ( [1] => mahendra )
     // [1] is value in field id
     // [mahendra] is value in field name 
  }
}

[YII] Basic View


Deskripsi

       Untuk memudahkan dalam pembuatan view, silahkan copy paste source code dibawah ini.

How To


1. View dibuat berdasarkan pada Action / Function yang dibuat di suatu Controller.

    jika anda mempunyai Action : index pada Controller : login   
    atau dalam bentuk codenya seperti ini pada controller :
    
    class loginController extends Controller
    {
          ..................Another code..........................
          ..................Another code..........................

          public function actionIndex()
          {
              // your code here 
             $this->render('index');
          }
    }

   maka path pembuatan view :
   YII_folder/protected/views/login/index.php
  
2. Ekstensi file .php 

3. Satu Action / Function pada Controller = Satu View

4. Satu Controller bisa punya banyak Action / Function

5. Sekarang bagaimana isi dari view ? silahkan belajar ke www.w3schools.com pilih menu Html / Php / Javascript :D



-End of  Basic View  -

[YII] Basic Model


Deskripsi
    YII mengimplementasi 2 jenis model yaitu Form model dan Active Record, Form model digunakan lebih ke arah untuk menangkap inputan user , di eksekusi kemudian dibuang. untuk contoh mekanismenya seperti halaman login form. sedangkan untuk yang Active Record lebih ke arah abstraksi dari database, menarik data dan kemudian mengolahnya, tapi untuk saat ini kita akan lebih fokus ke arah Active Record karena interaksi paling banyak terjadi disini. kali ini saya akan menggunakan cara manual ketimbang generate lewat GII Tools, kenapa manual karena klo membuat dengan cara manual kita akan lebih memahami isi dari model itu sendiri.

Howto
     1. Untuk membuat model path folder :
          webroot(htdocs/www) /Yii_Folder/protected/models/[you model here]
     2. Nama Model sama dengan Nama Classnya dan meng-extends class CActiveRecord
     3. 1 Model = 1 Table di 1 database
     4. Struktur Standart Model :

      <?php
      class Yiitest extends CActiveRecord
      {
public static function model($className=__CLASS__)
{
return parent::model($className);
}

public function tableName()
{
return 'yiitest';
}
      }
      ?>

        * Model memiliki 2 fungsi yang wajib ada yaitu
          - function model() // use standart format
          - tableName() // binding to your table
     
       5. Jika anda menggunakan GII tools , maka akan ada tambahan fungsi seperti :
          - function attributeLabels()
          - function function search()
          - function rules()
          - function relations()
          tenang aja itu hanya optional, udah saya test :)

        Your model now done, anda bisa gunakan model tersebut pada controller.










[YII] Basic Controller

This summary is not available. Please click here to view the post.

[YII] Short Fundamental



Deskripsi
      YII is powerfull PHP Framework in term of speed and perfomance, very suitable for use of e-commerce  website which has a complexity system and need high perfomance in handling a lot of traffic because the render is very fast !. but if you want to create a web application which ignore bandwidth of network (example for intranet) i suggesting u should learn Cakephp framework, very powerfull same as YII but the render rather slow. the benefit using cakephp is very easy to maintain by different programmers because all standart use of cakephp using an object very different with YII which still use namescoop to accessing class although it could create the object, consequently more difficult syntax understood by a new programmer.  

      ok let's start here how to access YII from URL, standart URL YII like this :
      http://YourHost/YiiFolder/index.php?r=controller/action&param1=value1&param2=value2
      for example
      http://localhost/Yii/index.php?r=Authenticate/Login&name=mahendra&password=123456

the statement above is only example, but never authenticate login form(username and password) with method = GET haha..... ok that's all about fundamental of YII Framework, simple right ?? 

next article i will explain about controller , action , CRUD , etc :D

hope this help you understand about YII, before go to section of controller or action YII, please read how to setup YII because this framework need a little adjustment :D

[YII] Create New Project


Deskripsi
       Tidak seperti framework kebanyakan begitu di download langsung bisa dipakai, YII perlu setting tersendiri agar dapat berjalan lancar, kesalahan path pada saat setting bisa juga menimbulkan error yang membuat kita pusing 7 keliling, ok selamat belajar !

Howto
      1. Download YII Source in  Here
      2. Taruh pada root webserver anda , wamp (www) or xampp (htdocs).
      3. Rename folder to yii.
      4. Open command prompt (CMD) and change your path to root webserver (www or htdocs)
          - in cmd your path must looks like this c:/wamp/www> or c:/xampp/htdocs>
      5. Now write this command when you still in root webserver
          for WAMP :
          c:/wamp/www/yii/framework/yiic webapps myproject
       
          for XAMPP
          c:/xampp/htdocs/yii/framework/yiic webapps myproject
       
          Full Example  :
          c:/wamp/www> c:/wamp/www/yii/framework/yiic webapps myproject
          c:/xampp/htdocs> c:/xampp/htdocs/yii/framework/yiic webapps myproject
 
         6. Now your project (myproject) created on your root webserver, you will see this new folder.


* Path mungkin bisa tidak sama karena sesuai dengan instalasi webserver anda.

hope this helps, if you still not understand please read the documentation :D

[YII] Connect Database Mysql / SQL Server 2005


Deskripsi
      Berikut adalah cara setup connection dari framework Yii (1.1.13) ke database Mysql / SQL Server 2005.    

Howto
      1. Activate extension php pdo_mysql (for mysql database) or pdo_mssql (for sqlserver database) , if you don't have pdo for sql server download Here (i hope you know how to activate extension php)
   
      2. Open your file in path Yiiproject/protected/config and see this 2 files :
          - console.php and main.php
   
      3. find string 'db' and equate the settings for 'db' :
       
         for example you have Specification like this :
          * Database : Sqlserver 2005 or Mysql
          * Database Name : 'dbnew'
          * Table : 'user_table'
          * Field : ID (PK + AI) , name

         and this is the correct settings :
          for Mysql Database (required pdo_mysql) :
               'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=dbnew',
'emulatePrepare' => true,
'username' => 'xxx',
'password' => 'xxx',
'charset' => 'utf8',
),

         for Sql Server 2005 Database (not tried another version) :
               'db'=>array(
'connectionString' => 'mssql:server=localhost;dbname=dbnew',
'username' => 'xxx',
'password' => 'xxx',
),

Hope this helps :D