Find us on facebook

Showing posts with label Yii. Show all posts
Showing posts with label Yii. Show all posts

Apr 27, 2015

Set default controller in yii1

config/main.php

'defaultController' => 'newcontrollername',

Or

framework/web/CWebApplication.php

public $defaultController

Sep 24, 2014

calling to a different action in yii form

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

?>

Aug 18, 2014

Get Unique values from an array

public function actionGetLunchCategory() {

$this -> layout = false;
header('Content-type: application/json');

$id = $_POST['id'];
$LunchMenus = MenuDiningtypes::model() -> findAll(array("condition" => "diningtypes_type_id =  $id"));

$LunchCategories = array();
foreach ($LunchMenus as $LunchMenu) {
$menu_id=$LunchMenu->menu_id;
$Menu = Menu::model() -> find(array("condition" => "id = $menu_id "));

$mainmenu_id=$Menu -> main_menu;

$MainMenu = MainMenu::model() -> find(array("condition" => "id = $mainmenu_id "));

$path = "/" . $MainMenu -> id . "/" . $MainMenu -> image;
$return_array = array('id' => $MainMenu -> id, 'name' => $MainMenu -> name, 'image' => $path, );
array_push($LunchCategories, $return_array);
}
$LunchCategories = array_unique($LunchCategories,SORT_REGULAR);
echo CJSON::encode($LunchCategories);
Yii::app() -> end();

}

Aug 12, 2014

Draggable Droppable for image positioning under various groups

View
  <?php
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/css/jquery-ui.js');
?>
 
  <?php
  Yii::app()->clientScript->registerCoreScript('jquery');
  $HotelAreas = HotelArea::model()->findAll();
foreach($HotelAreas as $HotelArea){
$Tables = Table::model()->findAll('is_active = 1 AND place='.$HotelArea->id);
foreach($Tables as $Table){
?>

  <script>
  $(function() {
left=0;
top=0;
    $("#<?php echo $Table->id?>").draggable();
$( "#droppable-<?php echo $HotelArea->id ?>").droppable({


      drop: function( event, ui ) {
       //alert(ui.draggable.prop('id'));
  event.stopPropagation();
var left = ui.position.left;
var dropPositionY = event.pageY - $(this).offset().top;
var dragItemOffsetY = event.offsetY;
var top =ui.position.top;
var droppableId = $(this).attr("id");
           $.ajax({
   
 url: "<?php echo Yii::app()->createAbsoluteUrl('Table/UpdatePosition');?>",
 type:"POST",
 data: "id="+ui.draggable.prop('id')+"&left=" + left+"&top=" + top+"&droppableId=" + droppableId,
 //dataType:"json",
 success: function(responce)

 {
 //alert(responce);

 }

});
           
      }
    });

  });
 
  </script>
  <?php
  }
  }
  ?>
<div class="span12">

<div class='fulid-row'>

<?php
$a_id = Yii::app() -> controller -> action -> id;
$c_id = Yii::app() -> controller -> id;
?>
<div id="content-box">
<div id="element-box">
<div id="system-message-container"></div>
<div class="">
<div class="adminform">

<?php $this->renderPartial('_left_menu'); ?>
<div class="span10">
<div class="headerContent">
<h3 style="padding: 5px;">Manage Tables</h3>
<!-- <h1 style="font-style: italic; margin: 25px 0px 0px -408px;">Manage Menu Items</h1> -->

</div>
<div class="space"></div>

</div>

<div class="span10" style="">
<div class="cpanel-right right-side">
<div style="margin-left: 20px;float: left;">
<?php
$HotelAreas = HotelArea::model()->findAll();
foreach($HotelAreas as $HotelArea){

$Tables = Table::model()->findAll('is_active = 1 AND place='.$HotelArea->id);


foreach($Tables as $Table){
$sql="SELECT image from table_type_images where table_type_id =".$Table->shape." AND chairs = ".$Table->chairs;
$TableTypeImage = TableTypeImages::model()->findBySql($sql);
if($Table->position==""|| $Table->position==Null){
$style="width:110px;margin-left: 20px;";
echo '<div id='.$Table->id.' style='.$style.'>';
}
elseif($Table->position!=""|| $Table->position!=Null){
$position=$Table->position;
$position=explode(",",$position);
$left=$position[0].'px';
$top=$position[1].'px';
$style="width:110px;left:$left;top:$top;";
echo '<div id='.$Table->id.' style='.$style.'>';
}
echo CHtml::image(Yii::app()->getBaseUrl().'/images/tables/'.$TableTypeImage->image, 'Tables[]');
echo '</div>';


}


}

?>
</div>
<div style="margin-left: 200px;">
<?php
$HotelAreas = HotelArea::model()->findAll();
foreach($HotelAreas as $HotelArea){

echo '<div id="droppable-'.$HotelArea->id.'" style="border: 3px solid #f90;border-radius: 1em;width:1000px;height:300px;">'.$HotelArea->name.
'</div>';

}
?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>


Controller
public function actionUpdatePosition(){
$left= $_POST['left'];
$top = $_POST['top'];
$id = $_POST['id'];
$droppableId = $_POST['droppableId'];
$droppableId=explode('-',$droppableId);
$Table = new Table;
$Table->updatePosition($left,$top,$id,$droppableId[1]);
//echo $top.",".$left;

}

Model
public function updatePosition($left=null,$top=null,$id=null,$droppableId=null)
{

$position =$left.",".$top;

$sql = "UPDATE `table` SET `position`='$position',`place`=$droppableId WHERE id=:id";

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

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

}

Aug 9, 2014

Draggable Droppable in yii

 <style>
 #droppable {
    width: 64em;
    height: 49em;
    padding: 0.5em;
    border: 3px solid #f90;
    border-radius: 1em;
    margin: 0 auto;
}</style>

  <?php
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/css/jquery-ui.js');
?>
 
  <?php
  Yii::app()->clientScript->registerCoreScript('jquery');
$Tables = Table::model()->findAll('is_active = 1');
foreach($Tables as $Table){
?>

  <script>
  $(function() {
left=0;
top=0;
    $("#<?php echo $Table->id?>").draggable();
$( "#droppable" ).droppable({


      drop: function( event, ui ) {
       //alert(ui.draggable.prop('id'));
  event.stopPropagation();
var left = ui.position.left;
var dropPositionY = event.pageY - $(this).offset().top;
var dragItemOffsetY = event.offsetY;
var top =ui.position.top;
//var top = event.offsetY;//
           $.ajax({
   
 url: "<?php echo Yii::app()->createAbsoluteUrl('Table/UpdatePosition');?>",
 type:"POST",
 data: "id="+ui.draggable.prop('id')+"&left=" + left+"&top=" + top,
 //dataType:"json",
 success: function(responce)

 {
 //alert(responce);

 }

});
           
      }
    });

  });
 
  </script>
  <?php
  }
  ?>
<div class="span12">

<div class='fulid-row'>

<?php
$a_id = Yii::app() -> controller -> action -> id;
$c_id = Yii::app() -> controller -> id;
?>
<div id="content-box">
<div id="element-box">
<div id="system-message-container"></div>
<div class="">
<div class="adminform">

<?php $this->renderPartial('_left_menu'); ?>
<div class="span10">
<div class="headerContent">
<h3 style="padding: 5px;">Manage Tables</h3>
<!-- <h1 style="font-style: italic; margin: 25px 0px 0px -408px;">Manage Menu Items</h1> -->

</div>
<div class="space"></div>

</div>

<div class="span10" style="">
<div class="cpanel-right right-side">
<div style="margin-left: 20px;float: left;">
<?php
$Tables = Table::model()->findAll('is_active = 1');


foreach($Tables as $Table){
if($Table->position==""|| $Table->position==Null){
$style="width:110px;margin-left: 20px;";
echo '<div id='.$Table->id.' style='.$style.'>';
}
elseif($Table->position!=""|| $Table->position!=Null){
$position=$Table->position;
$position=explode(",",$position);
$left=$position[0].'px';
$top=$position[1].'px';
$style="width:110px;left:$left;top:$top;";
echo '<div id='.$Table->id.' style='.$style.'>';
}
echo CHtml::image(Yii::app()->getBaseUrl().'/images/tables/'.$Table->image, 'Tables[]');
echo '</div>';


}

?>
</div>
<div style="margin-left: 200px;">

<div id="droppable"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

Controller
public function actionUpdatePosition(){
$left= $_POST['left'];
$top = $_POST['top'];
$id = $_POST['id'];
$Table = new Table;
$Table->updatePosition($left,$top,$id);
//echo $top.",".$left;
}
Model
public function updatePosition($left=null,$top=null,$id=null)
{

$position =$left.",".$top;

$sql = "UPDATE `table` SET `position`='$position' WHERE id=:id";

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

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

Aug 8, 2014

Yii: working with multiple tables

public function rules()
{
return array(array('item_id', 'safe', 'on'=>'search'),);
}

public function relations()
{
return array(
'items'           => array(self::BELONGS_TO, 'Menu','item_id'),
)
}
public function attributeLabels()
{
return array('item_id'=>'Item Id',);
}

$criteria=new CDbCriteria;
$criteria->together = true;
$criteria->with = array('items');
$criteria->compare('id',$this->id);
$criteria->compare('type',$this->type);
$criteria->compare('items.name',$this->item_id);

view file

 array(
'name'=>'item_id',
'value'=>'$data->items->name',
),

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 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

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;
}
}

Jun 25, 2014

Add a field that is not a table field into grid in YII

public $date;
public $time;
public $datetime;
public $order_type;

public function attributeLabels()
{
return array(
'datetime' =>'Delivery/Collection Date & Time',
'order_type' =>'Order Type',
etc...
); }

protected function afterFind() {
parent::afterFind();
//$delivery_date_new = strstr($this->delivery_date, '+', true);

if(strpos($this->delivery_date,'+') !== false){
$pieces = explode(" ", $this->delivery_date);
$timenew=explode(":", $pieces[1]);
$this->time=$timenew[0].":".$timenew[1];
$this->date = $pieces[0];
$this->datetime=$this->date." ".$this->time;
}else{
$this->time = $this->dilivery_time;
$this->date = $this->delivery_date;
$this->datetime=$this->delivery_date." ".$this->dilivery_time;
}
if ($this->delivery_type == 0)
{
$this->order_type = "Takeaway";
} elseif ($this->delivery_type == 1) {
$this->order_type = "Delivery";
} else {
$this->order_type = "Table";
}



return $this;
}

array_multisort

$sortArray = array();

foreach($displays as $display){
foreach($display as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}

$orderby = $groups[0];

array_multisort($sortArray[$orderby],SORT_DESC,$displays);
print_r($sortArray);exit;

Jun 6, 2014

Restore a large MySQL database using cmd in Windows machine

First open the cmd

Change the directory to mysql installed directory's bin. Mine is
D:/wamp/bin/mysql/mysql5.5.24/bin

D:/wamp/bin/mysql/mysql5.5.24/bin> mysql -u root -p

mysql> create database mydb;
mysql> use mydb;
mysql> source db_backup.sql;

For dump file
mysql> source db_backup.dump;

OR
First open the cmd

Change the directory to mysql installed directory's bin. Mine is
D:/wamp/bin/mysql/mysql5.5.24/bin

D:\wamp\bin\mysql\mysql5.5.24\bin>mysql -u root -p testing1 < D:\test2.sql

OR (For file type :File MySQL dump 10.13  Distrib 5.1.73, for redhat-linux-gnu (x86_64))
First open the cmd

Change the directory to mysql installed directory's bin. Mine is
D:/wamp/bin/mysql/mysql5.5.24/bin

D:\wamp\bin\mysql\mysql5.5.24\bin>mysql -u root testing1<test

Nov 1, 2013

Display horizontal check box list with CHtml::checkBoxList() in Yii

echo CHtml::checkBoxList(
string $name, 
mixed $select, 
array $data,
array('separator'=>'','template'=>'<div class=areas>{input}&nbsp;{label}</div>'));

Oct 12, 2013

Create a form with Yii (Part 2 - Declaring Validation Rules in Model Class)

When the user submit inputs we need to check whether the inputs are valid. For doing that we need to do validation. We can write code for validation rules inside rules() function which is located in Customer model class we created in Create a form with Yii (Part 1 - Define Model class). This function will return an array with rule configurations.

we should only define rules for the attributes that will receive user inputs.

public function rules() {
     
        return array(
            array('id, title_id, first_name, last_name, gender, dob, city, state, postal_code, phone, mobile_phone, email, marital_status', 'required'),
            array('title_id', 'numerical', 'integerOnly' => true),
            array('city, state, postal_code,mobile_phone, marital_status', 'length', 'max' => 20),
            array('first_name, last_name,email', 'length', 'max' => 50),
            array('gender', 'length', 'max' => 2),
            array('phone', 'length', 'max' => 30),
            array('email', 'email', 'checkMX' => true),
            array('dob', 'safe'),
            array('id, title_id, first_name, last_name,gender, dob,city, state, postal_code,phone, mobile_phone, email, marital_status', 'safe', 'on' => 'search'),
        );
    }

We will check the code line by line.

1)
array('id, title_id, first_name, last_name, gender, dob, city, state, postal_code, phone, mobile_phone, email, marital_status', 'required')
This code specifies that "id, title_id, first_name, last_name, gender, dob, city, state, postal_code, phone, mobile_phone, email, marital_status" these all attributes are required.

2)
array('title_id', 'numerical', 'integerOnly' => true)
This specifies that title_id is numerical and it's value must be integer.

3)
array('city, state, postal_code,mobile_phone, marital_status', 'length', 'max' => 20)
This code says that above mentioned attributes' maximum lenghth should be 20 characters.

4)
array('email', 'email', 'checkMX' => true)
checks if the email has a MX(mail exchanger record) registered

5)
array('dob', 'safe')
If a field has no particular data-format validations, we use 'safe' validator(This will be discussed clearly later).

4)
array('id, title_id, first_name, last_name,gender, dob,city, state, postal_code,phone, mobile_phone, email, marital_status', 'safe', 'on' => 'search')
In search scenario

Create a form with Yii (Part 1 - Define Model class)

Create a Customer model class used to collect user input. Here we use Active Record Model, Because we need to save user input into the database. 

Here we go.....

We define Customer model class as Active Record model class by extending CActiveRecord. Active Record model class represents a single database table. Here it is "customer" table. Active record instance represents a row in that table. Here it is one row(record) in customer table.

class Customer extends CActiveRecord {


    public static function model($className = __CLASS__) {

        return parent::model($className);
    }

    public function tableName() {

        return 'customer';
    } 
}

Normally Active Record class name is database table name. If you want to use different names for table and Active Record class you can override tableName() function as mentioned above.



Dealing with Forms in Yii

There are 3 major steps for dealing with forms.


  1. Create model class.
  2. Create a Controller action.
  3. Create form.
Create model class


There are two types of models.
  • Form Model - With this we can collect, use and discard user input. (Eg : Login form)
  • Active Record - With this we can collect user input and save them to the database.
Create a Controller action

Once model class is created, we should write code for the controller action to manipulate the model.

Create Form

Finally we create the form which contains HTML input fields. With Yii we can use helper classes to create forms.

Eg:  CHtml::textField() - we can call this to create text input field.
      CHtml::dropDownList() - we can call this to create drop down list.

Oct 2, 2013

CRUD operations with Yii

CRUD means create, read, update and delete.

Step 1: Turn on the php pdo extension to use database feature.

Step 2: Create connection to the database. I'm using MySQL.

To use MySQL uncomment the following code which is in     D:/wamp/www/testyii/protected/config/main.php

'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=testyii',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),

Step 3: Use Gii (Gii is a powerfull code generator)

To use Gii uncomment following code which is in D:/wamp/www/testyii/protected/config/main.php

'modules'=>array(

'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'testyii',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),

),
Here 'password'=>'testyii' you can set any password you like. I'm using "testyii" as my password.

Step 4: Access the URL http://localhost/testyii/index.php?r=gii



Step 5: Go to Model Genertor.

Give table name and Model Class as below. It will Generate model class for User.


Step 6: Then go to Crud Genertor.



Add Model class same as before. For me it is  "User". Controller ID will be user.

Step 7: Then access URL http://localhost/testyii/index.php?r=user
You can add users, update and delete users. Also you can view user list without writing a single code.


Oct 1, 2013

Start with Yii framework

What is Yii?

Yii is a fast,secure and professional MVC framework.

Start with Yii

Step 1: Download Yii from http://www.yiiframework.com/


Step 2: Unzip the package and put it in your web root. (www for WAMP or htdocs for XAMPP)

Now your Yii folder will be in www.

Step 3: Access Yii requirement checker with following URL
http://localhost/yii/requirements/


Step 4: Then create the skeleton

Open cmd and type,

C:\Users\hp>php
'php' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\hp>path D:\wamp\bin\php\php5.4.3

C:\Users\hp>php
^C
C:\Users\hp>cd D:\wamp\www

C:\Users\hp>d:

D:\wamp\www>php yii/framework/yiic.php webapp testyii
Create a Web application under 'D:\wamp\www\testyii'? (yes|no) [no]:yes

After you press enter it generates the application "testyii" under D:\wamp\www\testyii.

Finally says "Your application has been created successfully under D:\wamp\www\testyii"

Step 5: Now you can access your application through URL http://localhost/testyii