YII中checkBoxList的数据库存取

checkBoxList是YII中的复选框组,用户在增加数据时,将以数组的形式把数据提交过来。但是,对应数据库的一个字段,只能保存字符串,不能保存数组。这时,我们可以先将提交过来的数组,用PHP的implode(),将数组转换成字符串,然后保存到数据库中。修改数据时,从数据库的一个字段中取出类似1,2,8,9的字符串,用explode(),重新将字符串转换成数组,在actionupdate()方法中,使用$model->goods_color的形式,将数据赋值给模型对应的属性,这时候,之前保存的值,将会被勾中。修改后的值,会重新再入库。效果如下:

1、增加商品

YII中checkBoxList的数据库存取_第1张图片

2、选择提交

YII中checkBoxList的数据库存取_第2张图片

3、提交后数据库显示的字符串

YII中checkBoxList的数据库存取_第3张图片

4、点击修改,表单又会从数据库将读出来的值对应到相应的值

YII中checkBoxList的数据库存取_第4张图片

以下是对应的代码:

控制器:

array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin','@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new TblGoods;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                //使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第1步
                //在Goods控制器下实例化category对象,并执行SQL语句,取得所有数据。
                $category =  TblCategory::model()->findAll();

		if(isset($_POST['TblGoods']))
		{
			$model->attributes=$_POST['TblGoods'];
                        //yii checkBoxList 的高级使用
                        //将checkBoxList提交的数据,转换成字符串后再保存到数据库中。
                        //获取颜色数组后将数组转换成字符串,用豆号分隔。并保存到数据库中。
                        if(!empty($_POST['TblGoods']['goods_color'])){
                            $str_color=  implode(',', $_POST['TblGoods']['goods_color']);
                            $model->goods_color=$str_color;
                        }
                        //获取颜色数组后将数组转换成字符串,用豆号分隔。并保存到数据库中。
                        if(!empty($_POST['TblGoods']['goods_size'])){
                            $str_size=  implode(',', $_POST['TblGoods']['goods_size']);   
                            $model->goods_size=$str_size;
                        }

                        //实现文件,图片的上传
                        $model->goods_small_pic=  CUploadedFile::getInstance($model, goods_small_pic);
                        $model->goods_big_pic=  CUploadedFile::getInstance($model, goods_big_pic);
                        if($model->goods_small_pic){
                            $newimg='goods_small_pic_'.time().'_'.rand(1,9999).".".$model->goods_small_pic->extensionName;
                            //$newimg="abc.jpg";
                            $model->goods_small_pic->saveAs('assets/uploads/tblgoods/'.$newimg);
                            $model->goods_small_pic='assets/uploads/tblgoods/'.$newimg;
                        }
                        if($model->goods_big_pic){
                            $newimg2='goods_big_pic_'.time().'_'.rand(1,9999).".".$model->goods_big_pic->extensionName;
                            //$newimg2="abcd.jpg";
                            $model->goods_big_pic->saveAs('assets/uploads/tblgoods/'.$newimg2);
                            $model->goods_big_pic='assets/uploads/tblgoods/'.$newimg2;
                        }
                        
			if($model->save())
				$this->redirect(array('view','id'=>$model->goods_id));
		}

		$this->render('create',array(
			'model'=>$model,
                        //使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第2步
                        //在Goods控制器下create将上面得到的数组,分配到create这个VIEW页面。
                        'category'=>$category
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                //yii checkBoxList 的高级使用
                //如果数据库颜色存在颜色数据,先将数据读取出来,转换成数组后,再赋值给$model->goods_color
                //这时候,在视图那边的checkBoxList将会显示从数据库中存在的值了。
                if(!empty($model->goods_color)){
                    $color=$model->goods_color;
                    $arr_color= explode(',', $color);
                    $model->goods_color=$arr_color;
                }
                //如果数据库颜色存在尺寸数据,先将数据读取出来,转换成数组后,再赋值给$model->goods_size
                //这时候,在视图那边的checkBoxList将会显示从数据库中存在的值了。
                if(!empty($model->goods_size)){
                    $size=$model->goods_size;
                    $arr_size= explode(',', $size);
                    $model->goods_size=$arr_size;
                }
                
                //使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第1步
                //在Goods控制器下实例化category对象,并执行SQL语句,取得所有数据。
                $category =  TblCategory::model()->findAll();

		if(isset($_POST['TblGoods']))
		{                          
			$model->attributes=$_POST['TblGoods'];
                        
                        //获取颜色数组后将数组转换成字符串,用豆号分隔。并保存到数据库中。
                        if(!empty($_POST['TblGoods']['goods_color'])){
                            $str_color=  implode(',', $_POST['TblGoods']['goods_color']);
                            $model->goods_color=$str_color;
                        }
                        //获取颜色数组后将数组转换成字符串,用豆号分隔。并保存到数据库中。
                        if(!empty($_POST['TblGoods']['goods_size'])){
                            $str_size=  implode(',', $_POST['TblGoods']['goods_size']);   
                            $model->goods_size=$str_size;
                        }
                        
                        //实现文件,图片的上传
                        $model->goods_small_pic=  CUploadedFile::getInstance($model, goods_small_pic);
                        $model->goods_big_pic=  CUploadedFile::getInstance($model, goods_big_pic);
                        if($model->goods_small_pic){
                            $newimg='goods_small_pic_'.time().'_'.rand(1,9999).".".$model->goods_small_pic->extensionName;
                            //$newimg="abc.jpg";
                            $model->goods_small_pic->saveAs('assets/uploads/tblgoods/'.$newimg);
                            $model->goods_small_pic='assets/uploads/tblgoods/'.$newimg;
                        }else{
                            $model->goods_small_pic=$_POST['temp_img1'];
                        }
                        if($model->goods_big_pic){
                            $newimg2='goods_big_pic_'.time().'_'.rand(1,9999).".".$model->goods_big_pic->extensionName;
                            //$newimg2="abcd.jpg";
                            $model->goods_big_pic->saveAs('assets/uploads/tblgoods/'.$newimg2);
                            $model->goods_big_pic='assets/uploads/tblgoods/'.$newimg2;
                        }else{
                            $model->goods_big_pic=$_POST['temp_img2'];
                        }
                        
			if($model->save())
				$this->redirect(array('view','id'=>$model->goods_id));
		}

		$this->render('update',array(
			'model'=>$model,
                        //使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第2步
                        //在Goods控制器下create将上面得到的数组,分配到create这个VIEW页面。
                        'category'=>$category
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('TblGoods');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new TblGoods('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['TblGoods']))
			$model->attributes=$_GET['TblGoods'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return TblGoods the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=TblGoods::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param TblGoods $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='tbl-goods-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


 

模型:

true),
			array('cat_id, click_count, brand_id, goods_number, market_price, shop_price, promote_price', 'length', 'max'=>8),
			array('goods_sn', 'length', 'max'=>16),
			array('goods_name', 'length', 'max'=>32),
			//array('goods_desc, goods_small_pic, goods_big_pic', 'length', 'max'=>255),
                        array('goods_desc','length','max'=>255),
                        //要实现图片的上传与修改,要将保存图片URL地址的字段改为file,如下所示。
                        //array('goods_small_pic','file','types'=>'jpg,gif,png','on'=>'insert'),
                        //array('goods_big_pic','file','types'=>'jpg,gif,png','on'=>'insert'),
                    
			array('promote_start_date, promote_end_date, add_time', 'safe'),
                    array('shops_id', 'length', 'max'=>8),
                    //array('goods_color', 'length', 'max'=>32),
                    //array('goods_size', 'length', 'max'=>32),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('goods_id, cat_id, goods_sn, goods_name, click_count, brand_id, goods_number, market_price, shop_price, promote_price, promote_start_date, promote_end_date, goods_desc, goods_small_pic, goods_big_pic, is_sale, is_delete, is_best, is_new, is_hot, is_promote, add_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    //使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第2步
                    //将category这个表关联到goods
                    'category'=>array(self::BELONGS_TO, 'category','cat_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'goods_id' => '产品ID',
			'cat_id' => '类别ID',
			'goods_sn' => '产品编号',
			'goods_name' => '产品名称',
			'click_count' => '点击次数',
			'brand_id' => '品牌',
			'goods_number' => '数量',
			'market_price' => '市场价',
			'shop_price' => '本店价',
			'promote_price' => '促销价',
			'promote_start_date' => '开始时间',
			'promote_end_date' => '结束时间',
			'goods_desc' => '产品描述',
			'goods_small_pic' => '产品小图',
			'goods_big_pic' => '产品大图',
			'is_sale' => '是否销售',
			'is_delete' => '是否删除',
			'is_best' => '是否精品',
			'is_new' => '是否新品',
			'is_hot' => '是否热卖',
			'is_promote' => '是否促销',
			'add_time' => '创建时间',
                    'shops_id' => '门店ID',//表示这商品属于哪个门店
                    'goods_color' => '颜色',
                    'goods_size' => '尺寸',
                       使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第3步
                        //将关联到的字段,设置标题名称
                        //注意:这里的goods表和category表都有cat_id这个字段,系统将会使用后面设置的
                        'cat_id'=>'类别ID',
                    
                        'cat_name'=>'类别名称',
                        'parent_id'=>'类别父类 ID'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
                
                /**
                 *按照特定的条件显示数据表的内容 
                 */
                //创建访问控制对象,该类在components组件文件夹下accessCtrl,该类是自定义的by ping
                $accessCtrl=new accessCtrl();
                //把上面得到的criteria对象传递到shopmanager方法,得到返回结果
                if($temp=$accessCtrl->accessForGoods($criteria)){
                    $criteria=$temp;
                }
                //END:按照特定的条件显示数据表的内容 

		$criteria->compare('goods_id',$this->goods_id,true);
		$criteria->compare('cat_id',$this->cat_id,true);
		$criteria->compare('goods_sn',$this->goods_sn,true);
		$criteria->compare('goods_name',$this->goods_name,true);
		$criteria->compare('click_count',$this->click_count,true);
		$criteria->compare('brand_id',$this->brand_id,true);
		$criteria->compare('goods_number',$this->goods_number,true);
		$criteria->compare('market_price',$this->market_price,true);
		$criteria->compare('shop_price',$this->shop_price,true);
		$criteria->compare('promote_price',$this->promote_price,true);
		$criteria->compare('promote_start_date',$this->promote_start_date,true);
		$criteria->compare('promote_end_date',$this->promote_end_date,true);
		$criteria->compare('goods_desc',$this->goods_desc,true);
		$criteria->compare('goods_small_pic',$this->goods_small_pic,true);
		$criteria->compare('goods_big_pic',$this->goods_big_pic,true);
		$criteria->compare('is_sale',$this->is_sale);
		$criteria->compare('is_delete',$this->is_delete);
		$criteria->compare('is_best',$this->is_best);
		$criteria->compare('is_new',$this->is_new);
		$criteria->compare('is_hot',$this->is_hot);
		$criteria->compare('is_promote',$this->is_promote);
		$criteria->compare('add_time',$this->add_time,true);
                $criteria->compare('shops_id',$this->shops_id);
                $criteria->compare('goods_color',$this->goods_color);
                $criteria->compare('goods_size',$this->goods_size);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return TblGoods the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}


 

视图:








beginWidget('CActiveForm', array( 'id'=>'tbl-goods-form', // Please note: When you enable ajax validation, make sure the corresponding // controller action is handling ajax validation correctly. // There is a call to performAjaxValidation() commented in generated controller code. // See class documentation of CActiveForm for details on this. 'enableAjaxValidation'=>false, //要实现图片的上传与修改,enctype这句话一定要加上去。 'htmlOptions'=>array('enctype'=>'multipart/form-data') )); ?>

注:带 * 号为必填项!

errorSummary($model); ?>
labelEx($model,'cat_id'); ?> dropDownlist($model,'cat_id',CHtml::listData($category, 'cat_id', 'cat_name'));?> error($model,'cat_id'); ?>
labelEx($model,'goods_sn'); ?> textField($model,'goods_sn',array('size'=>16,'maxlength'=>16)); ?> error($model,'goods_sn'); ?>
labelEx($model,'goods_name'); ?> textField($model,'goods_name',array('size'=>32,'maxlength'=>32)); ?> error($model,'goods_name'); ?>
goods_color=array(1,3); //则checkBoxList对应的值将会打上勾 ?> labelEx($model,'goods_color'); ?> checkBoxList($model,'goods_color', CHtml::listData(SpecInfo::model()->findAllByAttributes(array('spec_id'=>2)),'spec_info_id','spec_info_name'), array( 'separator'=>'', 'labelOptions'=>array( 'style'=>'display:inline; margin-right:10px;' ) ) ); ?> error($model,'goods_color'); ?>
labelEx($model,'goods_size'); ?> checkBoxList($model,'goods_size', CHtml::listData(SpecInfo::model()->findAllByAttributes(array('spec_id'=>3)),'spec_info_id','spec_info_name'), array( 'separator'=>'', 'labelOptions'=>array( 'style'=>'display:inline; margin-right:10px;' ) ) ); ?> error($model,'goods_size'); ?>
labelEx($model,'click_count'); ?> textField($model,'click_count',array('size'=>8,'maxlength'=>8)); ?> error($model,'click_count'); ?>
labelEx($model,'brand_id'); ?> textField($model,'brand_id',array('size'=>8,'maxlength'=>8)); ?> error($model,'brand_id'); ?>
labelEx($model,'goods_number'); ?> textField($model,'goods_number',array('size'=>8,'maxlength'=>8)); ?> error($model,'goods_number'); ?>
labelEx($model,'market_price'); ?> textField($model,'market_price',array('size'=>8,'maxlength'=>8)); ?> error($model,'market_price'); ?>
labelEx($model,'shop_price'); ?> textField($model,'shop_price',array('size'=>8,'maxlength'=>8)); ?> error($model,'shop_price'); ?>
labelEx($model,'promote_price'); ?> textField($model,'promote_price',array('size'=>8,'maxlength'=>8)); ?> error($model,'promote_price'); ?>
labelEx($model,'promote_start_date'); ?> textField($model,'promote_start_date'); ?> error($model,'promote_start_date'); ?>
labelEx($model,'promote_end_date'); ?> textField($model,'promote_end_date'); ?> error($model,'promote_end_date'); ?>
labelEx($model,'goods_desc'); ?> textField($model,'goods_desc',array('size'=>60,'maxlength'=>255)); ?> widget('application.extensions.ckeditor.CKEditor', array( 'model'=>$model,//$model表示数据表的model 'attribute'=>'goods_desc',//表示要操作的字段 'language'=>'zh-cn', )); ?> error($model,'goods_desc'); ?>
labelEx($model,'goods_small_pic'); ?> textField($model,'goods_small_pic',array('size'=>60,'maxlength'=>255)); ?> error($model,'goods_small_pic'); ?> goods_small_pic.'" width="100px"/>'; ?> isNewRecord){?>
labelEx($model,'goods_big_pic'); ?> textField($model,'goods_big_pic',array('size'=>60,'maxlength'=>255)); ?> error($model,'goods_big_pic'); ?> goods_big_pic.'" width="100px"/>'; ?> isNewRecord){?>
labelEx($model,'is_sale'); ?> textField($model,'is_sale'); ?> error($model,'is_sale'); ?>
labelEx($model,'is_delete'); ?> textField($model,'is_delete'); ?> error($model,'is_delete'); ?>
labelEx($model,'is_best'); ?> textField($model,'is_best'); ?> error($model,'is_best'); ?>
labelEx($model,'is_new'); ?> textField($model,'is_new'); ?> error($model,'is_new'); ?>
labelEx($model,'is_hot'); ?> textField($model,'is_hot'); ?> error($model,'is_hot'); ?>
labelEx($model,'is_promote'); ?> textField($model,'is_promote'); ?> error($model,'is_promote'); ?>
labelEx($model,'add_time'); ?> textField($model,'add_time'); ?> error($model,'add_time'); ?>
labelEx($model,'shops_id'); ?> textField($model,'shops_id'); ?> dropDownList($model,'shops_id', CHtml::listData(TblShops::model()->findAll(),'shops_id','shops_name')) ?> error($model,'shops_id'); ?>
isNewRecord ? 'Create' : 'Save'); ?>
endWidget(); ?>


 

你可能感兴趣的:(PHP,YII框架)