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;'
  )
 )
);

Monday, February 13, 2012

Make upload file in yiiframework

Upload file in yiiframework is easy than the others. Simple to use this, you can use the functions of saveAs in yiiframework. Oke let's suppose you have a table like this :

t_users            
id_user              varchar(30)
profile_picture   varchar(100)
name                  varchar(50)

You can use gii to generate the model and the CRUD form. and then if you have already have those files. And now you can go to your form to edit the form like this. Don't forget to add the htmlOptions as multipart form data like below.

<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'tuser-form',
 'enableAjaxValidation'=>false,
 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>
<p class="note">
 Fields with <span class="required">*</span> are required.
</p>

<?php echo $form->errorSummary($model); ?>
 <div class="row">
  <?php echo $form->labelEx($model,'profile_picture'); ?>
  <?php echo $form->fileField($model,'profile_picture',array('size'=>60,'maxlength'=>200)); ?>
  <?php echo $form->error($model,'title'); ?>
 </div>
 

And then in your TUserController just update the actionUpdate and actionCreate like this ::

$model->attributes=$_POST['TUser'];
 $model->profile_picture=CUploadedFile::getInstance($model, 'profile_picture');
 if($model->save()){
  if(strlen($model->profile_picture)>0)
   $model->profile_picture->saveAs(Yii::app()->basePath.'/../upload/'.$model->profile_picture);
  $this->redirect(array('view','id'=>$model->id_user));
 }
Oke tha's so simple to create an upload for yiiframework..

if you want to make some filter of your files use the rules in your model, in this case is TUser model..

like this


public function rules()
    {
        return array(
            array('picture_profile', 'file', 'types'=>'jpg, gif, png'),
           ...
        );
    }

Yii is Rock..

Sunday, February 12, 2012

Using emultiselect in yii framework

In this sections I wanna explain the extension in yiiframework, If you have to enable multiple selections in your website, you can use emultiselect extensions in yiiframework. This extension is useful for you for enabling the multiple options of dropdownlist interface.

Lets take a look a sample of application that using this extension.

http://www.yiiframework.com/extension/emultiselect/

That's the look of emultiselect applications. And now we have to download this extensions in the url above. And then extract this to your site in protected/extensions folder. 

To use this great multiselect options just simple use this code


<?php $this->widget('application.extensions.emultiselect.EMultiSelect',
            array('sortable'=>true/true, 'searchable'=>true/true));?>

And then add class to the existing dropdownlist in your form view. for example :

echo $form->dropDownList(new TProjectHasTUnit(),'work_id_FK',$list,
       array('multiple'=>'multiple',
       'key'=>'unit_id', 'class'=>'multiselect')
     );


Note :


if you are using this for update action, pay attention for keeping the selected options to be selected. And to fulfill this purpose, you have to set the dropdownlist from your database.

To create this use have to take the value from your database first and for the example I use this :


<?php $this->widget('application.extensions.emultiselect.EMultiSelect',
            array('sortable'=>true/true, 'searchable'=>true/true));
    $m=TUnit::model()->findAll();
    $list=CHtml::listData($m,'unit_id','name');
    if($model->isNewRecord){
     echo $form->dropDownList(new TProjectHasTUnit(),'work_id_FK',$list,
       array('multiple'=>'multiple',
       'key'=>'unit_id', 'class'=>'multiselect')
     );
    }else{
     
     $selected_scope=TProjectHasTUnit::model()->findAllByAttributes(array('project_id_FK'=>$model->project_id));
     $selected_key_scope=array();
     foreach ($selected_scope as $val){
      $selected_key_scope[]=$val->work_id_FK;
     }
     echo $form->dropDownList(new TProjectHasTUnit(),'work_id_FK',$list,
       array('multiple'=>'multiple',
             'key'=>'unit_id', 'class'=>'multiselect','options'=>$this->createOptions($selected_key_scope))
     );
    }
  ?>

Don't forget to create the funtions $this->createOptions() in the protected/components/Controller.php for later use.



public function createOptions($arraySelectedValue){
  $selected_attr=array('selected'=>'selected');
  $all=array();
  foreach($arraySelectedValue as $val){
   $all["$val"]=$selected_attr;
  }
  return $all;
 }
That's simple and just follow that you can see the result.. Keep use this Yii is rock..