1.ProductController(Controller)
public function actionCreate() { $model=new Product; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Product'])) { $model->attributes=$_POST['Product']; if($model->save()) $this->redirect(array(‘view’,'id’=>$model->id)); } $category=Category::model()->findAll(); $this->render(‘create’,array( ’model’=>$model, ’category’=>$category, )); }
2.product.php(Model,主要语句)
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( ’category’=>array(self::BELONGS_TO,’Category’,'category_id’), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( ’id’ => ‘ID’, ’name’ => ‘Name’, ’category_id’ => ‘Category’, ); }
3.create.php(视图文件,主要语句)
<?php echo $this->renderPartial(‘_form’, array(‘model’=>$model,’category’=>$category)); ?>
4._form.php
<div> <?php echo $form->labelEx($model,’category_id’); ?> <?php echo $form->dropDownlist($model,’category_id’,CHtml::listData($category,’id’,'name’)); ?> <?php echo $form->error($model,’category_id’); ?> </div>