Find us on facebook

Jul 29, 2014

Relationships in Yii

BELONGS_TO: e.g. Student belongs to School
HAS_MANY: e.g. School has many Student
HAS_ONE: e.g. Teacher has at most one School
MANY_MANY: e.g. Student belongs to many Teacher and Teacher has many Student.

​​class Student extends CActiveRecord
{
  public function relations()
     {
  return array(
              'school'=>array(self::BELONGS_TO, 'School', 'school_id'),
              'teachers'=>array(self::MANY_MANY, 'Teacher','tbl_student_teacher(student_id, teacher_id)'),
         );
 }
}

class School extends CActiveRecord
{
    ......
    public function relations()
    {
        return array(
            'students'=>array(self::HAS_MANY, 'Student', 'school_id'),
            'teacher'=>array(self::HAS_ONE, 'Teacher', 'school_id'),
        );
    }
}

FindAll() in Yii

$sql="SELECT image from table_type_images where table_type_id =".$Table->shape." AND chairs = ".$Table->chairs;
$TableTypeImage = TableTypeImages::model()->findBySql($sql);

$Table=Table::model()->findByPK($table_id);

$models = Vehicle::model()->findAll( array('order' => 'vehicle_no'));

$AuthitemDes = Authitem::model() -> findAll('type = 0 AND description IS NOT NULL');
FindAll with Where clause = condition
MainMenu::model() -> findAll(array("condition"=>"res_id =  $res_id","order"=>"name"));​

FindAll with Where clause Like condition
$Staff= CHtml::listData(AuthAssignment::model() -> findAll('itemname LIKE :Staff',array(':Staff' => "%Staff%")), 'userid', 'userid');

Joining Two tables
$criteria=new CDbCriteria;$criteria->select = 't.userid,users.username';$criteria -> join = 'JOIN  users on userid= users.id';$criteria->condition = 'itemname LIKE :Staff OR itemname LIKE :Admin OR itemname LIKE :Cashier'; $criteria->params    = array(':Staff'=>'%Staff%',':Admin'=>'%Admin%',':Cashier'=>'%Cashier%'); $criteria->order = 'username DESC,userid DESC';$Staff = AuthAssignment::model()->findAll($criteria);$StaffList= CHtml::listData($Staff, 'userid', 'username');​echo $form->dropDownList($model,'emp_id',$StaffList);​



$res_id = $_POST['res_id'];

$criteria=new CDbCriteria;
$criteria->select = 'Distinct t.id,t.name';
$criteria -> join = 'JOIN  menu on t.id= menu.main_menu';
$criteria->condition = 't.res_id =:res_id'; 
$criteria->params    = array(':res_id'=>$res_id); 



$mainMenu = MainMenu::model() -> findAll($criteria);

Jul 18, 2014

Javascript Submit Form

<?php
             
echo '<a href="javascript: submitform()">Next</a>'

 ?>
<script type="text/javascript">
function submitform()
{
    document.forms["rep-data-models-form"].submit();
}
</script>

Submit form to specific action
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'rep-data-models-form',
'action' => Yii::app()->createUrl('reports/repColumns/create'),
'enableAjaxValidation'=>true,
'htmlOptions' => array(
                'enctype' => 'multipart/form-data',
            ),
));

?>

Yii Radio Button List onchange event with javascript

<?php
             
echo $form->radioButtonList($model,'MODELID',CHtml::listData($model::model()->findAll(), 'MODELID', 'MODELNAME'),array('separator'=>' ','labelOptions'=>array('style'=>'display:inline'),'class'=>'rad','onchange'=>'getRadioValue();'));
echo CHtml::hiddenField('dataModel','',array('id' => 'dataModel'));
 
?>
<?php
Yii::app()->clientScript->registerCoreScript('jquery');
?>
<script>
function getRadioValue(){
var value = $("input[type='radio']:checked").val();
$("#dataModel").val(value);

}
</script>

onchange check box checked - javascript with yii checkboxlist

<?php
$areas = CHtml::listData(Area::model()->findAll("type='Postcode'"), 'id', 'name');
$areacharges = CHtml::listData(DeliveryCharge::model()->findAll(), 'area_id', 'charge');
echo CHtml::checkBoxList('postcodes[postcodes][]', $areas['id'], $areas,
array(
'labelOptions'=>array('style'=>'display:inline;line-height: 3em'),
'separator' => '<br>',
'onclick'=>'getValue();'
)
);
?>

<?php

foreach($areas as $key=>$value){
$areacharges = DeliveryCharge::model()->find("area_id=$key");
?>

<div id="<?php echo $key;?>" style="visibility:hidden;margin-bottom: 12px;" class="inputmenu">
<?php echo CHtml::textField("pcharges[pcharges][$key]","$areacharges->charge",array('size'=>10,'class'=>'inputmenu','id'=>"charges".$key));?>
</div>

<?php

}
?>

function getValue(){
$("input[type='checkbox']:checked").each(function()
{
var value =$(this).val();
document.getElementById(value).style.visibility = 'visible';
});
$("input[type='checkbox']:not(:checked)").each(function()
{
var value =$(this).val();

document.getElementById(value).style.visibility = 'hidden';
//$("#charges" +value).val('');

});
}



Jul 17, 2014

Insert Update Delete with createCommand in yii

public function assignVehicle($driver_id=null,$vehicle_id=null)
{
$sql = "UPDATE `drivers` SET `vehical_id`=$vehicle_id WHERE id=:driver_id";

$parameters = array(":driver_id"=>$driver_id);


Yii::app()->db->createCommand($sql)->execute($parameters);

}

public function insertCharges($area_id=null,$charge=null){



$sql = "insert into delivery_charge (`area_id`,`charge`) values (:area_id,:charge)";

$parameters = array(":area_id"=>$area_id,":charge"=>$charge);


Yii::app()->db->createCommand($sql)->execute($parameters);



}

$sql = "delete from `AuthItemChild` where parent=:parent AND child=:child";

  $parameters = array(":parent"=>$parent,":child"=>$child);


  Yii::app()->db->createCommand($sql)->execute($parameters);

Uploading image/file by creating a directory on the server in yii

^^^^ Form must have 'htmlOptions' => array(
        'enctype' => 'multipart/form-data',
    ),
^^^^^ model array('image', 'file', 'types'=>'jpg, gif, png','allowEmpty'=>true,'on'=>'update'),
^^^^^ Random name
$rnd = rand(0,9999);
$uploadedFile=CUploadedFile::getInstance($model,'image');
            $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name

            $model->image = $fileName;
$model->attributes=$_POST['Vehicle'];
$model->tax_document=CUploadedFile::getInstance($model,'tax_document');
$model->mot_document=CUploadedFile::getInstance($model,'mot_document');
$model->image=CUploadedFile::getInstance($model,'image');
$model->save();
if($model->save())

  $path="document/vechicle/";

if(!file_exists('document/vechicle/'.$model->id)){
mkdir('document/vechicle/'.$model->id, 0777,true);
chmod('document/vechicle/'.$model->id, 0777);
}
if ($model->tax_document){
$model->tax_document->saveAs('document/vechicle/'.$model->id.'/taxt'.$model->tax_document);
}
if ($model->mot_document){
$model->mot_document->saveAs('document/vechicle/'.$model->id.'/mot'.$model->mot_document);
}
if ($model->image){
$model->image->saveAs('document/vechicle/'.$model->id.'/img'.$model->image);

$this->redirect(array('view','id'=>$model->id));

Jul 7, 2014

Push data to GCM server

public function sentToGcm($id, $devid, $oid, $ost) {

$response["success"] = 1;
$devid = $devid;
$registatoin_ids = array($devid);
$msgall = $ost;

$msg = array("message" => $msgall, "o_id" => $oid, 'type' => 'order_st');
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $registatoin_ids, 'data' => $msg);
$headers = array('Authorization: key =AIzaSyD8E0T0h49MBYBST2aj_RuOCNxKReciCZA', 'Content-Type: application/json');

$data = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
//$ss = Yii::app()->curl->post($url, $data);

echo $result;
}

Update a table's specific column values with Yii

public function actionGetProf() {
try {
$user_id = $_POST['user_id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$street_address = $_POST['street_address'];
$floor = $_POST['floor'];
$city = $_POST['city'];
$apartent_name = $_POST['apartent_name'];
Profiles::model()->updateByPk($user_id, array(
'lastname' => $lastname,
'firstname' => $firstname,
'street_address' => $street_address,
'floor' => $floor,
'city' => $city,
'apartent_name' => $apartent_name,
));

$msg = CJSON::encode(array( array('success' => "success", 'message' => 'exception', 'user_id' => $Profiles)));
echo $msg;


} catch (Exception $exc) {
$msg = CJSON::encode(array( array('success' => "false", 'message' => 'exception')));
echo $msg;
}
}