Yii 2.0 dropDownList没有填充数据库数据

时间:2015-03-25 13:27:39

标签: php yii yii2

尝试在我的视图中创建一个下拉列表,其中填充了数据库表中的数据" Category"。 然而,这不起作用,没有任何东西被填充。

控制器\ CasesController:

public function actionIndex()
{

    $searchModel = new CaseSearch();  
    $allCategory = new Category;
    $allCategory = Category::findAllCategories();

    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    $post_obj = Yii::$app->request->post();

    $category=1;
    if(isset($post_obj['CaseSearch']['category'])){
       $category = $post_obj['CaseSearch'];
       $dataProvider = $searchModel->searchByCategory($category);   
    }

    $searchModel->category = $category;

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
        'post' => $post_obj,
        'allCategory' => $allCategory
    ]);
}

模型\类别:

class Category extends \yii\db\ActiveRecord
{
public $id;
public $name;

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'Category';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['id'], 'integer'],
        [['name'], 'required'],
        //[['LastEdited', 'Published'], 'safe'],
        [['name'], 'string', 'max' => 45]
    ];
}

public static function findAllCategories()
{
    Category::find()->indexBy('id')->all();
    return self::find();


}

查看:

echo $form->field($searchModel, 'newcategory')
    ->dropDownList(
        $allCategory           // Flat array ('id'=>'label')

);

知道为什么这不起作用吗?

1 个答案:

答案 0 :(得分:0)

将这些更改为行

$allCategory = new Category;
$allCategory = Category::findAllCategories();

为:

$allCategory = Category::find()->all();

echo $form->field($searchModel, 'newcategory')
->dropDownList(
    $allCategory           // Flat array ('id'=>'label')
);

为:

echo $form->field($searchModel, 'newcategory')
          ->dropDownList(
              ArrayHelper::map($allCategory, 'id', 'name')
            )
?>