在yii中使用dropDownlist与listData实现下拉菜单

代码:TblGoodsController.php(控制器)

 

<?php

class TblGoodsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
        //每个控制器可以在这里单获设置布局文件By Ping 2014-2-20
	public $layout='//layouts/houtai';
        

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>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'];
			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);
                // 
                //使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第1步
                //在Goods控制器下实例化category对象,并执行SQL语句,取得所有数据。
                $category =  TblCategory::model()->findAll();

		if(isset($_POST['TblGoods']))
		{
			$model->attributes=$_POST['TblGoods'];
			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();
		}
	}
}


代码:TblGoods(模型model)

<?php

/**
 * This is the model class for table "tbl_goods".
 *
 * The followings are the available columns in table 'tbl_goods':
 * @property string $goods_id
 * @property string $cat_id
 * @property string $goods_sn
 * @property string $goods_name
 * @property string $click_count
 * @property string $brand_id
 * @property string $goods_number
 * @property string $market_price
 * @property string $shop_price
 * @property string $promote_price
 * @property string $promote_start_date
 * @property string $promote_end_date
 * @property string $goods_desc
 * @property string $goods_small_pic
 * @property string $goods_big_pic
 * @property integer $is_sale
 * @property integer $is_delete
 * @property integer $is_best
 * @property integer $is_new
 * @property integer $is_hot
 * @property integer $is_promote
 * @property string $add_time
 */
class TblGoods extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_goods';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('is_sale, is_delete, is_best, is_new, is_hot, is_promote', 'numerical', 'integerOnly'=>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('promote_start_date, promote_end_date, add_time', 'safe'),
			// 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' => 'Cat',
			'goods_sn' => '产品编号',
			'goods_name' => '产品名称',
			'click_count' => '点击次数',
			'brand_id' => '品牌',
			'goods_number' => 'Goods Number',
			'market_price' => 'Market Price',
			'shop_price' => 'Shop Price',
			'promote_price' => 'Promote Price',
			'promote_start_date' => 'Promote Start Date',
			'promote_end_date' => 'Promote End Date',
			'goods_desc' => 'Goods Desc',
			'goods_small_pic' => 'Goods Small Pic',
			'goods_big_pic' => 'Goods Big Pic',
			'is_sale' => 'Is Sale',
			'is_delete' => 'Is Delete',
			'is_best' => 'Is Best',
			'is_new' => 'Is New',
			'is_hot' => 'Is Hot',
			'is_promote' => 'Is Promote',
			'add_time' => 'Add Time',
                       使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第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;

		$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);

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


代码:create.php(视图)

<?php
/* @var $this TblGoodsController */
/* @var $model TblGoods */

$this->breadcrumbs=array(
	'Tbl Goods'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'商品列表', 'url'=>array('index')),
	array('label'=>'管理商品', 'url'=>array('admin')),
);
?>

<h1>Create TblGoods_cccc</h1>
<!--使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第4步
//在create这个VIEW页面下,再分配到_form这个VIEW页面。-->
<?php $this->renderPartial('_form', array('model'=>$model,'category'=>$category)); ?>


代码:_form.php(视图)

<?php
/* @var $this TblGoodsController */
/* @var $model TblGoods */
/* @var $form CActiveForm */
?>

<div class="form">

<?php $form=$this->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,
)); ?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo $form->labelEx($model,'cat_id'); ?>
                <!--
                //使用下拉菜单,实现添加产品或修改产品时,可以从下拉列表选择产品类别:以下为第5步
                //在_form这个VIEW页面中,使用CHtml::listDate方面,将分类信息语取出来。
                //$model:这个表示goods的model对象
                //cat_id:这个表示表单中提交出去的name
                //$category:这个表示从Goods模型中关联到的Category的模型数据
                //cat_id:这个表示下拉菜单使用的值
                //cat_name:这个表示form中显示出来的名字,实际用到的其实是cat_id
                -->
                <?php echo $form->dropDownlist($model,'cat_id',CHtml::listData($category, 'cat_id', 'cat_name'));?>
            
		<?php echo $form->error($model,'cat_id'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_sn'); ?>
		<?php echo $form->textField($model,'goods_sn',array('size'=>16,'maxlength'=>16)); ?>
		<?php echo $form->error($model,'goods_sn'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_name'); ?>
		<?php echo $form->textField($model,'goods_name',array('size'=>32,'maxlength'=>32)); ?>
		<?php echo $form->error($model,'goods_name'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'click_count'); ?>
		<?php echo $form->textField($model,'click_count',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'click_count'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'brand_id'); ?>
		<?php echo $form->textField($model,'brand_id',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'brand_id'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_number'); ?>
		<?php echo $form->textField($model,'goods_number',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'goods_number'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'market_price'); ?>
		<?php echo $form->textField($model,'market_price',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'market_price'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'shop_price'); ?>
		<?php echo $form->textField($model,'shop_price',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'shop_price'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'promote_price'); ?>
		<?php echo $form->textField($model,'promote_price',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'promote_price'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'promote_start_date'); ?>
		<?php echo $form->textField($model,'promote_start_date'); ?>
		<?php echo $form->error($model,'promote_start_date'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'promote_end_date'); ?>
		<?php echo $form->textField($model,'promote_end_date'); ?>
		<?php echo $form->error($model,'promote_end_date'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_desc'); ?>
		<?php echo $form->textField($model,'goods_desc',array('size'=>60,'maxlength'=>255)); ?>
		<?php echo $form->error($model,'goods_desc'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_small_pic'); ?>
		<?php echo $form->textField($model,'goods_small_pic',array('size'=>60,'maxlength'=>255)); ?>
		<?php echo $form->error($model,'goods_small_pic'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_big_pic'); ?>
		<?php echo $form->textField($model,'goods_big_pic',array('size'=>60,'maxlength'=>255)); ?>
		<?php echo $form->error($model,'goods_big_pic'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_sale'); ?>
		<?php echo $form->textField($model,'is_sale'); ?>
		<?php echo $form->error($model,'is_sale'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_delete'); ?>
		<?php echo $form->textField($model,'is_delete'); ?>
		<?php echo $form->error($model,'is_delete'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_best'); ?>
		<?php echo $form->textField($model,'is_best'); ?>
		<?php echo $form->error($model,'is_best'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_new'); ?>
		<?php echo $form->textField($model,'is_new'); ?>
		<?php echo $form->error($model,'is_new'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_hot'); ?>
		<?php echo $form->textField($model,'is_hot'); ?>
		<?php echo $form->error($model,'is_hot'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_promote'); ?>
		<?php echo $form->textField($model,'is_promote'); ?>
		<?php echo $form->error($model,'is_promote'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'add_time'); ?>
		<?php echo $form->textField($model,'add_time'); ?>
		<?php echo $form->error($model,'add_time'); ?>
	</div>

	<div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
	</div>

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

</div><!-- form -->


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值