yii学习笔记

1、安装yii

2、创建站点:

D:\AppServ\www\yii\framework>d:/xampp/php/php.exe yiic webapp ../../ys2

Create a Web application under 'D:\AppServ\www\ys2'? (yes|no) [no]:yes

 

 

 

1、创建控制器:在protected 下面的controller中创建名为IndexController.php的文件:

<?php

       class IndexController extends Controller

       {

             

              public function actionIndex()

              {

                     echo "For test";     

              }    

       }

?>

 

2、修改默认的site控制器为Index控制器,在protected/config/main.php中添加:'defaultController'=>'Index',例如:

// autoloading model and component classes

       'import'=>array(

              'application.models.*',

              'application.components.*',

       ),

       'defaultController'=>'Index',

       'modules'=>array(

              // uncomment the following to enable the Gii tool

3、载入视图的两种方法,在控制器中添加:

       $this->render('index');//载入默认布局

       $this->renderPartial('index');//不载入默认布局,当然jquery就也不能用了

 

       载入的时候在view文件夹下的index 文件夹中必须有相应文件例如index.php

       里面的内如可以随意些,例如:

       <?php

       echo 'This is a test';

?>

 

       需要注意的是render或者renderPartial后面的括号中传递什么名字,那么在view文件夹下也要有同样名字的.php文件

       例如我在控制器中用

                            $this->render("admin");

       那么在view文件夹下也要有 admin.php才行。

 

4、用到的外部的js,css,img 等图片需要放到asserts文件夹下,如果有前台和后台的区分,那么需要再在asserts文件夹下建文件夹比如

       index,admin 一个是前台,一个是后台

 

       调用的时候需要在相应的view中加入<?php echo Yii::app()->reuest->baseUrl;?>

       例如原来用的是<link href="./css/css" /> 那么改后应该是

       <link href="<?php echo Yii::app()->reuest->baseUrl;?>/asserts/index/css/index.css" />

 

5、给视图分配数据:控制器中:

       public function actionIndex()

       {

              $data = array(

                     "title"=>"wzy test",

                     );

              $this->render("index",$data);

       }

       在视图index.php中可以直接

       <?php echo $title;?>

6、引入自定义函数:

       自定义函数应写在protected目录下,比如function.php

       <?php

       function p($str)

       {

              var_dump($str);

       }

?>

       那么在protected同级目录的index.php中加入 include_once(dirname(__FILE__)."/protected/function.php");

       这个时候在控制器中我们就可以用了。例如:

      

 

       public function actionAdmin()

              {

                     $data = array(

                            'title'=>"wzy test",

                     );

                     p($data);

                     $this->render('admin',$data);

                    

              }

 

       访问 http://localhost/youshi/index.php?r=index/admin  就能看到结果了

7、header,footer的添加

       在文件夹protected/view/layout 创建文件company.php,内容如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>wzy test </title>

</head>

 

<body>

<table width="100%" border="0" cellspacing="0" cellpadding="1">

  <tr>

    <th bgcolor="#0099CC" scope="col">&nbsp;</th>

  </tr>

  <tr>

    <th scope="row">

<!-- 以上是头部--->

<!-------下面是页面内容---->

<?php echo $content;?>

 

<!------以下是尾部------>

</th>

  </tr>

  <tr>

    <th bgcolor="#6699FF" scope="row">&nbsp;</th>

  </tr>

</table>

</body>

</html>

      

 

然后打开 protected/components/controller.php 修改public $layout='//layouts/column1'; 为 public $layout='//layouts/company'; 即可

 

 

 

8、添加新的控制器文件夹,为了后台和前台的控制器分开,就添加modules

首先打开protected/config/main.php 找到gii modules,去掉注释,修改密码。

然后在浏览器里输入:http://localhost/youshi/index.php?r=gii/module/index

输入刚才的密码进入,点选Module Generator,输入Module ID 为admin(也可以是其他的,随意命名)

预览生成,即可,这个时候在浏览器里输入http://localhost/youshi/index.php?r=admin

还不能访问,需要在protected/config/main.php 的gii下面加入"admin"才行:

 

'modules'=>array(

              // uncomment the following to enable the Gii tool

             

              'gii'=>array(

                     'class'=>'system.gii.GiiModule',

                     'password'=>'12345',

                     // If removed, Gii defaults to localhost only. Edit carefully to taste.

                     'ipFilters'=>array('127.0.0.1','::1'),

              ),

              'admin'

             

       ),

 

 

 

9、表单创建

<?php $form = $this->beginWidget('CActiveForm');?>

<?php echo $form->textField(模型,‘表单名’,html属性);?>

 

这里模型需要创建,在文件夹/protectd/model/下面

比如创建一个AddType.php 里面内容是:

class AddType extends CFormModel

{

       public $bigtype;

       public $smalltype;

      

       public function rules()

       {

              return array(

                     // username and password are required

                     array('username, password', 'required'),

                     array('bigtype,smalltype','required'),

                     // rememberMe needs to be a boolean

                     array('rememberMe', 'boolean'),

                     // password needs to be authenticated

                     array('password', 'authenticate'),

              );

       }

 

}

 

然后 在在相应的控制器中的相应页面TypeContrloller 中加入:

       public function actionIndex()//这里是一个页面

       {

             

              $this->renderPartial('index');

       }

       public function actionAddtype()//这里是另外一个页面

       {

              $addType = new AddType();

              ///下面是接收数据库,这里需要注意的是在AddType.php的public function rules() 这个函数中要加上指定的rule,才能接收数据,否则就过滤掉了

              if(isset($_POST['AddType']))

              {

                     $addType->attributes = $_POST['AddType'];

                    

                     var_dump($addType->showValues());

              }

             

              ////end

              $this->render('addtype',array('addType' => $addType));     

       }

<?php echo $form->textField($addType,"bigtype",array("class"=>"f1"))?> 表示添加一个名为bigtype,class 为f1的文本框

这里文本框的名称必须在addtype.php这个类中必须先定义好才行,不然会出错的。

<?php echo CHtml::submitButton('Login'); ?>

<?php $this->endWidget();?>

 

 

由于没有模型,就创建一个。在protected/models,下面有个loginForm。我们可以在DefaultController中使用

public function actionIndex()

{

       $loginForm = new LoginForm;

       $this->renderPartial('index',array('loginForm'=>$loginForm));

 

}

 

 

在index.php中就可以 用下面的代码调用

<?php echo $form->textField($loginForm,'username',array('id'=>'username',"class"=>"itxt"));?>

 

 

 

如果后台也需要单独的layouts,那么就需要在D:\AppServ\www\ys2\protected\modules\admin 下面也需要一个文件夹,

可以复制D:\AppServ\www\ys2\protected\components 这个文件夹,

这个文件夹中要有一个Controller.php ,修改里面的layout,这里需要注意 public $layout = "/layouts/admin"; 这里的layouts前面只有一个斜线

相应的在文件夹D:\AppServ\www\ys2\protected\modules\admin\views 也建一个文件夹叫layouts 并建立相应的layouts

 

 

 

下面的这些配置可以在D:\AppServ\www\yii\framework\db/CDbConnection.php 中找到

'db'=>array(

                     'connectionString' => 'mysql:host=localhost;dbname=tisfa',//注意这里如果是linux或者苹果系统,可能需要将localhost 改为127.0.0.1

                     'emulatePrepare' => true,

                     'username' => 'root',

                     'password' => 'qweasd',

                     'charset' => 'utf8',

                    

                     'tablePrefix'=>'fa_',//这里是给表加前缀

                     'enableParamLogging' => true,//这里是开启调试

              )

      

      

              测试数据库链接: var_dump(Yii::app()->db);

             

一个数据表一个模型,就是model

 

比如在protected/models/下面定义:

user.php

内容:必须要两个方法,model,tableName

父类是:CActiveRecord ,这个类保护,增删,改查等功能

 

class User extends CActiveRecord{

       /**

        *必不可少方法1

        *

        */

        public static function model($className = __CLASS__){

              return parent::model($className);

        }

        public function tableName(){

              return ""{{pname}};//注意,这里是不需要表前缀的,因为前面已经定义过了

        }

}

 

或者type.php

<?

       class Type extends CActiveRecord{

             

             

              public static function model($className = __CLASS__ ){

                     return parent::model($className);

              }

              public function tableName(){

                     return "{{pname}}";     

              }

                    

       }

?>

 

 

然后在TypeController.php 中加入:

public function actionAddtype()

       {

              $addType = new AddType();

              if(isset($_POST['AddType']))

              {

                     $addType->attributes = $_POST['AddType'];

                    

              }

              $pname = Type::model()->find('id=:sid',array(':sid'=>'1')); //这里就是取数据库信息的。

              //这里的Type就是我们上面写的type.php。 id 是字段名字,sid 相当于一个变量名字。

              //find 表示查找一条记录

              var_dump($pname->ctype);

              $this->render('addtype',array('addType' => $addType));     

       }

 

      

      

       public function actionAddtype()

       {

              $addType = new AddType();

              if(isset($_POST['AddType']))

              {

                     $addType->attributes = $_POST['AddType'];

                    

              }

             

              if($addType->validate())//这里是验证为空的。

              {

                    

                     }

              //$pname = Type::model()->find('id=:sid',array(':sid'=>'1'));

              //var_dump($pname->ctype);

              $this->render('addtype',array('addType' => $addType));     

       }

      

       在view页面里这样写:

        <td><?php echo $form->error($addType,"bigtype")?></td>

        

        在模型的addType.php rule里这样写

        

        public function rules()

       {

              return array(

                     // username and password are required

                     //array('username, password', 'required'),

                     array('bigtype','required','message'=>"请填写类型"),

                     // rememberMe needs to be a boolean

                     //array('rememberMe', 'boolean'),

                     // password needs to be authenticated

                     //array('password', 'authenticate'),

              );

       }

             

             

       到目前为止有两模型,一个是form的模型,一个是增删改查的模型

      

      

      

      

       ***********验证码的产生与应用***********************************************************************

       在控制器中TypeController.php中加入:

       public function actions()

       {

              return array(

                     'captcha' => array(

                     'class' => 'CCaptchaAction',//或者:system.web.widgets.captcha.CCaptchaAction

                     'height' => 25,

                     'width' => 80,

                     'minLength' => 5,

                     'maxLength' => 5

                     ),

              );    

       }

      

       在视图中调用:

        <?php

    $this->widget('CCaptcha',array('showRefreshButton'=>false,'clickableImage'=>true,'imageOptions'=>

       array('alt'=>'点击换图','title'=>'点击刷新','style'=>'cursor:pointer')));

       ?>

      

       这个时候点击图片可以刷新显示,如果刷新没有执行,那么需要改控制器中的renderPartial 为render

      

       这个时候,直接刷新页面,字母还是没有刷新,那么需要修改文件:

       在framework/web/widgets/captcha/CCaptchaAction.php 中run 方法的

       $this->renderImage($this->getVerifyCode()); 改为:$this->renderImage($this->getVerifyCode(true));

      

       验证码的验证是在model的rules 方法里

       public function rules()

       {

              return array(

                     // username and password are required

                     //array('username, password', 'required'),

                     array('bigtype','required','message'=>"请填写类型"),

                     array('code','captcha','message'=>'验证码错误'),

                     // rememberMe needs to be a boolean

                     //array('rememberMe', 'boolean'),

                     // password needs to be authenticated

                     //array('password', 'authenticate'),

              );

       }

      

       验证码的验证既: array('name值','captcha',错误信息);

      

      

       **********************************************************************************

      

      

       在做登录的时候文本框的名字必须是“username” 和“password”,不然则需要修改yii/framework/web/auth 下面的CUserIdentity.php中的定义

       登录的话,需要:

       view页面:

       <?php echo $form->textField($addType,"username",array("class"=>"f1"))?>

    <?php echo $form->textField($addType,"password",array("class"=>"f2"))?>

      

       model页面加user.php,用来读取数据库信息:

       <?

       class User extends CActiveRecord

       {

              public static function model($className = __CLASS__)

              {

                     return parent::model($className);

              }

              public function tableName()

              {

                     return "{{guser}}";

              }

             

             

       }

?>

 controller.php 中:

 if($addType->validate()&& $addType->login())

              {

                     echo '1';

              }

             

addtype 页面,就是处理form表单的页面:

public function rules()

       {

              return array(

                     // username and password are required

                     //array('username, password', 'required'),

                     array('username','required','message'=>"请填写类型"),

                     array('code','captcha','message'=>'验证码错误'),

                     array('password', 'authenticate'), //这里的authenticate 是调用这个方法

                     // rememberMe needs to be a boolean

                     //array('rememberMe', 'boolean'),

                     // password needs to be authenticated

                     //array('password', 'authenticate'),

              );

       }

      

      

       public function authenticate($attribute,$params)

       {

              if(!$this->hasErrors())

              {

                     //$this->_identity=new UserIdentity($this->username,$this->password);

                    

                     $this->_identity = new TypeIdentity($this->username,$this->password);

                    

                     if(!$this->_identity->authenticate())

                            $this->addError('password','用户名或密码不正确');

              }

       }

      

      

       public function login()

       {

              if($this->_identity===null)

              {

                     $this->_identity=new TypeIdentity($this->username,$this->password);

                     $this->_identity->authenticate();

              }

              if($this->_identity->errorCode===TypeIdentity::ERROR_NONE)

              {

                     $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

                     Yii::app()->user->login($this->_identity,$duration);

                     return true;

              }

              else

                     return false;

       }

      

在protected/components下面加一个验证的页面:TypeIdentity.php 内如如下:

 

<?

       class TypeIdentity extends CUserIdentity{

              //public $bigtype;

             

              public function authenticate()

              {

                    

                     $userInfo = User::model()->find('cname=:cname',array(':cname'=> $this->username));

                    

                     if($userInfo == NULL)

                     {

                            $this->errorCode = self::ERROR_USERNAME_INVALID;

                            return false;   

                     }

                     if($userInfo->ad4 !== $this->password)

                     {

                            $this->errorCode = self::ERROR_PASSWORD_INVALID;

                            return false;

                     }

                    

                     $this->errorCode = self::ERROR_NONE;//这里注意,一定要写,不然登陆不成功

                     return true;

              }

       }

?>

 

取登陆后的用户名: Yii::app()->user->name;

为了区分开前后台同时登陆时用户名混淆,需要在: modules/admin/AdminModule.php 中的init函数中:

public function init()

       {

              // this method is called when the module is being created

              // you may place code here to customize the module or the application

 

              // import the module-level models and components

              $this->setImport(array(

                     'admin.models.*',

                     'admin.components.*',

              ));

             

              /////加上下面的部分,可以使前后台的登录名不混淆

              Yii::app()->setComponents(

              array(

                     'user' => array('stateKeyPrefix'=>'admin'),

              )

              );

       }    

      

       登出方法:

       public function actionOut()

              {

                     Yii::app()->user->logout();   

              }

             

      

       链接跳转:

       $this->redirect(array('控制器/方法'));

       如果是同一个控制器,那么可以写成$this->redirect(array('方法'));

       $this->redirect(array('default/index'));

      

       view里面调用链接:

       $this->createUrl('控制器/方法',get参数组);

      

       $this->createUrl('article/index',array('aid'=>3));

      

       session的使用:

       存储:Yii::app()->session['logintime'] = time();

       调用: Yii::app()->session['logintime'];

       清除: Yii::app()->session->clear();

                 Yii::app()->session->destroy();

       客户端IP: Yii:app()->request->userHostAddress;

      

      

       标签的写法:

       在模型中写:

       public function attributeLabels(){

              return array(

              'passwd' => "Please input password";

              );

       }

       调用的时候用: $form->labelEx($userModel,'password'); 这个后面会显示一个* 号。

                                   $form->label($userModel,'password'); 不显示 * 号

       由于数据库中不存在,新密码,和确认密码,这个时候需要定义属性

      

       rules中的确认密码相同

      

      

       public function rules()

              {

                     return array(

                            array('username', 'required','message'=>'Please input username'),

                            array('password', 'required','message'=>'Please input password'),

                            array('password','checkPwd'),//调用自定义方法

                            array('newpwd1','required','message'=>'Please input pwd'),

                            array('newpwd2','required','message'=>'Please input pwd'),

                            array('newpwd2','compare','compareAttribute'=>'newpwd1','message'=>'Two pwd is not the same'),

                     );

              }

             

              public function checkPwd()

              {

                     $user = $this->find("uname=:uname",array(":uname"=>Yii::app()->user->name));

                     if(md5($this->password) != $user->pwd)

                     {

                            $this->addError('password','pwd is wrong');       

                     }

              }

             

开启前台js 验证:

必须用render

<?php $form = $this->beginWidget('CActiveForm',array(

       'id'=>'form id',//开启js 验证,不需要这个

       'enableClientValidation' => true,

       'clientOptions'=>array(

              'validateOnSubmit'=>true,

       ),

)); ?>

 

 

按主键修改记录:

if($userModel->validate())

                     {

                            $userinfo = $userModel->find("uname=:uname",array(":uname"=>Yii::app()->user->name));

                            $password = md5($userModel->newpwd2);

                            if($userModel->updateByPK($userinfo->id,array('pwd'=>$password)))

                            {    

                                   Yii::app()->user->setFlash("pwdsucsess","password modify success");

                            }

                            else {

                                   Yii::app()->user->setFlash("pwdsucsess","password modify failed");

                            }

                     }

                    

       当修改成功后:在前台显示成功信息:在view中显示:面的语句要在form中间,放在form外面是不显示的

       <?php

       if(Yii::app()->user->hasFlash('pwdsucsess'))

              echo Yii::app()->user->getFlash('pwdsucsess');

?>

 

///下面一段可以使显示的消息在指定时间内消失

<?php

       if(Yii::app()->user->hasFlash('linksuccess'))

              echo '<div id="abc">'.Yii::app()->user->getFlash('linksuccess').'</div>';

             

       Yii::app()->clientScript->registerScript(

              'mhHideEffect',

              '$("#abc").animate({opacity:1.0},3000).fadeOut("slow");',

              CClientScript::POS_READY

       );

?>

 

 

日志信息:

在protected/config/main 里面的 log里面的,把下面的注释去掉即可

 

array(

                                   'class'=>'CWebLogRoute',

                            ),

                           

但是这个在正式环境是要去掉的。只供开发的时候调试用的。不然会出现很多调试信息的

 

 

 

增加的时候:控制器:

public function actionAdd()

              {

                     $ctModel = new Category;

                     if(isset($_POST['Category']))

                     {

                            $ctModel -> attributes = $_POST['Category'];

                           

                            var_dump($_POST);    

                            $ctModel -> save();

                     }

                     $this->render('add',array('ctModel'=>$ctModel));

              }

             

model里面: 请注意字段的名字对应

 

       <?php

       class Category extends CActiveRecord

       {

              public $cname;

              public static function model($className = __CLASS__)

              {

                     return parent::model($className);

              }

              public function tableName()

              {

                     return "{{category}}";  

              }

              public function rules()

              {

                     return array(

                            array('cname,ctitle','safe'),

                     );    

              }

       }

?>

 

 

查询:

查询单条记录:find('username=:name',array(":name"=>username))

通过主键查询 findByPk():findByPk(1)

通过sql语句查询出一条:findBySql():findBySql("SELECT * FROM{{admin}}");

 

查询多条:findAll()

findAll('color=:color',array(':color'=>'red'));

 

findAllByPk() 通过主键查询多条

findAllByPk(array(1,2))

 

通过sql语句查询多条

findAllBysql

findAllBysql("SELECT * FROM {{admin}}");

 

 

控制器:public function actionIndex()

              {

                     $ctModel = Category::model();

                     $sql = "SELECT id,cname FROM {{category}}";

                     $info = $ctModel -> findAllBysql($sql);

                     //var_dump($info);

                     $this->render('index',array('ctInfo'=>$info));

              }    

             

       试图:

      

<?php foreach($ctInfo as $v) {?>

<p><?php echo $v->id;?></p>

<p><?php echo $v->cname;?></p>

<p><a href="<?php echo $this->createUrl('edit',array('id'=>$v->id));?>">Edit</a></p>

<?php } ?>

 

 

 

编辑的话,直接用与add同样的view

 

然后控制器:

public function actionEdit($id)

              {

                     $ctModel = Category::model();

                     $info = $ctModel->findByPk($id);

                    

                     if(isset($_POST['Category']))

                     {

                            $info -> attributes = $_POST['Category'];   

                            $info->save();

                     }

                    

                     $this->render('edit',array('ctModel'=>$info));

              }

 

      

      

      

       删除:

      

       public function actionDel($id)

              {

                     Category::Model()->deleteByPk($id);

              }

             

             

百度编辑器:

可以放在assets的admin文件夹下面

载入两个js文件:  ueditor.all.min.js 和ueditor.config.js

配置项:

<script>

window.UEDITOR_HOME_URL = “”;//js的home路径

window.onload = function (){

window.UEDITOR.initialFrameHeight = 900;

window.UEDITOR.initialFrameWidth = 900;

UE.getEditor('content');

}

</script>

 

form的其他信息

允许上传的表单

<?php $form = $this->beginWidget('CActiveForm',array('htmlOptions'=>array('enctype'=>'multipart/form-data')));?>

单选框radio

<?

echo $form->readioButtonList($articleModel,'type',array(0=>'普通',1=>'热门'),array('separator'=>'$nbap;')); //最后一个参数是分割符号,可以试试默认是BR就是换行

?>

 

 

下拉框select

在控制器中,

       $category = Category::model();

       $categoryInfo = $categor->findAllBysql('SELECT cid,cname FROM {{category}}');

       $cateArr = array();

       $cateArr[] = "Select";

      

       foreach($categoryInfo as $v)

       {

              $cateArr[$v->cid] = $v->cname;

       }

       $data = array(

              'articleModel'=>$articleModel,

              'cateArr' => $cateArr,

       );

       $this->render('add',$data);

 

视图中:

              echo $form->dropDownList($articleModel,'cid',$cateArr);

      

上传控件file

echo $form->fileField(articleModel,'fileid');

 

文本域textarea

 

echo $form->textArea($article,'areaid',array('cols'=>50,'rows'=>10,'maxlength'=>100));

 

 

rule 中的in的使用,就是判断select的时候用

比如array('type','in','range'=>array(0,1),'message'=>'请选择是0还是1')

 

缩略图

array('thumb','file','type'=>'jpg,gif,png,bmp','message'=>'没有上传或者类型不对');

 

上传类

$articleModel->thumb = CUploadedFile::getInstance($articleModel,'thumb');

if($articleModel->thumb)

{

       $preRand = 'img_'.time().mt_rand(0,999);

       $imgName = $preRand.'.'.$articleModel->thumb->extensionName;

       $articleModel->thumb->saveAs('uploads/'.$imgName);

       $articleModel->thumb = $imgName;

      

      

       //缩略图类,

      

       $path = dirname(Yii::app()->BasePath).'/uploads/';

       $thumb = Yii::app()->thumb;注意这里的thumb是在main里面配置的那个key

       $thumb->image = $path.$imgName;

       $thumb->width = 130;

       $thumb->height = 95;

       $thumb->mode = 4;//只缩放不裁剪

       $thumb->director = $path;//存放路径

      

       $thumb->defaultName = $preRand;//加上这句,表示不保留原图

      

       $thumb->createThumb();

       $thumb->save();

      

}

 

 

裁剪,缩略图类,在main里面设置(第三方类)

在protected 下面extensions中建立CThumb/CThumb.php

在main.php中配置,找到

‘components’=>array(

'user'=>array(

'allowAutoLogin'=>true,

),

'thumb'=>array(

'class'=>'ext.CThumb.CTumb'

),

)

 

取旧图: $model->thumb;

 

使用请看上面

 

 

分页类:

$criteria = new CDbCriteria();//AR的另一种写法

$criteria->order = ‘id asc’;

$model = Model::model();

$total = $model->count($criteria);//统计总条数

$pager = new Cpagination($total);

$pager->pagerSize = 3;

$pager->applyLimit($criteria);//进行limit截取

$info = $model->findAll($criteria);

$data = array(‘info’=>$info,’pages’=>$pager);

$this->render(‘index’,$data);

 

 

 

视图页

<div>

<?

$this->widget(‘CLinkPager’,array(

‘header’=>’’,

‘firstPageLabel’=>’首页’,

‘lastPageLabel’=>’末页’,

‘prevPageLabel’=>’上一页’,

‘nextPageLabel’=>’下一页’,

‘pages’=>$pages,

‘maxButtonCount’=>5

));

?>

</div>

 

 

 

 

 

 

 

 

 

 

代码示例:

public function actionIndex()

              {

                     $ctModel = Category::model();

                    

                     $cri = new CDbCriteria();

                     $total = $ctModel->count($cri);

                     $cri->order = ‘id asc’;

                    

                     $pager = new CPagination($total);

                     $pager->pageSize = 3;

                     $pager->applyLimit($cri);

                    

                     $info = $ctModel->findAll($cri);

                    

                    

                    

                     //$sql = "SELECT id,cname FROM {{category}}";

                     //$info = $ctModel -> findAllBysql($sql);

                     //var_dump($info);

                     $this->render('index',array('ctInfo'=>$info,'pages'=>$pager));   

              }    

 

Yii::app()->db->createCommand('select * from user orderbay id DESC')->queryAll();  万能方法  绝对块

 

 

视图中

<div class='page'>

<?

       $this->widget('CLinkPager',array(

              'header'=>'',

              'firstPageLabel' => 'First',

              'lastPageLabel'  => 'Last',

              'prevPageLabel'  => 'Prev',

              'nextPageLabel'  => 'Next',

              'pages'                   => $pages,

       ));

?>

 

 

 

 

 

 

 

下面是允许登陆用户访问的方法:每个控制器都要有一份

规则是从上到下,@ 表示所有登陆用户 * 代表所有未登录用户,注意顺序

@ 也可以直接写用户名

 

 

未登录用户的访问跳转,需修改main.php中的内容

 

 

 

 

 

下面表示index方法不需要验证

 

 

 

 

 

 

 

 

 

配置默认登陆

 

 

 

 

 

 

  1. //添加  
  2. Yii::app()->db->createCommand()->insert('tbl_user',   
  3. array(  
  4.     'username' => 'zhangsan',   
  5.     'email' => 'zhangsan@zs.com'));  
  6. //修改  
  7. Yii::app()->db->createCommand()->update('tbl_user',   
  8. array(  
  9.     'username' => 'Tester'), 'id=:id', array(  
  10. 10.     ':id' => 3));  

11. //删除     

12. Yii::app()->db->createCommand()->delete('tbl_user', 'id=:id',   

13. array(  

  1. 14.     ':id' => 2));  

15. //查询  

16. $users = Yii::app()->db->createCommand()  

  1. 17.     ->select('*')  
  2. 18.     ->from('tbl_user')  
  3. 19.     ->queryAll();  

20. var_dump($users);  

 

 

3: 通过query方法

[plain] view plaincopy

  1. $sql = "SELECT COUNT(*) as clients FROM client_table";  
  2. $command = Yii::app()->db->createCommand($sql);  
  3. $results = $command->queryAll();  
  4. $numClients = (int)$results[0]["clients"];  


通过queryScalar可以让上面的语句更简单:

[plain] view plaincopy

  1. $sql = "SELECT COUNT(*) FROM client_table";  
  2. $numClients = Yii::app()->db->createCommand($sql)->queryScalar();

 

 

 

array('username, password', 'required','message'=>'{attribute}不能为空')

 

 

 

radio onlclick:

echo CHtml::activeRadioButtonList($product, 'product_id',
              $product_list,
              array('separator'=>' ', 'labelOptions'=>array('style'=>'display:inline'),
                  'onclick' => 'this.form.submit()'
               ));

 

 

 

载入jquery 框架

<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
载入CSS

Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/test.css');

 

 

定义全局变量:

 

In Yii, you can do achieve this by making a class (under protected/compoents) which inherits

CApplicationComponent

class. And then you call any property of this class globally as a component.

class GlobalDef extends CApplicationComponent {
 public $aglobalvar;
}

Define this class in main config under components as:

'globaldef' => array('class' => 'application.components.GlobalDef '),

And you can call like this:

echo Yii::app()->globaldef->aglobalvar;

Hope that can help.

 

 

删除连接带确认:

echo CHtml::link(Yii::t('cmp','Delete'),'javascript:',array('onclick'=>'return chkDelete(\''.Yii::app()->createUrl('admin/Link/delete',array('lid'=>$v->id)).'\')'))

 

 

调用js alert 并转向:

Yii::app()->clientScript->registerScript('my_script','alert("Success");window.location.href="'.Yii::app()->createUrl("admin/link/index").'";',CClientScript::POS_READY);

 

 

分页排序:

$info       = $gda->findAll(array('order'=>'type asc'),$cri);

 

返回上一页:$this->redirect( Yii::app()->request->getUrlReferrer());

 

 

Ajax 验证:

 

控制器:

public function actionAdd()

              {

                     $gda = new Gda;

                    

                     if(isset($_POST['Gda']))

                     {

                            $gda->attributes = $_POST['Gda'];     

                           

                            if(isset($_POST['ajax'])&&$_POST['ajax'] === 'gda-form')

                            {

                                   echo CActiveForm::validate($gda);

                                   Yii::app()->end();

                            }

                           

                            if($gda->validate())

                            {

                                   $exists = Gda::model()->exists('type=:type and name=:name',array(':type'=>$gda->type,':name'=>$gda->name));

                                   if($exists)

                                   {

                                          jsRedirect('Type : '.$gda->type.', name : '.$gda->name.' exists!',-1);

                                          Yii::app()->end();

                                   }

                                   if($gda->save())    

                                          jsRedirect('Add Successed!',Yii::app()->createUrl('admin/gda/'));

                                   else

                                          jsRedirect('Add Failed!',-1);

                                         

                            }

                     }

                    

                     $this->render('modify',array('info'=>$gda,'type'=>Yii::app()->vars->constantGdaType));               

              }

 

模型:

 

public function rules()

              {

                     return array(

                            array('type','required','message'=>'Type can\'t be null'),

                            array('name','required','message'=>'Name can\'t bu null'),

                            array('name','chkUnique','message'=>'abcde'),

                            array('comments','safe'),

                     );    

              }

              public function chkUnique()

              {

                            $old = GDA::model()->find('type=:type and name=:name',array(':type'=>$this->type,':name'=>$this->name));

                            if($old != NULL)

                                   $this->addError('name','Sorry Type: '.$this->type.', Name: '.$this->name.' is exists');

              }

 

视图:

 

 

<?php $form = $this->beginWidget('CActiveForm',array(

'id'=>'gda-form',

'enableAjaxValidation'=>true,

'enableClientValidation' => true,

'clientOptions' => array(

       'validateOnSubmit' => true,

),

));?>

 

 

下拉框值和文本显示一致

<?php echo $form->dropDownList($info,'rating',array_combine($rating,$rating));?>

 

 

 

 

多对多,与一对多关系:

 

模型中

       class Movie extends CActiveRecord

       {

              public static function model($className = __CLASS__)   

              {

                     return parent::model($className);      

              }

             

              public function tableName()

              {

                     return "{{detail}}";      

              }

             

              public function relations()

              {

                     return array(

                            'detail' => array(self::MANY_MANY,'actor','{{type}}(did,aid)'),

//其中,actor,是另一个模型的名字,type,是关联表的名字,did 是detail表的id,aid是actor表的id

                            'mmtype'  => array(self::BELONGS_TO,'movietype','mtype'),

//这里的key,不能和detail表中的字段名字相同,不然数据出不来。

//monvietype 是另一个模型的名字,mtype是detail表中的那个字段来自于movietype表

                     );    

              }

       }

 

 

控制器中:

public function actionIndex()

              {

                     $model = Movie::model();

                     $info = $model->findAll();

                    

                     $data = array('info'=>$info);

                     $this->render('index',$data); 

              }    

 

 

视图中:

<?php foreach($info as $v):?>

  <tr bgcolor="#FFFFFF">

    <td><?php echo $v->cname;?></td>

    <td><?php

       foreach ($v['detail'] as $vv)

              {

                     echo $vv->actor.'['.$vv->id.'],';     

              }

             

       ?></td>

    <td><?php echo $v->info?></td>

    <td><?php echo $v->id;?></td>

    <td><?php echo $v['mmtype']->mtype;

      

       ?></td>

  </tr>

  <?php endforeach;?>

 

给按钮添加js 函数:

<?php echo CHtml::button('>>>',array('title'=>'To Right','onclick'=>'toRight()'));?>

 

 

Select multi

 

<?php echo $form->ListBox($model,'skillid',array('id'=>'Select Skill', 'multiple' => 'multiple')); 

 

 

 

 

下面是多行插入:其中title,和text是字段名字

$builder=Yii::app()->db->schema->commandBuilder;
$command=$builder->createMultipleInsertCommand('tbl_post', array(
  array('title' => 'record 1', 'text' => 'text1'),
  array('title' => 'record 2', 'text' => 'text2'),
));
$command->execute();

 

 

 

Ajax 赋值select值

 

视图:

echo $form->dropDownList($mRmd,'place',$place,array(

              'id'   => 'place',

              'ajax'       => array(

                     'type'       => 'POST',

                     'url'  => Yii::app()->createUrl('admin/recommand/getType'),

                     'update'   => '#type',

                     'data'              => array('place_name'=>'js:$("#place").val()'),

              ),

       ));

 

echo $form->dropDownList($mRmd,'type',array(''=>'Select'),array('id'=>'type'));

 

控制器:

public function actionGetType()

              {

                     $str = '';

                     $subPlace = Yii::app()->vars->constantType[$_POST['place_name']];

                     foreach($subPlace as $v)

                     {

                            $str .= CHtml::tag('option',array('value'=>$v),$v,true);

                     }

                    

                     echo $str;

              }

 

——————————————————————————————————————

参考资料:

视图:

cdnauto/views/config/index.php

[php] view plaincopy

  1. echo CHtml::dropDownList('node', '', CHtml::listData(Node::model()->findAll(),'name','name'),array('empty'=>'--请选择节点--',  
  2.         'id' => 'node',  
  3.         'ajax'=>array(  
  4.             'type'=>'POST',  
  5.             'url'=>Yii::app()->createUrl('cdnauto/config/getNodeServersByNodeName'),  
  6.             'update'=>'#servers',  
  7.             'data'=>array('node_name'=>'js:$("#node").val()'),  
  8.         )  
  9.     )         

10. );          

11. echo "        ";  

12. echo CHtml::dropDownList('servers', '', array('--请选择服务器--'));  



 

 

控制器:

cdnauto/controllers/ConfigController.php

[php] view plaincopy

  1. public function actionGetNodeServersByNodeName(){  
  2.   //    if(!Yii::app()->request->isAjaxRequest)  
  3.   //      throw new CHttpException(404);  
  4.     $node_name = $_POST['node_name'];  
  5.     $nodeid = Node::model()->getNodeId($_POST['node_name']); //通过节点名称获取该节点ID  
  6.     $server = GossServer::model()->getServerByNodeid($nodeid); //通过节点ID获取服务器信息  
  7.     //$server 为array类型,形如 $server = array(array('name'=>'name1'),array('name'=>'name2'));所以需要两次foreach  
  8.     if(isset($server)){  
  9.       foreach ($server as $k=>$v){  
  10. 10.         foreach($v as $kk => $vv){  
  11. 11.           echo CHtml::tag('option', array('value'=>$kk), CHtml::encode($vv), true);  
  12. 12.         }  
  13. 13.       }        
  14. 14.     }else{  
  15. 15.         echo CHtml::tag('option', array('value'=>''), 'servers', true);  
  16. 16.     }  

17. }     




 

 

 

模型:

 

 GossServer.php

[php] view plaincopy

  1. /** 
  2.  * 通过节点ID获取该节点下所有的服务器名称 
  3.  * @author ysdaniel 
  4.  */  
  5. public static function getServerByNodeid($nodeid)  
  6. {  
  7.         $sql = "SELECT name FROM OSS_Server WHERE nodeid = '{$nodeid}' ";  
  8.         ///$sql = "SELECT name,nodeid FROM OSS_Server WHERE nodeid = '{$nodeid}' "; //both ok  
  9.         $cmd = Yii::app()->db->createCommand($sql);  
  10. 10.   
  11. 11.         $ret = $cmd->queryAll();  
  12. 12.         if (!$ret){  
  13. 13.                 throw new Exception("找不到这个节点对应的服务器");  
  14. 14.         }  
  15. 15.         return $ret;  

16. }     


Node.php

[php] view plaincopy

  1.  /** 
  2.  * 通过nodename获取nodeid名 
  3.  * @author  
  4.  */  
  5. public static function getNodeId($name)  
  6. {  
  7.         $sql = "SELECT id FROM OSS_Node WHERE name = '{$name}'";  
  8.         $cmd = Yii::app()->db->createCommand($sql);  
  9.   
  10. 10.         $ret = $cmd->queryAll();  
  11. 11.         if (!$ret){  
  12. 12.                 return null;  
  13. 13.                 //throw new Exception("找不到Node{$name}");  
  14. 14.         }  
  15. 15.         return $ret[0]['id'];  

16. }     



Onchage 事件

echo "Select Release : ".$form->dropDownList($model,'tpr',$tpri,array(

       'id'       => 'tpr',

       'onchange' => 'location.href    = \''.Yii::app()->createUrl('show/Report/crinoise&').'type='.$_GET['type'].'&tpr=\'+$(\'#tpr option:selected\').val();',

    ));

   

其它:

数据表结构

 

效果:

没有选择节点前:

 

选择节点后,第二个列表跟着变动:

 

 

 

 

 

 

 

 

  1. $criteria = new CDbCriteria;   
  2. //select  
  3. $criteria->select = '*';//默认*  
  4. $criteria->select = 'id,name';//指定的字段  
  5. $criteria->select = 't.*,t.id,t.name';//连接查询时,第一个表as t,所以用t.*  
  6. $criteria->distinct = FALSE; //是否唯一查询   
  7.   
  8.   
  9. //join  

10. $criteria->join = 'left join table2 t2 on(t.id=t2.tid)'; //连接表    

11. $criteria->with = 'xxx'; //调用relations    

  1. 12.   
  2. 13.   

14. //where 查询数字字段  

15. $criteria->addCondition("id=1"); //查询条件,即where id = 1    

16. $criteria->addBetweenCondition('id', 1, 4);//between 1 and 4       

17. $criteria->addInCondition('id', array(1,2,3,4,5)); //代表where id IN (1,23,,4,5,);    

18. $criteria->addNotInCondition('id', array(1,2,3,4,5));//与上面正好相法,是NOT IN  

  1. 19.   
  2. 20.   

21. //where 查询字符串字段  

22. $criteria->addSearchCondition('name', '分类');//搜索条件,其实代表了。。where name like '%分类%'   

  1. 23.    

24. //where 查询日期字段  

25. $criteria->addCondition("create_time>'2012-11-29 00:00:00'");  

26. $criteria->addCondition("create_time<'2012-11-30 00:00:00'");  

  1. 27.   
  2. 28.   

29. //where and or  

30. $criteria->addCondition('id=1','OR');//这是OR条件,多个条件的时候,该条件是OR而非AND    

  1. 31.   
  2. 32.   

33. //这个方法比较特殊,他会根据你的参数自动处理成addCondition或者addInCondition,  

34. //即如果第二个参数是数组就会调用addInCondition    

  1. 35.   
  2. 36.   

37. $criteria->compare('id', 1);      

38. /**  * 传递参数 */    

  1. 39.   
  2. 40.   

41. $criteria->addCondition("id = :id");    

42. $criteria->params[':id']=1;    

  1. 43.   
  2. 44.   

45. //order   

46. $criteria->order = 'xxx DESC,XXX ASC' ;//排序条件    

  1. 47.   
  2. 48.   

49. //group  

50. $criteria->group = 'group 条件';    

51. $criteria->having = 'having 条件 ';   

  1. 52.   
  2. 53.   

54. //limit  

55. $criteria->limit = 10;    //取1条数据,如果小于0,则不作处理    

56. $criteria->offset = 1;   //两条合并起来,则表示 limit 10 offset 1,或者代表了。limit 1,10

 

 

数据模型搜索方法:

[html] view plaincopyprint?

  1. public function search()  
  2. {  
  3.     // Warning: Please modify the following code to remove attributes that  
  4.     // should not be searched.  
  5.   
  6.     $criteria=new CDbCriteria;  
  7.   
  8.     $criteria->compare('id',$this->id);  
  9.     $criteria->compare('title',$this->title,true);                //支持模糊查找  
  10. 10.     $criteria->compare('content',$this->content,true);            //支持模糊查找  
  11. 11.     $criteria->compare('type',$this->type);  
  12. 12.     $criteria->compare('user',$this->user,true);              //支持模糊查找  
  13. 13.     $criteria->compare('status',$this->status);  
  14. 14.     $criteria->compare('create_data',$this->create_data,true);    //支持模糊查找  
  15. 15.   
  16. 16.     return new CActiveDataProvider($this, array(  
  17. 17.         'criteria'=>$criteria,  
  18. 18.         'pagination'=>array(  
  19. 19.             'pageSize'=>50,  
  20. 20.         ),  
  21. 21.     ));  

22. }  

 

定义比较运算

[html] view plaincopyprint?

  1. $criteria->compare('create_time','<='.$this->endtime),//创建早间小于等于指定时间  

定义要查找的字段

[html] view plaincopyprint?

  1. //查找的结果   
  2. $criteria->select = 'id,title,content,author,status,createtime',  
  3. //也可以以下一种方式定义  
  4. $criteria->select = array('id','title','content','author','status','createtime'),  



定义填加查找条件

[html] view plaincopyprint?

  1. //定义条件    
  2. $criteria->select =  'status=1',  
  3. //添加匹配  
  4. $criteria->compare('title',$this->title,true),  
  5. //添加条件 $condition可以是数组,也可以是字符串,and可以省略  
  6. $criteria->addCondition($condition,'and'),  
  7. //添加IN条件 $column为字段名  
  8. $criteria->addInCondition(string $column, array $values, string $operator='AND')  
  9. //添加notin条件  

10. $criteria->addNotInCondition(string $column, array $values, string $operator='AND')  

11. //添加like条件  

12. $criteria->addSearchCondition(string $column, string $keyword),  

13. //添加Between条件  

14. $criteria->addBetweenCondition(string $column, string $valueStart, string $valueEnd, string $operator='AND'),  

JOIN连表查询

[html] view plaincopyprint?

  1. $criteria->join = 'LEFT JOIN users ON users.id=authorID',  



order查询结果排序

[html] view plaincopyprint?

  1. $criteria->order = 'createtime DESC',  



group结果分组

[html] view plaincopyprint?

  1. $criteria->group =  'projectID, teamID',  



having筛选分组结果分组数量

[html] view plaincopyprint?

  1. $criteria->having =  'SUM(revenue)<5000

 

 

 

 

1.在视图中 CGridView中的columns添加

[html] view plaincopy

  1. array(  
  2.               'selectableRows' => 2,  
  3.               'footer' => '<button type="button" onclick="GetCheckbox();" style="width:76px">批量删除</button>',  
  4.               'class' => 'CCheckBoxColumn',  
  5.               'headerHtmlOptions' => array('width'=>'33px'),  
  6.               'checkBoxHtmlOptions' => array('name' => 'selectdel[]'),  
  7.       ),  


作用是添加多选框

 

2.js代码

 

 

[html] view plaincopy

  1. <script type="text/javascript">  
  2.     function GetCheckbox(){  
  3.             var data=new Array();  
  4.             $("input:checkbox[name='selectdel[]']").each(function (){  
  5.                     if($(this).attr("checked")==true){  
  6.                             data.push($(this).val());  
  7.                     }  
  8.             });  
  9.             if(data.length > 0){  
  10. 10.                     $.post("index.php?r=ip/delall",{'selectdel[]':data}, function (data) {  
  11. 11.                             if (data=='ok') {  
  12. 12.                                     alert('删除成功!');  
  13. 13.          window.open('index.php?r=ip/admin','indexFrame');;  
  14. 14.                           }  
  15. 15.                     });  
  16. 16.             }else{  
  17. 17.                     alert("请选择要删除的选项!");  
  18. 18.             }  
  19. 19.     }  

20. </script>  

 

3.Action

[html] view plaincopy

  1. /*  
  2.  * 作用:批量删除  
  3.  */  
  4.   public function actionDelall()  
  5.  {  
  6.    if (Yii::app()->request->isPostRequest)  
  7.    {  
  8.      $criteria= new CDbCriteria;  
  9.      $criteria->addInCondition('ip_id', $_POST['selectdel']);  
  10. 10.      Ip::model()->deleteAll($criteria);//Words换成你的模型   
  11. 11.      if(isset(Yii::app()->request->isAjaxRequest)) {  
  12. 12.        echo 'ok';  
  13. 13.      } else  
  14. 14.        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));  
  15. 15.    }  
  16. 16.    else  
  17. 17.      throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');  
  18. 18.  }  



 

顺便列出一些常用的类型:

[html] view plaincopy

  1. <?php $this->widget('zii.widgets.grid.CGridView', array(  
  2.  'id'=>'chapter-grid',  
  3.  'dataProvider'=>$model->search(),  //数据结果集  
  4.  'filter'=>$model,       
  5.  'columns'=>array(  
  6.       'id',  
  7.       //锚点<a href="http://www.gulianqiang.com/"></a>  
  8.        array(  
  9.               'name'=>'name',  
  10. 10.               'type'=>'raw',  
  11. 11.               'value'=>'CHtml::link($data->name,"/book/$data->id")',  
  12. 12.          ),  
  13. 13.       //图片  
  14. 14.        array(  
  15. 15.               'name'=>'image',  
  16. 16.               'type'=>'image',  
  17. 17.               'value'=>'LImages::getPath("book").$data->image',//图片相对路径  
  18. 18.          ),  
  19. 19.        //下拉列表  
  20. 20.         array(  
  21. 21.               'name'=>'type',  
  22. 22.               'value'=>'Lookup::item("chapterType",$data->type)',  
  23. 23.               'filter'=>Lookup::items('chapterType'),  
  24. 24.          ),  
  25. 25.        //内容截取  
  26. 26.         array(  
  27. 27.               'name'=>'content',  
  28. 28.               'type'=>'html',  
  29. 29.               'value'=>'mb_substr(htmlspecialchars_decode($data->content),0,100,"utf-8")',  
  30. 30.          ),  
  31. 31.                //时间  
  32. 32.         array(  
  33. 33.               'name'=>'create_time',  
  34. 34.               'type'=>'datetime',  
  35. 35.          ),  
  36. 36.        // 根据相关信息读数据库  
  37. 37.         array(  
  38. 38.               'name'=>'user_id',  
  39. 39.               'value'=>'User::model()->findbyPk($data->user_id)->username',  
  40. 40.               'filter'=>false,  
  41. 41.          ),  
  42. 42.   array(  
  43. 43.    'class'=>'CButtonColumn',  
  44. 44.   ),  
  45. 45.  ),  

46. )); ?>  

 

 

 

CGridView 用法例子:

模型:

public function rules()

              {

                     return array(

                            array('DWO_Id,Parent_CRI,LOT_lastupdate','safe'),

                     );    

              }

              public function search()

              {

                     $criteria = new CDbCriteria;

                     $criteria->compare('DWO_Id',$this->DWO_Id,true);

                    

                     $criteria->compare('Parent_CRI',$this->Parent_CRI,true);

                     $criteria->compare('LOT_lastupdate',$this->LOT_lastupdate,true);  

                    

                     return new CActiveDataProvider(

                            get_class($this),

                            array(

                                   'criteria'   => $criteria,

                                   'sort'       => array('defaultOrder'=>'LOT_lastupdate DESC'),

                                   'pagination'     => array('pageSize'=>7),

                            )

                     );

              }

 

控制器:

 

public function actionAdmin()

       {

              $model=new Post('search');

              if(isset($_GET['Post']))

                     $model->attributes=$_GET['Post'];

              $this->render('admin',array(

                     'model'=>$model,

              ));

       }

 

 

<?php

 

       $this->widget('zii.widgets.grid.CGridView',array(

              'dataProvider'  => $dwo->search(),

              'filter'             => $dwo,

              'pager'                   => array(

                     'class'      => 'CLinkPager',

                     //'cssFile' => false,这里如果没有请注释掉,不然会出错

                     'header'   => 'Go To Page',

                     'firstPageLabel'      => 'First',

                     'lastPageLabel'       => 'Last',

                     'nextPageLabel'             => 'Next',

                     'prevPageLabel'             => 'Prev'

              ),

              'columns'        => array(

                     array(

                            'name'=>'DWO_Id',

                            'type'=>'raw',

                            'value'=> 'CHtml::encode($data->DWO_Id)'

                     ),

                     array(

                            'name'=>'Parent_CRI',

                            'type'=>'raw',

                            'value'=>'CHtml::link(CHtml::encode($data->Parent_CRI),"mailto:".CHtml::encode($data->Parent_CRI))'

                     ),

                     array(

                            'name'=>'LOT_lastupdate',

                            'type'=>'raw',

                            'value'=>'date_format(date_create($data->LOT_lastupdate),"Y-m-d H:i:s")'

                     ),

                    

                     array(

                     'header'=>'Operation',

                     'footer'=>'aaa',

                     'class'=>'CButtonColumn',

                     'updateButtonUrl'   => 'Yii::app()->controller->createUrl("updaterole",array("id"=>$data->primaryKey))',

                     'deleteConfirmation'      => 'Are you sure?',

                     'buttons'  => array(

                            'view'      => array('visible'=>'false'),

                            'delete'=> array('url'=>'Yii::app()->controller->createUrl("deleterole",array("id"=>$data->primaryKey))'),

                     ),

              ),

              ),

       ));

      

?>

 

 

 

 

显示首页,最后一页:

添加css

ul.yiiPager .first, 

ul.yiiPager .last 

    display:inline; 

 

 

 

 

CDetailView 例子:

控制器:

public function actionMdetail($did)

       {

              $info = Dwo::model()->findByPk($did);

              $this->render('mdetail',array('info'=>$info));

       }

View 视图

 

<?php

       $this->widget('zii.widgets.CDetailView',array(

              'data'=>$info,

              'attributes'=>array(

                     'DWO_Id',

                     'LOT_lastupdate',

                     'Parent_CRI',

                     'ClosedDate',

                     'Priority'

              ),

       ));

?>

 

参考:http://www.yiiframework.com/doc/api/1.1/CDetailView

$this->widget('zii.widgets.CDetailView', array(
    'data'=>$model,
    'attributes'=>array(
        'title',             // title attribute (in plain text)
        'owner.name',        // an attribute of the related object "owner"
        'description:html',  // description attribute in HTML
        array(               // related city displayed as a link
            'label'=>'City',
            'type'=>'raw',
            'value'=>CHtml::link(CHtml::encode($model->city->name),
                                 array('city/view','id'=>$model->city->id)),
        ),
    ),
));

 

 

AJAX操作:

视图:

<?php $form = $this->beginWidget('CActiveForm');?>

Please input CR ID : <?php echo $form->textField($model,'crid',array(

       'id'   => 'crid',

));?>

<?php echo CHtml::ajaxSubmitButton('Search',Yii::app()->createUrl("show/Cr/info"),array(

       'type'       => 'POST',

       'data'       => 'js:{"crid":$("#crid").val(),"type":"cr_info"}',

       'success'   => 'js:function(s){$("#cr_info").html(s);}',

));?>

<?php     $this->endWidget(); ?>

 

控制器

public function actionIndex()

       {

              $model                         = Cr::model();

             

              $data = array(

                     'model'=>$model,

                     );

              $this->render('index',$data);

       }

       public function actionInfo()

       {

              $model           = Cr::model();

              $info = $model->find('CR_Id=:crid',array(':crid'=>addslashes(trim($_POST['crid']))));

              $field      = $model->allLabel();

             

              $data       = array(

                     'info' => $info,

                     'title' => $field,

              );

             

              $this->renderPartial('detail',$data);

       }

 

AJAX返回的视图:

<?php

       if($info):

?>

 

<table width="100%" border="0" cellspacing="1" cellpadding="4" bgcolor="<?php echo BORDERCOLOR;?>">

 <?php

  foreach($title as $k=>$v):

  ?> 

  <tr bgcolor="<?php echo BGCOLOR;?>"> 

  

  <th scope="row" bgcolor="<?php echo CTITLECOLOR?>" align="left" title="<?php echo $v;?>"><?php echo $k;?></th>   

  <td><?php echo $info->$k!='0000-00-00 00:00:00'?$info->$k:''; ?></td>   

  </tr> 

  <?php endforeach;?> 

 </table>

  <?php else:?>

  <p align="center">No Data To Display</p>

  <?php endif;?>

 

 

 

查询单条信息:

find() 查询一条信息

例子:find(‘username=:name’,array(‘:name’=>’admin’))

findByPk() 通过主键查询

例子:findByPk(1);

findBySql() 通过sql语句查询出一条

例子:findBySql(‘SELECT * FROM {{admin}}’);

 

查询多条:

findAll() 查询多条信息:

例子: findAll(‘color=:color’,array(‘:color’=>’red’))

findAllByPk(): 通过多个 主键查询

findAllByPk(array(1,2,3))

 

findAllBysql()

例子:  findAllBysql(‘SELECT * FROM {{admin}}’);

 

 

 

伪静态的实现:

首先加载模块:LoadModule rewrite_module modules/mod_rewrite.so

然后确保目录的:AllowOverride All ## 这里一定要是All

然后在根目录下创建文件.htaccess ,文件内容为:

RewriteEngine on

# if a directory or a file exists,use it directly

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

#otherwise forward it to index.php

RewriteRule . index.php

 

或者:

RewriteEngine on
# if a directory or a file exists,use it directly
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#otherwise forward it to index.php
RewriteRule ^(.*)$  index.php/$1 [L]

 

然后打开protected/config目录下的main.php

找到并改为下面的部分

 

'urlManager'=>array(

                     'urlFormat'=>'path',//改为path格式路径

                     'showScriptName'=>false,//去掉index.php

                     'rules'=>array(

                            'index.html'    => array('show/Cr/index'),

                            'a/<aid:\d+>'   => array('article/index','urlSuffix'=>'.html'),

                            'c/<cid:\d+>'   => array('category/index','urlSuffix'=>'.html'),

                     ),

              ),

 

 

 

开启缓存:

在main.php的组件components中配置设置缓存

‘cache’    => array(

       ‘class’=>’system.caching.CFileCache’

);

//模块地址 是framework/caching/CFileCache.php

 

例如:

'components'=>array(

              'user'=>array(

                     // enable cookie-based authentication

                     'allowAutoLogin'=>true,

              ),

              // uncomment the following to enable URLs in path-format

              'cache'     => array(

                     'class'      => 'system.caching.CFileCache',// 这里开启的是文件缓存

              ),

 

 

片段缓存:

<?php if($this->beginCache($id,array(‘duration’=>1))):?>

缓存内容

<?php $this->endCache();endif;?>

 

其中上面的$id,是缓存的编号(一个页面可能有多个缓存),duration是时间,以秒为单位

注意,片段缓存这里,如果缓存内容有参数,那么可能不能用。

 

整页缓存:在控制器中

Public function filters()

{

       Return array(

              Array(

                     ‘system.web.widgets.COutputCache + index’,//index是缓存的页面

‘duration’   => 30,

‘variByParam’=>array(‘aid’),//如果页面有参数,应该写在这里

),

);

}

 

数据缓存:

$value = Yii::app()->cache->get($id);

 

 

 

If($value == false)

{

       Yii::app()->cache->set($id,$value);

}

 

其中$value 是缓存的内容,$id是缓存的编号

 

 

添加全局变量:

在文件夹:protected\components 下面添加文件:

globalVars.php 内如如下:

<?php

       class globalVars extends CApplicationComponent

       {

              public $notInLdapUser         = array('');

              public $notInLdapUserPwd   = array('abcde'=>'');

                    

       }

?>

 

然后在protacted/config/main.php中定义:

'components'=>array(

              'user'=>array(

                     // enable cookie-based authentication

                     'allowAutoLogin'=>true,

              ),

              //global vars

              'globalVars'     => array(

                     'class'             => 'application.components.globalVars',

              ),

 

调用的时候:Yii::app()->globalVars->notInLdapUser

 

 

 

Gridview 例子:

 

模型:

public function tableName()

              {

                     return "{{detail}}";

              }

             

              public function relations()

              {

                     return array(

                            'detail' => array(self::MANY_MANY,'actor','{{type}}(did,aid)'),

                            'mmtype' => array(self::BELONGS_TO,'movietype','mtype'),

                     );    

              }

public function search()

              {

                     $criteria = new CDbCriteria;

                     $criteria->with = array('mmtype');

                     $criteria->compare('cname',$this->cname,true);

                    

                     $criteria->compare('info',$this->info,true);

                    

                     return new CActiveDataProvider(

                            get_class($this),

                            array(

                                   'criteria'   => $criteria,

                                  

                            )

                     );

              }

 

控制器:

public function actionIndex()

              {

                     $model = new Movie('search');

                     if(isset($_POST['Movie']))

                            $model->attributes = $_POST['Movie'];

                    

                     $data = array('model'=>$model);

                     $this->render('index',$data); 

              }    

 

视图:

<?php

 

       $this->widget('zii.widgets.grid.CGridView',array(

              'dataProvider'  => $model->search(),

              'filter'             => $model,

              'pager'                   => array(

                     'class'      => 'CLinkPager',

                     //'cssFile' => false,这里如果没有请注释掉,不然会出错

                     'header'   => 'Go To Page',

                     'firstPageLabel'      => 'First',

                     'lastPageLabel'       => 'Last',

                     'nextPageLabel'             => 'Next',

                     'prevPageLabel'             => 'Prev'

              ),

              'columns'        => array(

                     array(

                            'name'=>'cname',

                            'type'=>'raw',

                            'value'=> 'CHtml::encode($data->cname)'

                     ),

                     array(

                            'name'=>'info',

                            'type'=>'raw',

                            'value'=>'CHtml::link(CHtml::encode($data->info),"mailto:".CHtml::encode($data->info))'

                     ),

                     array(

                            'name'=>'mtype',

                            'type'=>'raw',

                            'value'=>'$data->mmtype->mtype'

                     ),

                    

                    

             

              ),

       ));

      

?>

 

 

 

 

AJAX 分页

 

ajax验证表单、分页、Yii ajax分页

一:ajax有专门的Widget,你可以在视图里直接调用,比如用ajax验证表单,写法如下:

[php] view plaincopy

  1. <?php $form=$this->beginWidget('CActiveForm', array(  
  2.         'id'=>'user-form',  
  3.         'enableAjaxValidation'=>true,  
  4. )); ?>  
  5. ...表单内容...  
  6. <?php $this->endWidget(); ?>  

分页:

[php] view plaincopy

  1. $articles = array();  
  2.   
  3. // 查询条件  
  4. $criteria = new CDbCriteria();  
  5. $criteria->order = '`createdTime` DESC';  
  6. $criteria->addCondition("`typeId` = '1' AND `status` = '1'");  
  7.   
  8. // 求总的记录数  
  9. $count = Article::model()->count($criteria);  
  10.   
  11. $pages = new CPagination($count);  
  12.   
  13. $pages->pageSize = 10;  
  14. $pages->applyLimit($criteria);  
  15.   
  16. $articles = Article::model()->findAll($criteria);  

 

Yii ajax分页:

我们有时候需要ajax读取数据,并进行分页。首先我们遇到的是如何载入样式表,自动化习惯了后,一些基本的常识还是得知道的。 

在载入页面添加如下

[php] view plaincopy

  1. $cs = Yii::app()->getClientScript();  
  2. $url=CHtml::asset(Yii::getPathOfAlias('system.web.widgets.pagers.pager').'.css');  
  3. $cs->registerCssFile($url);  

OK,样式表载入了,那么如何进行分页呢。这里其实已经不是yii的功能了,而是Jquery。我们可以为分页的链接live一个click

如下,添加js,选择器修改下

[php] view plaincopy

  1. $('#search_list .yiiPager a').live('click',function(){  
  2.     $.ajax({  
  3.         url:$(this).attr('href'),  
  4.         success:function(html){  
  5.             $('#search_list').html(html);  
  6.         }  
  7.     });  
  8.     return false;  
  9. });  

 

 

下面实例是cgridview ;

模型:

public function featureSearch()

              {

                     $featureId = isset($_GET['featureid'])?addslashes(trim($_GET['featureid'])):addslashes(trim($_POST['featureid']));

                     $criteria                = new CDbCriteria;

                     $criteria->select     = " t4.id AS id,t4.DWO_Id AS DWO_Id,t4.ProjectName AS ProjectName,sum(t.`totalchurn`) AS totalchurn";//

                     $criteria->join       = 'LEFT JOIN {{act2ver_link}} AS t2 ON (t.ver_id=t2.to_verid) ';

                     $criteria->join       .= 'LEFT JOIN {{activities}} AS t3 ON (t2.from_oid_vob=t3.act_oid_vob) ';

                     $criteria->join       .= 'LEFT JOIN {{DWO}} AS t4 ON (t3.act_oid=t4.CC_UCMActivityNo AND t3.pvob_oid=t4.PVOB) ';

                     $criteria->join       .= 'LEFT JOIN {{CRI}} AS t5 ON (t4.Parent_CRI=t5.id) ';

                     $criteria->distinct = FALSE;

                     $criteria->group     = 't4.DWO_Id';                    $criteria->addCondition('`Parent_CR.FeatureId`="'.$featureId.'"');

                    

                     return new CActiveDataProvider(

                            get_class($this),

                            array(

                                   'criteria'   => $criteria,

                                   /*'pagination'  => false

                                   */

                                   'pagination' => array(

                                          'pageSize' => 20,

                                          'params'   => array('featureid'=>$featureId)

                                         

                                   )

                            )

                     );

              }

             

 

控制器:

public function actionCri()

       {

              $model    = Cri::model();

             

             

              $data      = array(

                     'model'=>$model,

                     );

              $this->render('cri',$data);

       }

       public function actionCriInfo()

       {

              $model           = new Cri('featureSearch');

             

              $data              = array(

                     'model'           => $model,

              );

              $this->renderPartial('criInfo',$data);

       }

 

 

视图:

<div id="showcontent">

<?php

 

       $this->widget('zii.widgets.grid.CGridView',array(

              'dataProvider'  => $model->featureSearch(),

              //'filter'           => $model,

              'columns'        => array(

                     array(

                            'id'=>'Id',

'name'       => 'ID',

                            'type'=>'raw',

                            'value'=> 'CHtml::encode($data->id)'

                     ),

                     array(

                            'id'=>'CRI_Id',

                            'name'     => 'CRI Id',

                            'type'=>'raw',

                            'value'=>'$data->CRI_Id'

                     ),

              ),

       ));

        

?>

</div>

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl;?>/assets/ee6f27cf/gridview/styles.css" />

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl;?>/assets/64c8dc95/pager.css" />

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl;?>/assets/js/jquery.min.js"></script>

<script>

    $('#showcontent .yiiPager a').live('click',function(){ 

        $.ajax({ 

            url:$(this).attr('href'), 

            success:function(html){ 

                $('#showcontent').html(html); 

            } 

        }); 

        return false; 

    }); 

       //alert( $('#yw1').html());

      

</script>

 

 

 

 

 

 

 

 

 

Yii Criteria常用方法(select,join,where,日期,)

 

[php] view plaincopy

  1. $criteria = new CDbCriteria;   
  2. //select  
  3. $criteria->select = '*';//默认*  
  4. $criteria->select = 'id,name';//指定的字段  
  5. $criteria->select = 't.*,t.id,t.name';//连接查询时,第一个表as t,所以用t.*  
  6. $criteria->distinct = FALSE; //是否唯一查询   
  7.   
  8.   
  9. //join  
  10. $criteria->join = 'left join table2 t2 on(t.id=t2.tid)'; //连接表    
  11. $criteria->with = 'xxx'; //调用relations    
  12.   
  13.   
  14. //where 查询数字字段  
  15. $criteria->addCondition("id=1"); //查询条件,即where id = 1    
  16. $criteria->addBetweenCondition('id', 1, 4);//between 1 and 4       
  17. $criteria->addInCondition('id', array(1,2,3,4,5)); //代表where id IN (1,23,,4,5,);    
  18. $criteria->addNotInCondition('id', array(1,2,3,4,5));//与上面正好相法,是NOT IN  
  19.   
  20.   
  21. //where 查询字符串字段  
  22. $criteria->addSearchCondition('name', '分类');//搜索条件,其实代表了。。where name like '%分类%'   
  23.    
  24. //where 查询日期字段  
  25. $criteria->addCondition("create_time>'2012-11-29 00:00:00'");  
  26. $criteria->addCondition("create_time<'2012-11-30 00:00:00'");  
  27.   
  28.   
  29. //where and or  
  30. $criteria->addCondition('id=1','OR');//这是OR条件,多个条件的时候,该条件是OR而非AND    
  31.   
  32.   
  33. //这个方法比较特殊,他会根据你的参数自动处理成addCondition或者addInCondition,  
  34. //即如果第二个参数是数组就会调用addInCondition    
  35.   
  36.   
  37. $criteria->compare('id', 1);      
  38. /**  * 传递参数 */    
  39.   
  40.   
  41. $criteria->addCondition("id = :id");    
  42. $criteria->params[':id']=1;    
  43.   
  44.   
  45. //order   
  46. $criteria->order = 'xxx DESC,XXX ASC' ;//排序条件    
  47.   
  48.   
  49. //group  
  50. $criteria->group = 'group 条件';    
  51. $criteria->having = 'having 条件 ';   
  52.   
  53.   
  54. //limit  
  55. $criteria->limit = 10;    //取1条数据,如果小于0,则不作处理    
  56. $criteria->offset = 1;   //两条合并起来,则表示 limit 10 offset 1,或者代表了。limit 1,10  

 

 

 

 

 

http://blog.csdn.net/yuhui_fish/article/details/8242344

posted @ 2016-11-19 08:49  seedsman  阅读(458)  评论(0编辑  收藏  举报