Wednesday 13 November 2013

How to Get And Set Selected Dropdown Value in JQuery

<script type='text/javascript'>
// Get selected dropdown value

var country = $("#country option:selected").val();

// Set Selected dropdown value to another dropdown

$("#temp #country_id option[value='" + country + "']").attr("selected", "selected");
</script>

Working with Yii Active Record

findAll Syntax:

<?php
$data = Test::model()->findAll('id=:id', array(':id' => (int) $_POST['id']));
foreach ($data as $row) {
echo "" . $row->attributes['id'] . "";
echo "" . $row->attributes['name'] . "";
}
?>

findAll with DropDownList Syntax:

<?php
echo $form->labelEx($model, 'test_id');
$list = CHtml::listData(Test::model()->findAll('is_active=1', array('order' => 'name')), 'test_id', 'name');
echo $form->dropDownList($model, 'test_id', $list, array('empty' => 'Select Test Type'));
echo $form->error($model, 'test_id');
?>

findAllByAttribute Syntax

<?php
$data = Test::model()->findAllByAttributes(array('name' => explode(",", $_POST['type'])));
foreach ($data as $row) {
//Your Statement
}
?>

updateByPk Syntax

<?php
$model = $this->loadModel($id);
Test::model()->updateByPk($model->id, array("is_active" => 0));
?>

deleteAll by id Syntax

<?php
Test::model()->deleteAll("id=".$_POST['id']);
?>

CDbCriteria Find() Condition (Syntax 1)

<?php
$criteria = new CDbCriteria;
$criteria->condition = 'user_id =1 AND status=1';
$folder = Test::model()->find($criteria);
?>

CDbCriteria Find() Condition (Syntax 2)

<?php
$email='test@example.com';
$criteria = new CDbCriteria;
$criteria->select = 'name';
$criteria->condition = 'id=:id OR email=:email';
$criteria->params = array(':id' => $_GET["id"], ':email' => $email);
$result = Test::model()->find($criteria);
?>

Working with Yii Create Command

Select * Query using Create Command

<?php

// Example 1:

$sql = "SELECT * FROM table WHERE col1='data' AND col2=$id";
$result = Yii::app()->db->createCommand($sql)->query();
$rowCount = $result->rowCount;

// Example 2:

$sql = "SELECT * FROM table WHERE colname = '" . $_POST['data'] . "'";
$dbCommand = Yii::app()->db->createCommand($sql);
$data = $dbCommand->queryAll();
foreach ($data as $row) {
//------
//your statement
//------
}

?>

Insert into using Create Command

<?php
Yii::app()->db->createCommand()->insert('tablename', array(
  'col1' => col1data, 
  'col2' => col2data, 
  'col3' => "col3data" //varchar datatype
));
?>

Update Query using Create Command

<?php
Yii::app()->db->createCommand
("UPDATE user SET name = $name WHERE email=:em AND id=:cid")
->bindValues(array(':em' => "test@example.com", ':cid' => $id))
->execute();
?>

Delete Query using Create Command

<?php
Yii::app()->db->createCommand()->delete('colname', 'col_id=:id', array(':id' => $id));
?>

End Date should be greater than Start Date using CJuiDatePicker

<?php 
echo $form->labelEx($model, 'start_date');
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'htmlOptions' => array(
'size' => '10', // textField size
'maxlength' => '10', // textField maxlength
'class' => "input-small"
),
'options' => array(
'showAnim' => 'fold',
'dateFormat' => 'yy-mm-dd',
'changeMonth' => true,
'changeYear' => true,
'yearRange' => '2000:2099',
'onSelect' => 'js:function( selectedDate ) {
    // #end_date is the ID of end_date input text field
    $("#end_date").datepicker( "option", "minDate", selectedDate );
     }',
    ),
));

echo $form->labelEx($model, 'end_date');            
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'htmlOptions' => array(
'size' => '10', // textField size
'maxlength' => '10', // textField maxlength                        
'class' => "input-small"
),
'options' => array(
'showAnim' => 'fold',
'dateFormat' => 'yy-mm-dd',
'changeMonth' => true,
'changeYear' => true,
),
));
            
?>

Tuesday 12 November 2013

Remove default label from textFieldRow Yii

Add following labelOptions array in textFieldRow:


'labelOptions' => array('label' => false)

Example:


<?php
echo $form->textFieldRow($model, 'test', array(
'options' => array(
'width' => '200',
),
'labelOptions' => array('label' => false)
));
?>

Sunday 10 November 2013

How to get model attributes error in Yii Framework

getErrors() Method: It Returns the errors for all attribute or a single attribute.

Reference: http://www.yiiframework.com/doc/api/1.1/CModel#getErrors-detail

Example:
<?php
$valid = $model->validate();
print_r($model->getErrors());
exit;  //To show validation errors

if ($valid) {
    $model->save();
}
?>

How to run .sh file in Ubuntu command prompt

Give execute permission to your script

Example:

chmod +x /path/to/yourscript.sh


And to run your script

Example:

bash /path/to/yourscript.sh

How to calculate EMI using JQuery

Formula: EMI = (P * r/12) * [ (1+r/12)^n] / [ (1+r/12)^n-1]

Where,
P = Outstanding Principle
r = Interest Rate
n = Tenure (in months)


Following is the JS Code to calculate EMI

<script type="text/javascript">
function calculateEMI(obj) {                                               
 // Formula: 
 // EMI = (P * R/12) * [ (1+R/12)^N] / [ (1+R/12)^N-1]                               
                
 // isNaN(isNotaNumber): Check whether the value is Number or Not                
    if (!isNaN(obj.value) && obj.value.length !== 0) {
                    
    var emi = 0;
    var P = 0;
    var n = 1;
    var r = 0;                                       
                    
   // parseFloat: This function parses a string 
  // and returns a floating point number
    if($("#outstanding_principle").val() !== "")
       P = parseFloat($("#outstanding_principle").val());
                   
                        
    if ($("#interest_rate").val() !== "") 
      r = parseFloat(parseFloat($("#interest_rate").val()) / 100);

    if ($("#tenure").val() !== "")
        n = parseFloat($("#tenure").val());
                    
    // Math.pow(): This function returns the value of x to power of y 
    // Example: (5^2)
                    
    // toFixed: Convert a number into string by keeping desired decimals                   
                    
    if (P !== 0 && n !== 0 && r !== 0)
    emi = parseFloat((P * r / 12) * [Math.pow((1 + r / 12), n)] / [Math.pow((1 + r / 12), n) - 1]);
              
    $("#emi").val(emi.toFixed(2));
                
  }
}
</script>

And Following is the HTML code
<table>
   <tr>
     <th>Outstanding Principle</th>
     <th>Interest Rate (%)</th>
     <th>Tenure (in Months)</th>
     <th>EMI</th>
   </tr>
   <tr>
     <td>
       <input type="text" id="outstanding_principle" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" id="interest_rate" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" id="tenure" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" readonly="true" id="emi">
     </td>
 </tr>                
</table>

Demo