Thursday, December 18, 2014

Yii: Check Column Exists before Create Column with Migration Script

You need only 3 simple step to Create Column via Migration Script.

Step 1:
- Create Migration Script with yiic command:
- Goto project and run the following command


protected/yiic migrate create alter_table_column


Step 2:
- Go to folder path protected/migrations and look for file name mxxxxxx_xxxxx_alter_table_column.php
- Add the following command in function up.


public function up()
 {
  $table = Yii::app()->db->schema->getTable('table_name');
  if(!isset($table->columns['column_name'])) {
      // Column doesn't exist then create column
   $this->addColumn('table_name', 'column_name', 'int(11) NOT NULL');
  }
 }

Step 3:
- Run migration script with the following command:


protected/yiic migrate 


~ EOF. Thanks for Reading. ~

Monday, November 10, 2014

PHP Packing Solution - How to divide items equally

This tutorial concept is actually come from stackoverflow where the solution was suggested in ruby script but I had translate it in PHP script.

$list_of_bags = array(11, 41, 31, 15, 15, 66, 67, 34, 20, 42, 22, 25);
# total weight of all bags
$weight_of_bags = array_sum($list_of_bags);
# how many containers do we have at our disposal?
$number_of_containers = 4;
# How much should one container weight?
$weight_per_container = $weight_of_bags / $number_of_containers;
# We make an array containing an empty array for each container
$containers[] = array();

$total = 0;

# For each bag
foreach ($list_of_bags as $bag) {
    for($i=0; $i<$number_of_containers; $i++){

        $total = (isset($containers[$i])) ? array_sum($containers[$i]) : 0;
        if($total + $bag < $weight_per_container){
            $containers[$i][] = $bag;
            break;
        }
    }
}

# output all containers with the number of items and total weight
foreach ($containers as $index=>$container) {
   echo "container $index has ";
   echo count($container);
   echo " ";
   echo "items and weigths: ";
   echo array_sum($container);
   echo "
";
}
Output:
container 0 has 3 items and weigths: 83
container 1 has 3 items and weigths: 96
container 2 has 2 items and weigths: 87
container 3 has 2 items and weigths: 76
container 4 has 2 items and weigths: 47

Wednesday, November 5, 2014

PHP Recursive Function

Tutorial by: Adam Lim


For example we need to create calculation as below:
5 => (5*2)+(4*2)+(3*2)+(2*1)+(1*1)

It can be resolved by for loop as below:

$total=0;
for($i=5; $i=0; $i--){
  $total += $i * 2;
}


To create a recursive function, it should as follow:

function test($int){
  if($int>0){
    echo $int.<br>;
    return(($int*2) + test($int-1));     // call back self function to continue loop
  }else{
    return 0;
  }
}

echo test(5);

Output:
5
4
3
2
1
30

DEMO

Dynamic Photo Framing API

Today bonus is to introduce photo framing api(apisilo.com) for framing industry. It is easy to use as you just need to pass four parameters which is art, frametop, framebtm, and framesize.

Parameter values and file format:
art - Photo or the artwork you wish to frame (only jpg, gif, png file format)
frametop - small piece of frame image, please see sample. (only jpg, gif, png file format)
framebtm - small piece of frame image, please see sample. (only jpg, gif, png file format)
framesize - integer value that you wish to control frame thickness.

How to use it:

Use with jquery getJSON to call API

$.getJSON("http://frame.apisilo.com/index.php?jsoncallback=?",
    {
      art: "http://www.tourismeoutaouais.com/blogue/wp-content/uploads/2014/10/halloween2-620x350.jpg",
      frametop: "http://www.imagemagick.org/Usage/thumbnails/blackthin_btm.gif",
      framebtm: "http://www.imagemagick.org/Usage/thumbnails/blackthin_btm.gif",
      framesize:"50"
    },
    function(data) {
        var str = data['result'];
        var finalData = str.replace(/\\/gi, '');

        $("#framed_artwork").attr("src",finalData);
    });

Append the result in framed_artwork as following:
<img id="framed_artwork" src="sample.jpg" />


DEMO

Monday, October 27, 2014

Step By Step Cross Domain Pass Parameter

Objective of this tutorial is helping those who want to create api but having the issue of cross domain problem.

How to Create Client Call API
Step 1:
Create javascript file name myjsfile.js and paste the following codes.

$(function(){
  $('#btn_name').on('click', function(e){
    $.getJSON("http://www.yourotherdomain.com/myapifile.php?jsoncallback=?",
    {
      variable1: "maybe textbox value",
      variable2: "maybe textbox value",
      variable3: "maybe textbox value"
    },
    function(data) {
        var str = data['result'];
        alert(str);
    });
  });
});

Step 2:
Include the following code before </head> tag.

<script src="js/myjsfile.js" type="text/javascript"></script>

You are now able to pass parameter to function from difference domain http://www.yourotherdomain.com/myapifile.php  .


How to Create Server Response
Step 1:
Create php file name myapifile.php and paste the following codes.

<?php
 header("Content-Type: application/json, charset: utf-8;");
 $arr=array();
 $arr['result'] = "Here is your result data";
 echo $_GET['jsoncallback'].'('.json_encode($arr).');';
 exit;
?>

~End~

Notice:
You may get Uncaught SyntaxError: Unexpected token if you did not include $_GET['jsoncallback'].

References:
http://stackoverflow.com/questions/3143698/uncaught-syntaxerror-unexpected-token
http://www.w3resource.com/JSON/JSONP.php

Thursday, July 31, 2014

PROGRAMMING TOOLS

Well, this is for my own references as people tend to forget many things when they're getting older. : D

System Analysis and Design Tools
  1. Pencil
  2. MySQL Workbench

Coding and Development
  1. Sublime Text 2
  2. Notepad ++
  3. MySQL
  4. TortoiseSVN
FTP Uploader
Online Testing Tools
  1. http://sqlfiddle.com/
  2. http://jsfiddle.net/
  3. http://regex101.com/
  4. https://www.functions-online.com/preg_match.html
  5. http://writecodeonline.com/php/
  6. http://www.bootply.com/
  7. http://putsmail.com/
  8. http://phpfiddle.org/
Bootstrap
  1. http://charliepark.org/bootstrap_buttons/
  2. http://fontawesome.bootstrapcheatsheets.com/
  3. To help you decide which to use http://tagliala.github.io/vectoriconsroundup/#angle-up
Allow Phone Access to Localhost
  1. fiddler2 : To enable connection between mobile device and localhost device, you must change mobile device's proxy ip to follow localhost device connection ip. Port number in mobile device should be same as port number in fiddler setting.
Welcome for more tools sharing.

Wednesday, June 25, 2014

Opening new window/tab without using `window.open` or `window.location.href`


Answer from stackoverflow.com:

What it does:
  1. Create a form
  2. Give it attributes
  3. Append it to the DOM so it can be submitted
  4. Submit it
  5. Remove the form from the DOM
Now you have a new tab/window loading "https://google.nl" (or any URL you want, just replace it). Unfortunately when you try to open more than one window at once this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).
Source Code:

var form = $("<form></form>");
form.attr(
{
    id     : "newform",
    action : "https://google.nl",
    method : "GET",
    target : "_blank"        // Open in new window/tab
});

$("body").append(form);
$("#newform").submit();
$("#newform").remove();

Friday, May 30, 2014

Yii: Step by Step Create Custom Component

Setup Component:

1. Create new class file in protected/components/Beauty.php
2. Start with the following code in Beauty.php

<?php
class Beauty extends CApplicationComponent
{
     public function makeup(){
        $colorbox = 'blue';
        return $colorbox;
     }
}
?>

3. Go to protected/config/main.php and add the following line under components:

'components'=>array(
   'beauty' = array (
            'class' => 'application.components.Beauty';
              ),
),


How to use it in controller:

1. In controller file:

<?php
  class FashionController extends Controller{
        //call beauty component;
       $beauty = Yii::app()->beauty;
       $color = $beauty->makeup();
       
        // output is blue;
        echo $color
  }
?>

Thursday, May 29, 2014

Yii: Step by Step Working with CFile Extension

CFile extension is commonly used for filesystem objects (files or directories) manipulate. The following step will show you how to config till how to use it.

Setup
1. Click on -> CFILE and download the folder.
2. Unzip and copy the folder in to protected/extensions path
3. Rename the folder to file
4. Add the following code into protected/config/main.php

'components'=>array(
    'file' => array(
        'class' => 'application.extensions.file.CFile',
     ),
 ),

How to Use
// yourfile
$yourfile = 'sample.txt';

// Call extension into $cfile variable
$cfile = Yii::app()->file;

// Check file exist
$cfile->set($yourfile)->exists;

// Create file
$cfile->set($yourfile)->create();

// Append Content
$cfile->set($yourfile)->setContents('treat me a coffee for this tutorial!');

// Get Content from file
$cfile->set($yourfile)->getContents();

// Delete File
$cfile->set($yourfile)->delete();


Others available method as follow:
  • Create
  • CreateDir
  • Purge
  • Contents (get; set for files, append possible; contents filters for directories)
  • Copy
  • Rename/Move
  • Send/Download ('x-sendfile' header support)
  • Delete
The properties of file you can check as follow:
  • exists
  • isdir
  • isfile
  • isempty
  • isuploaded
  • readable
  • writeable
  • realpath
  • basename (setter available)
  • filename (setter available)
  • dirname
  • extension (setter available)
  • mimeType
  • timeModified
  • size
  • owner (setter available)
  • group (setter available)
  • permissions (setter available)

Wednesday, May 28, 2014

Yii: Step By Step Create Yiic Console Command Line

This is interesting part in Yii that I like, we can create our own yiic console application to run our function.
http://www.yiiframework.com/doc/guide/1.1/en/topics.console#creating-commands

Step 1: Create Command Class File in path protected/command/shell/commands
class Commands extends CConsoleCommand  {  
    public function actionIndex() {
        echo "Possible action : getMember(), ...\n";
    }
    public function actionMember($id="", $status = "") {
       // action activities
    }  
}

Step 2: Set configuration in /protected/config/console.php
'commandMap' => array(
      'foo' => array(
          'class' => 'application.commands.shell.Commands',
      ),
  ),

Step 3: Test your console command

From command prompt, go to directory protected/ and run yiic. You will notice new command that you have created available on the list. To use your command, just type yiic foo --bar=123 --status=active


Jquery Looping Cause "long running scripts"

I have to load array variable into selection box (selectBoxIt plugin). First attempt was using $.each and it cause overhead in jquery, therefore I got error "long running scripts". It has been solved by replace $.each loop method with regular for loop method.

Solution:
$.ajax({
    url: '/GetBar',
    type: 'GET',
    dataType: 'json',
    async: true,
    success: function(data) {
      var selectBox = $("select#Bar").data("selectBox-selectBoxIt");
      var bar = [];
       for (var i=0;i<data.length;i++) {
         bar[i] = {value:data[i]['mdm_id'], text:data[i]['bar']}
       }
       selectBox.add(bar);
    }
  });

But there are more studies about performance among $.each and for loop in jquery, will check out when i free. (http://stackoverflow.com/questions/14808144/each-vs-each-vs-for-loop-in-jquery)

Monday, May 19, 2014

SelectBoxIt Change Text When Option Value Is Not Unique

Big thanks to my colleague, I resolved the error in SelectBoxIt.

This problem happened when option value is not unique, and it did not display the correct text after we select the option. The following is how i work it:

First, set option attribute to selected when we make change of the option.

$('#member_profession').change( function() {
      var selectedOption = $('#member_profession option:selected').text();
      $("#member_profession").find('option').removeAttr("selected");
      $("#member_profession option").filter(function(index) { return $(this).text() === selectedOption; }).attr('selected', 'selected');
  });

Then, we have to bind changed event to selectbox:

  $('#member_profession').bind({
    "changed" : function(ev,obj) {
      var selectedOption = $('#member_profession option:selected').text();
      var selectBox = $("#member_profession").data("selectBox-selectBoxIt");
      selectBox._setText(selectBox.dropdownText, selectedOption);
    }
  });

Taaadaaa.. Hope it is helpful and also good for future reference too. ^^

References Link:
http://gregfranko.com/jquery.selectBoxIt.js/#OptionsAPI

Thursday, April 3, 2014

Property "CClientScript.scripts" is not defined.

Property "CClientScript.scripts" is not defined.

Cause:
Most probably happened when it cannot locate yii file.

Solution:
Check the path from index.php file and yiic.php file. Make sure it point to Yii Root.

Yii Load data into select option list box dynamically + sorting

I would like to share how to sort list and load data into list box in yii.

Let say we have member table like Member(id, mid, name),

Controller File

<?php
class SignupController extends Controller
{
public function actionGetMember(){
    $json = array();
    $records = Member::model()->findAll(array('order'=>'id'));

    $count_records = count($records);
    if($count_records > 0){
      $json = array();
      foreach ($records as $record) {
        array_push($json, $record->attributes);
      }
    }

    echo json_encode($json);
}
}

?>

==============================
Js File

jQuery(function($) {

// To call profession and specialty listing
  $.ajax({
    url: 'signup/GetMember',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
      $.each(data, function(index, element) {
        $("<option></option>", {value: element['mid'], text: element['name']}).appendTo('#User');
      });
    }
  });

});

===========================
View File

<select id="User">
<option>Please select:</option>
</select>