Friday, March 2, 2012

Make ajax request in yii framework

To make ajax request in yii framework is simple to use. For the usual  ajax request from jquery we can use this pattern like this..

$.ajax({
    url:"http://localhost/request.php",//this is the request page of ajax
    data:{params1:param1,param2:param2},//data for throwing the expected url
    type:"POST",//you can also use GET method
    dataType:"html",// you can also specify for the result for json or xml
    success:function(response){
         $('#result_selector').html(response);
    },
    error:function(){
         alert('Failed request data from ajax page");
    }

But in yii the ajax function has been integrated to the yii native function. There are many choices for you to make ajax call through button, link or other components.. From the documentation we can take a look of this part.

ajax()Generates the JavaScript that initiates an AJAX request.CHtml
ajaxButton()Generates a push button that can initiate AJAX requests.CHtml
ajaxSubmitButton()Generates a push button that can submit the current form in POST method.CHtml
That's the list of function supported by yii function. you can use that to populate the ajax request just use that function.

Oke let's take a look below code for the example

<?php
       echo CHtml::ajaxButton(
            'Submit request',
            array('test/function'),
            array('data'=>array('test'=>$model->id)),
            array('update'=>'#update_selector')//this is the update selector of yours $('#update_selector').load(url);
        );
?>
And then don't forget if you want to make an ajax call you should have to use renderPatial so the whole contents is not included.
public function actionFunction() {
 if(Yii::app()->request->isAjaxRequest){
  $this->renderPartial("_form",array('model'=>$model),false,true);
  Yii::app()->end();

 }
}
That's the easy look of yii function..


Wednesday, February 22, 2012

Make checkbox using ajax load in yiiframework

Sometimes you have to implement function for loading ajax content from another link to your page using checkbox. In yii there is also CHtml::activeCheckbox functions that can be used to fulfill this. But if you want to enable this checkbox to allow you loading ajax content you have to use a custom code because if you use ajax property in htmlOptions the checkbox can not be selected because in the end of generated code it has return false; 


So to custumize this I have one way for solving this problem. The way is just to create your own script to make this conditions just see this example below..


<?php echo CHtml::checkBox("load_ajax",false,array('id'=>'load_risk_all'));echo "Load All Risk Child";
$url=CController::createUrl('project/vieweach',array('project_id'=>$model->project_id));
Yii::app()->clientScript->registerScript("check",
           '$("#load_risk_all").change(function(){
             if($(this).is(":checked")){
              $("#load_risk").load("'.$url.'");
              $("#load_risk").fadeIn();
             }else{
              $("#load_risk").html("");
             }
             })
          ',
           CClientScript::POS_READY);

?>
<div id="load_risk">
</div>

And then you have to make sure for using partialRender for the content in your controller. You can also to customize your code of load() function in jQuery for loading the ajax content using $.ajax functions with the data you want.

$this->renderPartial('/risk/view_each',array('provider'=>$provider),false,true);


You can also use onChange event in checkbox htmlOption for supporting your own javascript model like this


<?php echo CHtml::checkbox("load risk",false,array("onChange"=>"js:yourcustomfunction()")); ?> //don't forget to register your own function in script tag
Then nice use this..

Make dropdownlist in yii framework

Oke let's take a look how to make a yii dropdownlist box. In yii you can easily build your dropdown list box using CHtml::dropdownListbox

Suppose you have a table of tbl_country

country_name | id
Indonesia        | 1
USA               | 2

And you want to add your data into a form in your model to show as a dropdown list. Just edit your _form files in your view and add this following code


       <div class="row">
  <?php echo $form->dropDownList($model,'country_id',
   CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
   array('empty'=>'Select Country'))?>
 </div>
That's just simple to do with yii. Have to try it!..

Monday, February 20, 2012

Make your own rule in yii framework

If you want to create new rules that doesn't meet to your spesification in your model you can create your custom rules in your model.

To accomplish this just simple add your custom function in your model. And then add the function in rules that you have created.

The example can be seen below code to define my custom function


public function beforeProjectStart($attribute,$params){
  $project=Project::model()->findByPk($this->project_id_FK);
  if(Utils::getDaysBetweenTwoDatesForModel($this->start_time_planned, $project->start_time_planned)<0)//jika start date pada components lebih besar dari start date dari project maka error
   $this->addError($attribute, "Start time component planned must be more than project start planned ".$project->start_time_planned);
 }
 public function beforeProjectEnd($attribute,$params){
  $project=Project::model()->findByPk($this->project_id_FK);
  if(Utils::getDaysBetweenTwoDatesForModel($this->end_time_planned, $project->end_time_planned)>0)//jika start date pada components lebih besar dari start date dari project maka error
  $this->addError($attribute, "End time component planned must be more than project end planned ".$project->end_time_planned);
 }

And then you can add your custom rules as below in your rules()
public function rules()
 {
  // NOTE: you should only define rules for those attributes that
  // will receive user inputs.
  return array(
  array('name', 'required'),
  array('start_time_planned','beforeProjectStart'),
  array('start_time_planned','beforeProjectEnd'),
That's simple to custom your own rules and add your custom message to your rules. Yii is ROck..

Friday, February 17, 2012

Make rule of date in model yiiframework

If you want to simple create a rule validation about comparing between date, you have to see CCompareValidator. To create this validator just simple to use this. From the documentation of rules in model you can see this :


compare : CCompareValidator, compares the specified attribute value with another value and validates if they are equal.
  1. allowEmpty, whether the attribute value can be null or empty.
  2. compareAttribute, the name of the attribute to be compared with.
  3. compareValue, the constant value to be compared with.
  4. operator, the operator for comparison.
  5. strict, whether the comparison is strict (both value and type must be the same.
And to use this just see the example below to rules() in your model..

                 array(
     'start_time_planned',
     'compare',
     'compareAttribute'=>'end_time_planned',
     'operator'=>'<=', 
     'allowEmpty'=>false , 
     'message'=>'{attribute} must be greater than "{compareValue}".'
   ),
the operator can be =,<,>. and you can have a custom message for error in "message" property

Thursday, February 16, 2012

Adding and substracting date in PHP

In this time I want to share code for letting you adding and subtracting date in php. You can use this for easy to add the day, week, or year from specific date in PHP.

Let's take a look for this code :

$date = "2012-02-16";
$newdate = strtotime ( '-3 day' , strtotime ( $date ) ) ; //substracting date to 3 days before
$newdate2 = strtotime ( '+3 week' , strtotime ( $date ) ) ;/substracting date to 3 weeks after
 
$newdate3 = strtotime ( '-3 year' , strtotime ( $date ) ) ;//substracting date to 3 years before
$newdate = date ( 'Y-m-j' , $newdate ); //save to new variable
echo $newdate;

The other code for you to use the date variable in PHP

$d = mktime(0,0,0,$month,$day,$year);
$end_date = date("Y m d",strtotime("+2 days",$d));
//To add days to current date
date('Y-m-d', strtotime("+2 days"));


Just share the code in my mind.

Wednesday, February 15, 2012

Simple tricks for creating repeating functions in form

This just a simple trick for writing your code in yiiframework for not repeating the same work.

If we have a functions that has a repeating use in our view for example you have a project that has many of date picker in a project management applications, so you have to write this in your form repeatly.


$this->widget('zii.widgets.jui.CJuiDatePicker',
 array(
  // you must specify name or model/attribute
  //'model'=>$model,
  //'attribute'=>'projectDateStart',
  'name'=>'Project[projectDateStart]',

  // optional: what's the initial value/date?
  //'value' => $model->projectDateStart
  'value' => '08/20/2010',

  // optional: change the language
  //'language' => 'de',
  //'language' => 'fr',
  //'language' => 'es',
  'language' => 'pt-BR',

  /* optional: change visual
   * themeUrl: "where the themes for this widget are located?"
   * theme: theme name. Note that there must be a folder under themeUrl with the theme name
   * cssFile: specifies the css file name under the theme folder. You may specify a
   *          single filename or an array of filenames
   * try http://jqueryui.com/themeroller/
  */
  'themeUrl' => Yii::app()->baseUrl.'/css/jui' ,
  'theme'=>'pool', //try 'bee' also to see the changes
  'cssFile'=>array('jquery-ui.css' /*,anotherfile.css, etc.css*/),


  //  optional: jquery Datepicker options
  'options' => array(
   // how to change the input format? see http://docs.jquery.com/UI/Datepicker/formatDate
   'dateFormat'=>'mm/dd/yy',

   // user will be able to change month and year
   'changeMonth' => 'true',
   'changeYear' => 'true',

   // shows the button panel under the calendar (buttons like "today" and "done")
   'showButtonPanel' => 'true',

   // this is useful to allow only valid chars in the input field, according to dateFormat
   'constrainInput' => 'false',

   // speed at which the datepicker appears, time in ms or "slow", "normal" or "fast"
   'duration'=>'fast',

   // animation effect, see http://docs.jquery.com/UI/Effects
   'showAnim' =>'slide',
  ),


  // optional: html options will affect the input element, not the datepicker widget itself
  'htmlOptions'=>array(
  'style'=>'height:30px;
   background:#ffbf00;
   color:#00a;
   font-weight:bold;
   font-size:0.9em;
   border: 1px solid #A80;
   padding-left: 4px;'
  )
 )
);