Wednesday, June 12, 2013

SCRIPT5 Access denied on form submit in IE if file is triggered

SCRIPT5 access denied is a problem when you want to trigger a input[type='file'] element on internet explorer(ie). Most of the browsers like mozilla, opera working by just triggering click on the file input field. But internet explorer(ie) does not like this and think this it as violation of access. So we just can put the file inside a div and make the input area whole around as div area. So when one click on the div, actually it clicks on the input element and open file selection dialog. And ie is now happy with it.
See the full result in jsFiddle.

jsFiddle view


Html and css

<div class="file_upload_section">
    <span>Click to upload</span>
    <input type="file" name="upload_file" />
</div>

<style type="text/css">
    div.file_upload_section {
        position: relative;
        background-color: yellow;
        padding: 20px
        font-weight: bold
        overflow: hidden;
    }
    
    div.file_upload_section input[type=file] {
        position: absolute;
        right: 0px;
        top: 0px;
        font-size: 2000px;
        height: 100%;
        opacity: 0;
        z-index: 1000;
        width: 100%;
    }
</style>

Additional jQuery code


$("div.file_upload_section").click(function() {
    var file = $(this).find("input[name='upload_file']");
    file.change(function() {
        var fileName = "Uploading: " + $(this).val().split("\\").pop();
        file.closest("div.file_upload_section").find("span").html(fileName);
    });
});

Tuesday, June 11, 2013

YII Get active controller and action name

Current Controller
Yii::app()->controller->id;
and Current Action
Yii::app()->controller->action->id;

Sunday, June 9, 2013

YII load model dynamically by model name


$phoneModel = $this->loadMyModel(100, "PhoneNumber"); 
 
public function loadMyModel($id, $modelName){
    $model = new $modelName();
    $criteria = new CDbCriteria;
    $criteria->condition = $model->getTableAlias().".id = :id";
    $criteria->params = array(
        "id" => $id
    );
    $data = new CActiveDataProvider($model, array(
        'criteria'=>$criteria
    ));
    if(count($data->getData()) > 0) {
        $data = $data->getData();
        $data = $data[0];
        return $data;
    }
    return null;
}

YII execute delete, update and select custom sql query

$command = Yii::app()->db->createCommand();

$sql='DELETE FROM phone WHERE contact_id=:contact_id AND id=:id';
$params = array(
    "contact_id" => $contactId,
    "id" => $id
);
$command->setText($sql)->execute($params);


$command=$connection->createCommand($sql); 
$rowCount=$command->execute();   // execute the non-query SQL
$dataReader=$command->query();   // execute a query SQL
$rows=$command->queryAll();      // query and return all rows of result
$row=$command->queryRow();       // query and return the first row of result
$column=$command->queryColumn(); // query and return the first column of result
$value=$command->queryScalar();  // query and return the first field in the first row
 
 
 
After CDbCommand::query() generates the CDbDataReader instance, one can retrieve rows of resulting data by calling CDbDataReader::read() repeatedly. One can also use CDbDataReader in PHP's foreach language construct to retrieve row by row.
$dataReader=$command->query();
// calling read() repeatedly until it returns false
while(($row=$dataReader->read())!==false) { ... }
// using foreach to traverse through every row of data
foreach($dataReader as $row) { ... }
// retrieving all rows at once in a single array
$rows=$dataReader->readAll();
 
 
 

Using Transactions

When an application executes a few queries, each reading and/or writing information in the database, it is important to be sure that the database is not left with only some of the queries carried out. A transaction, represented as a CDbTransaction instance in Yii, may be initiated in this case:
  • Begin the transaction.
  • Execute queries one by one. Any updates to the database are not visible to the outside world.
  • Commit the transaction. Updates become visible if the transaction is successful.
  • If one of the queries fails, the entire transaction is rolled back.
The above workflow can be implemented using the following code:
$transaction=$connection->beginTransaction();
try
{
    $connection->createCommand($sql1)->execute();
    $connection->createCommand($sql2)->execute();
    //.... other SQL executions
    $transaction->commit();
}
catch(Exception $e) // an exception is raised if a query fails
{
    $transaction->rollback();
}
 
 
 
 

Binding Parameters

To avoid SQL injectionattacks and to improve performance of executing repeatedly used SQL statements, one can "prepare" an SQL statement with optional parameter placeholders that are to be replaced with the actual parameters during the parameter binding process.
The parameter placeholders can be either named (represented as unique tokens) or unnamed (represented as question marks). Call CDbCommand::bindParam() or CDbCommand::bindValue() to replace these placeholders with the actual parameters. The parameters do not need to be quoted: the underlying database driver does it for you. Parameter binding must be done before the SQL statement is executed.
// an SQL with two placeholders ":username" and ":email"
$sql="INSERT INTO tbl_user (username, email) VALUES(:username,:email)";
$command=$connection->createCommand($sql);
// replace the placeholder ":username" with the actual username value
$command->bindParam(":username",$username,PDO::PARAM_STR);
// replace the placeholder ":email" with the actual email value
$command->bindParam(":email",$email,PDO::PARAM_STR);
$command->execute();
// insert another row with a new set of parameters
$command->bindParam(":username",$username2,PDO::PARAM_STR);
$command->bindParam(":email",$email2,PDO::PARAM_STR);
$command->execute();
 
 


http://www.yiiframework.com/doc/api/1.1/CDbCommand#delete-detail

Google visualization charts tooltip formating


<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
 google.load("visualization", "1", {packages:["corechart"]});
 jQuery(document).ready(function() {
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('string', 'Year');
  dataTable.addColumn('number', 'Sales');
  dataTable.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true} });
  dataTable.addColumn('number', 'Benefit');
  dataTable.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true} });
  dataTable.addRows([
   ['2010', 1990, '<b>$1990K in our first year!</b>', 1800, '<b>$1800K in our first year!</b>'], /* support any valid html */
   ['2011', 1500, '<i>$1500K in our second year!</i>', 1300, '<i>$1300K in our second year!</i>'],
   ['2012', 1200, '$1200K in 2012.', 1040, '$1040K in 2012.'],
   ['2013', 1000, '$1M in sales last year.', 910, '$910K in sales last year.']
  ]);

  var options =
    tooltip: {isHtml: true},
    chartArea: {width: "90%", left: 0, top: 0}
  };

  // Create and draw the visualization.
  var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
  ac.draw(dataTable, options);
 });
</script>
</head>
<body>
 <div id='visualization'></div>
</body>
</html>

 
https://developers.google.com/chart/interactive/docs/customizing_tooltip_content 
 
 

Friday, June 7, 2013

Solve PHP Fatal Error: Allowed memory size of 8388608 bytes exhausted

This error message can spring up in a previously functional PHP script when the memory requirements exceed the default 8 MB limit. However, do not fret because this is an easy problem to overcome.

To change the memory limit for one specific script, include a line such as this at the top of the script:
ini_set("memory_limit","12M");
The 12M sets the limit to 12 megabytes (12582912 bytes). If this does not work, keep increasing the memory limit until your script fits or your server squeals for mercy.
You can also make this a permanent change for all PHP scripts running on the server by adding a line such as this to the server’s php.ini file:
memory_limit = 12M

http://www.tech-recipes.com/rx/777/solve-php-fatal-error-allowed-memory-size-of-8388608-bytes-exhausted-tried/ 

Wednesday, June 5, 2013

How to draw a two y axis line chart in google charts


function drawVisualization() {
  var data = google.visualization.arrayToDataTable([
    ['x',                'Total Run', 'Centuary', 'Half Centuary'],
    ['January, 2013',    200,         1,           1],
    ['February, 2013',   105,         0,           1],
    ['March, 2013',      300,         1,           2],
    ['April, 2013',      305,         0,           5],
    ['May, 2013',        100,         0,           0],
    ['June, 2013',       290,         1,           2],
    ['July, 2013',       400,         2,           3],
    ['August, 2013',     180,         0,           1],
    ['September, 2013',  270,         1,           2],
    ['Ocotber, 2013',    170,         0,           1],
    ['November, 2013',   180,         1,           0],
    ['December, 2013',   240,         1,           2]
  ]);

  new google.visualization.AreaChart(document.getElementById('visualization')).
      draw(data, {
        curveType: "function",width: 500, height: 400,
        vAxes: {
          0: {logScale: false, maxValue: 100},
          1: {logScale: false, maxValue: 5}
        },
        focusTarget: 'category',
        series:{
          0:{targetAxisIndex:0},
          1:{targetAxisIndex:1},
          2:{targetAxisIndex:1}}
      }
   );
} 

Example Image: