Monday, December 10, 2012

Make Different Cells css row or cells column in CGridView Yii

CGridview is one of the most powerful tools that you can do with generating table in Yii framework.But sometimes you want to include your own data into Columns properti as parameter to check data with the columns data that came from external sources.

The way you can do is creating the new gridview with the external data addition in the end. You can extend grid view with your own data and then place this code to the Components in yiiframework.


Yii::import('zii.widgets.grid.CGridView');
class GridViewWithVariable extends CGridView {
    public $params;
}
And then name it as GridViewWithVariable.php in components. And then you can create the new  array in your GridView like this

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'params'=>$params,
    'columns'=>array(
        'title',         
        'category.name',  
        'content:html',   
        array(            
            'name'=>'val',
            'value'=>'in_array(val,$this->grid->params)',//you can access your variable like this
        ),
        array(            
            'name'=>'authorName',
            'value'=>'$data->author->username',
        ),
        array(            
            'class'=>'CButtonColumn',
        ),
    ),
));

If you want to create different css in row you can create your custom Css like this. This is the gridview that created from CSqlDataProvider so you have to access your data via array like $data["DirekturID"].

$this->widget('GridViewWithVariable', array(
    'dataProvider' => $dataProvider,
    'params' => $arrNotResponsibleDirektur,
    'columns' => array(
        array(
            'name' => 'Direktur',
            'value' => '$data["Direktur"]',
            'cssClassExpression' => 'in_array($data["DirekturID"],$this->grid->params)?"normal":"merah"',
            'htmlOptions'=>array('width'=>'300px'),

        
        ),
        array(
            'name' => 'Yes',
            'type' => 'raw',
            'value' => '$data["ResponID"]=="1"?"✓":""',
            'cssClassExpression' => '"yes"',
            'htmlOptions'=>array('width'=>'40px'),
        
        ),
        array(
            'name' => 'No',
            'type' => 'raw',
            'value' => '$data["ResponID"]=="2"?"✓":""',
            'cssClassExpression' => '"no"',
            'htmlOptions'=>array('width'=>'40px'),
        
        ),
        array(
            'name' => 'Partially True',
            'type' => 'raw',
            'value' => '$data["ResponID"]=="3"?"✓":""',
            'cssClassExpression' => '"partially-true"',
            'htmlOptions'=>array('width'=>'40px'),

        
        ),
        array(
            'name' => 'Not applicable',
            'type' => 'raw',
            'value' => '$data["ResponID"]=="4"?"✓":""',
            'cssClassExpression' => '"not-applicable"',
            'htmlOptions'=>array('width'=>'40px'),

        
        ),
        array(
            'name' => 'Jawaban',
            
            'value' => '$data["Jawaban"]',

        ),
    )
));
And you can see the result here : You can use also "rowCssClassExpression" to use with different css color in CGridView row

Friday, July 27, 2012

Make underconstruction page in yiiframework

When you building a website you should have to think sometime when you are maintaining your website you should have to make your website off from the public.

And now to make that you can make a simple way to create under construction page

Here codes you can use in config main /protected/config/main.php. This trick does when you create empty file called underconstruction.txt in your root website.


return array(
  'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
  'name'=>'Your Site',
  'sourceLanguage'    =>'en_US',
  'language'          =>'en_US',
                'catchAllRequest' => (file_exists(dirname(__FILE__).'/../../underconstruction.txt')) ? 
die('<div style="text-align:center;line-height:300px;font-size:100px;>Under 
Construction</div>'): null,

That's code check all request to your yii site whether the file underconstruction.txt is exist or not in your root web directory. If it exist and then your website is under construction and view the message you have supply

Select random data from table in yiiframework

To random data some times we need it using logic of programming using variable but now I want to give you another short way to select random data from spesific table
Here some codes that you can try

$models=User::model()->findAll(array(
 'select'=>'*, rand() as rand',
 'limit'=>24,
 'order'=>'rand',
 )
);

From above code we can see that we fetch the table user using criteria. This codes give you a way to select all data with random position of order.

You can try that..

Friday, June 15, 2012

Make RadioButton List in Yii framework

Radio Button in yii framework is simple using radioButtonList function in CActiveForm. But how can we make a proper view to the design and get nice visual in yii.

This is how we can make a radiobutton list in yii with horizontal view. In the default the view will be vertical alignment.

And in your view just use this code like this :

<?php echo $form->radioButtonList($model,'GENDER',array('2'=>'Females','1'=>'Males'),array(
                'separator'=>'&nbsp;',
                 'labelOptions'=>array(
                           'style'=>'display: inline; margin-right: 10px; font-weight: normal;')
    )?>
That's all and you can make a better view of using radioButtonList in yiiframework.

Wednesday, May 30, 2012

Tiny Mce Errors in the server yiiframework

Maybe some of you that using tiny mce ever have an error when using tiny mce in the server like this in the firebugs:

"NetworkError: 500 Internal Server Error - http://example.com/assets/96646869/tiny_mce/tiny_mce_gzip.php?js=true&diskcache=true&core=true&suffix=&themes=advanced&plugins=safari%2Cpagebreak%2Cstyle%2Clayer%2Ctable%2Csave%2Cadvhr%2Cadvimage%2Cadvlink%2Cemotions%2Cspellchecker%2Cinlinepopups%2Cinsertdatetime%2Cpreview%2Cmedia%2Csearchreplace%2Cprint%2Ccontextmenu%2Cpaste%2Cdirectionality%2Cfullscreen%2Cnoneditable%2Cvisualchars%2Cnonbreaking%2Cxhtmlxtras%2Ctemplate&languages=en" 

Don't worry, this is the perrmission issue from your folder in the server. To solve the problems is simple
Add the permission folder recursively to 755.

For the example the folder begin from asset/96646869/tiny_mce

Change the all folder permissions to  755...

Good Luck

Sending email in yiiframework using yii-mail extensions

Sending email in a website is one of the main function to have interaction with the users and one of main features of the website.

For yii users maybe ever had error when sending the emails in the localhost with some kinds of warning.

The error maybe like this :

mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() 

It has caused because in the localhost there is no mail server so you can even send email. To solve this issue you must install mail server in your local computer such as hMailServer.

Or if you want to use the mail server from your provider you can use the SMTP configuration email from the provider.

Wednesday, April 18, 2012

Make ajax validation true in your captcha in yiiframework

Maybe you want to use your captcha in your yiiframwork to use in ajaxvalidation to be true. By default the setting may use you as ajaxvalidation false. But when you want to make it available to be in ajax validation true a little bit tricky you have to look.
Let's take alook the solution I get when digging the yii forum..

Thanks to the members there.


In the default form page in your yiiframework you should look like this :


<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'user-form',
 'enableAjaxValidation'=>false,
        'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>
 

Set default page in Clistview or CGridview in the last page yiiframework

By default default page of Clistview or Cgridview only set to the front of clistview or in the first page as default page. But when you want to use the last page as your default page to be viewed to user you have to modified the pagination in the data provider. You can use this to show when you are using the clistview or component that has the pagination object like others. Maybe you can use this as default discussion thread.

Let's take a look the code that you should have to write down.

if(Yii::app()->request->isAjaxRequest){
 $dataProvider=new CActiveDataProvider('KomentarThread',array(
   'criteria'=>array(
     'condition'=>'ID_THREAD=:id_thread',
     'params'=>array(':id_thread'=>$model->ID_THREAD)
   )
 ));
 $p=$dataProvider->pagination;
 $p->setItemCount($dataProvider->getTotalItemCount());
 $p->currentPage=$p->pageCount-1;
 $this->renderPartial('/komentarThread/_comments_all',array(
   'all_komentar'=>$dataProvider)
   ,false,true);
 Yii::app()->end();
}

The part of $p variable is to set your currentPage to the last page.

So enjoy your modification of your data provider...

Thursday, April 12, 2012

Make captcha in yii framework

If you want to make captcha in yiiframework you have gone to the right place. I want to teach you about how to make captcha in yiiframework.

You can make captcha in yiiframework easy because yii has featured to make the captchaa easily. So let't take a look how to make the captcha in yiiframework

To make the capctha you have to do :
  • Add the code rules to your controller id. For example UserController. 
  •  public function actions(){
      return array(
        // captcha action renders the CAPTCHA image displayed on the user registration page
        'captcha'=>array(
          'class'=>'CCaptchaAction',
          'backColor'=>0xFFFFFF,
        ),
      );
     }
    

Thursday, April 5, 2012

URL in yii Framework

Maybe sometime you are confuse about the standard getting url in Yii Framework. You can use some of the pattern below of the url in yii framework

FULL URL ==> http://www.example.com:8080/project/index.php?r=post/view&id=123

PROPERTY
hostInfo     http://www.example.com:8080
port                                8080
baseUrl                                 /project
url                                     /project/index.php?r=post/view&id=123
requestUri                              /project/index.php?r=post/view&id=123
scriptUrl                               /project/index.php
queryString                                                r=post/view&id=123
scriptFile                 /var/www/html/project/index.php

You can access this url with the code of url :


Yii::app()->request->hostInfo;
Yii::app()->request->port; 
Yii::app()->request->baseUrl;
Yii::app()->request->url; //and the other property

Now You can choose your property you need

Tuesday, April 3, 2012

Using CJuiAutoComplete in yii framework

In the version 1.1.3 yii CAutoComplete was deprecated, so for better result you should consider using CJuiAutoComplete to make autocomplete in yii framework.

To use this widget is more easy to use but with the multiple selections of CJuiAutoComplete maybe you should have to implements more javascript functions.

Let's take a look how to make CJuiAutoComplete with multiple selection enabled. Assume you have code in the article in views article /protected/views/article/_form.php. And I have table with just only 2 fields : id_tag and name

Wednesday, March 14, 2012

How to add multi-language site in yii framework

To make multi language in your yii framework you have to implements some rules. You can use the session variables to make the translation between your page. With the the documentation you can look at here.

I have to implements this to make the translation page. You can follow the instruction in that articles that not almost I discuss in this page.

But when I finish implement that step, I can make my own translation page on the protected/messages/<your language id>/<your category>.php files..

For the example :

../protected/messages/id/translation.php

The example of the translation page that I use like this
<?php
/**
 * Bahasa Indonesia Yang digunakan untuk menerjemahkan
 */
return array(
  //------NAVIGASI MENU------------//
  'Home'=>'Beranda',
  'About'=>'Tentang',
  'Contact'=>'Kontak',
  'Login'=>'Masuk',
  'Logout'=>'Keluar',
  
  
  
  //-----------ISI KONTEN DEPAN------------------//
  'What are You Looking For?'=>'Apa Yang Anda Cari?',
  'Sell Your Products'=>'Mau Menjual Barang',
  'Products'=>'Barang',
  'Services'=>'Jasa'
  
  );
?>

Oke when you finish that I use my native languages (Indonesian=ID) and than I can use that for my translation in my code using this example in your view files.



echo Yii::t('translation','Home');

Tuesday, March 13, 2012

Alternative Way to make Dropdown menu in yii

Maybe you are a newbie and want to make dropdown in yii just like me before. Oke to make dropdown menu in yii is simple. You can use this solution to make your Dropdown list..
Maybe you can check my post before here

From there you can use this in two ways of using dropdown list in yii framework

The first one is just like my post before :

<div class="row">
  <?php echo $form->dropDownList($model,'country_id',
   CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
   array('empty'=>'Select Country'))?>
 </div>

And the other option is using CHtml::dropDownList like this suppose you have to make your view class with the Users model

<div class="row">
  <?php echo CHtml::dropDownList('Users[country_id'],'',
   CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
   array('empty'=>'Select Country'))?>
 </div>
That's the other option that you can choose..

Thursday, March 8, 2012

How to make CGridview with dropdown filter

To get the filter of your CGridView you have to add filter parameters in your CGridview call. This filters can be an instance of the object active records. If you want to add some filtering of your model with dropdown menu you can see the example below :


$this->widget('zii.widgets.grid.CGridView',array(
   'dataProvider'=>$model->search(),
   'id'=>'risk-id',
   'filter'=>$model,
   'columns'=>array(
   array(
      'name'=>'No',
      'type'=>'raw',
      'value'=>'$this->grid->dataProvider->pagination->currentPage*$this->grid->dataProvider->pagination->pageSize + $row+1',//this for the auto page number of cgridview
      'filter'=>''//without filtering 
   ),
   array(
      'name'=>'name',
      'type'=>'raw',
      'value'=>'Chtml::link(Chtml::encode($data["name"]),array("risk/view","id"=>$data["risk_id"]))',
      'filter'=>CHtml::listData(Risk::model()->findAll(
                  array(
                   'select'=>array('name'),
                   'distinct'=>true
                   
                  )),"name","name")//this is the focus of your code
      
   ),
   array(
      'name'=>'date_identified',
      'type'=>'raw',
      'value'=>'Chtml::encode($data->date_identified)'
   ),
   array(
      'name'=>'description',
      'type'=>'raw',
      'value'=>'Chtml::encode($data->description)'
   ),
   array(
      'name'=>'type',
      'type'=>'raw',
      'value'=>'Chtml::encode($data->type)',
      
   ),
   array(
      'name'=>'link',
      'type'=>'raw',
      'value'=>'$data->link'
   ),
   

)

));

YOu can see that in the field of name, You can put the dropdown box to your filtering attribut. In this example I use the data of name in my risk table and get the distinct value of it.


You can also make your spesific column to exclude the filtering by passing parameter filter to null object or '' object.

And the result you can see here :




Wednesday, March 7, 2012

Using CMaskField in your yii framework

In order to supply the format of your textfield sometimes you should have to implement the specific format of your textfield. It can be solved by using the existing widget in yii framework.

You can look at this http://www.yiiframework.com/doc/api/1.1/CMaskedTextField to make CMaskedTextField that give you the alternative way to give preformatted textfield.


Oke let's take look the code :


<?php
$this->widget('CMaskedTextField', array(
'model' => $model,
'attribute' => 'aluguel',
'mask' => '(999) 999-9999? x99999',
'htmlOptions' => array('size' => 6)
));
?>
This is with the regex types
<?php
$this->widget('CMaskedTextField', array(
'model' => $model,
'attribute' => 'aluguel',
'mask' => '9.999,99',
'charMap' => array('.'=>'[\.]' , ','=>'[,]'),
'htmlOptions' => array('size' => 6)));
?>
And the final code you can see below the result here is:


.The following mask definitions are predefined:
  • a - Represents an alpha character (A-Z,a-z)
  • 9 - Represents a numeric character (0-9)
  • * - Represents an alphanumeric character (A-Z,a-z,0-9)


Tuesday, March 6, 2012

Insert widget to another widget in Yii

For this time I want to share how I accomplish inserting widget in yii to another widget..

You can take a look of this code of using widget in yii :

  $this->widget('ext.xxx.yyy',array(...)); 
It executing echo statement in yii so if you want to insert widget to another widget you have to get the result of this string.

To get this way you have to save the result before and then insert those string to another widget using ob_start(). 


Oke let's take a look of example how we can insert cjuislider inside of cdetailview..

the widget is as below :


<?php
//save the result of this result of string to slider variable
ob_start();
$this->widget('zii.widgets.jui.CJuiSliderInput', array(
    'name'=>'my_slider',
    'value'=>0,
    'event'=>'change',
    'options'=>array(
        'min'=>0,
        'max'=>100,
        'slide'=>'js:function(event,ui){$("#amount").text(ui.value);}',
),
    'htmlOptions'=>array(
        'style'=>'width:200px; float:left;'
),
));
echo '<div id="amount"></div>';
$slider=ob_get_contents();
ob_end_clean();

?>
<?php $this->widget('zii.widgets.CDetailView', array(
 'data'=>$model,
 'id'=>'hor-minimalist-b',
 'attributes'=>array(
  'project_id',
  'title',
  array(
         'label'=>'Project proposal',
         'type'=>'raw',
         'value'=>empty($model->project_proposal)?"":CHtml::link($model->project_proposal,Yii::app()->homeUrl.'/../upload/'.$model->project_proposal),
  ),
  array(
         'label'=>'Progress',
         'type'=>'raw',
         'value'=>$slider,//this variable that's get from the code above
  ),
  'start_time_actual',
  'end_time_actual',
//   'id_FK',
  'scope_name'
 ),
));
?>

Oke that's simple way how to insert widget to another widget in yii If you have another good solution just share yours..

Monday, March 5, 2012

Add paging index in your CListView

If you are using CListView to populate your data you can customize your view to show the automatic number of your CListView..

you can just add $index variable to your _view in CListView


<div class="view" >
 <i><b><?php echo CHtml::encode($data->getAttributeLabel('Project title')); ?>:</b></i>
 <span class="info">
 <?php echo $index+1;?>//this is the variable in CListView
 </span>
 <h3><?php echo CHtml::link(CHtml::encode($data->title), array('view', 'id'=>$data->project_id)); ?></h3>

In your index file in your view you can see like this :


<h1>Projects</h1>

<?php $this->widget('zii.widgets.CListView', array(
 'dataProvider'=>$dataProvider,
 'itemView'=>'_view',
)); ?>

Make page numbering in CGridview yii framework

This time I want to share how we can easily modify CGridView based on the table shown to add automatic numbering of CGridView.

Let's take a look how we can set up this with little modification :
See the example below :


$this->widget('zii.widgets.grid.CGridView',array(
   'dataProvider'=>$provider,
   'id'=>'components-id',
   'columns'=>array(
     array(
      'name'=>'No',
      'type'=>'raw',
      'value'=>'$this->grid->dataProvider->pagination->currentPage*$this->grid->dataProvider->pagination->pageSize + $row+1'//this is the numbering of your cgridview
      ),
     array(
      'name'=>'Name',
      'type'=>'raw',
      'value'=>'Chtml::link(Chtml::encode($data->name),array("risk/view","id"=>$data->risk_id))'
      ),
     array(
      'name'=>'Date Identified',
      'type'=>'raw',
      'value'=>'Chtml::encode($data->date_identified)'
      ),
     array(
      'name'=>'description',
      'type'=>'raw',
      'value'=>'Chtml::encode($data->description)'
      ),
     
    )
   
 ));

Voila now we can see an automatic number in your CGridView..