Yii dropDownlist 与CHtml:listData实例详解

jerry Yii 2015年08月23日 收藏

1.ProductController(Controller)

  1. public function actionCreate()
  2.  {
  3.   $model=new Product;
  4.   // Uncomment the following line if AJAX validation is needed
  5.   // $this->performAjaxValidation($model);
  6.   if(isset($_POST['Product']))
  7.   {
  8.    $model->attributes=$_POST['Product'];
  9.    if($model->save())
  10.     $this->redirect(array(‘view’,'id’=>$model->id));
  11.   }
  12.   $category=Category::model()->findAll();
  13.   $this->render(‘create’,array(
  14.    ’model’=>$model,
  15.    ’category’=>$category,
  16.   ));
  17.  }

2.product.php(Model,主要语句)

  1. public function relations()
  2.  {
  3.   // NOTE: you may need to adjust the relation name and the related
  4.   // class name for the relations automatically generated below.
  5.   return array(
  6.   category’=>array(self::BELONGS_TO,’Category’,'category_id’),
  7.   );
  8.  }
  9.  /**
  10.   * @return array customized attribute labels (name=>label)
  11.   */
  12.  public function attributeLabels()
  13.  {
  14.   return array(
  15.    ’id’ => ‘ID’,
  16.    ’name’ => ‘Name’,
  17.    ’category_id’ => ‘Category’,
  18.   );
  19.  }

3.create.php(视图文件,主要语句)

  1. <?php echo $this->renderPartial(‘_form’, array(‘model’=>$model,’category’=>$category)); ?>

4._form.php

  1. <div>
  2.   <?php echo $form->labelEx($model,’category_id’); ?>
  3.   <?php echo $form->dropDownlist($model,’category_id’,CHtml::listData($category,’id’,'name’)); ?>
  4.     <?php echo $form->error($model,’category_id’); ?>
  5.  </div>