如何从下拉列表中获取值并将其用作表单提交ID

时间:2015-07-05 17:48:30

标签: php yii

我是yii的新手所以这可能或者可能没有多大意义。所以我想在表单上使用提交下拉列表值作为cat_id的id。

型号:

public function getCategories(){

    $user = Yii::app()->db->createCommand()
        ->select()
        ->from('categories')
        ->queryAll();

    return $user;

}

这来自类别模型。

控制器:

public function actionCreate()
{
    $model=new Posts;
    $categories = Categories::model()->getCategories();
    $model->cat  = CHtml::listData($categories, 'id', 'name');

    if(isset($_POST['Posts']))
    {
        $model->attributes=$_POST['Posts'];
        if($model->save())
            $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
        'categories'=>$model->cat,
        'model'=>$model,
    ));
}

查看:

<div class="row">
    <?php echo $form->labelEx($model,'cat_id'); ?>
    <?php echo CHtml::dropDownList('categories', $model, $model->cat, array('empty' => 'Select a category')); ?>
    <?php echo $form->error($model,'cat_id'); ?>
</div>

1 个答案:

答案 0 :(得分:1)

public function actionCreate()
{
    $model=new Posts;

    if(isset($_POST['Posts']))
    {
        $model->attributes=$_POST['Posts'];
        if($model->save())
            $this->redirect(array('view','id'=>$model->id));
    }

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

查看为

<div class="row">
    <?php echo $form->labelEx($model,'cat_id'); ?>
    <?php echo $form->dropDownList($model,'cat_id',CHtml::listData(Categories::model()->findAll(),'id','name'),array('empty' => 'Select a category')); ?>
    <?php echo $form->error($model,'cat_id'); ?>
</div>