Yii2 - 使数据库结构下拉列表不是db中插入的数据
问题描述:
我有一个表单页面,其中一个字段被命名为type
,它是enum('lost', 'found')
,并且在这种形式下,我希望该字段仅作为下拉列表有这两个选项lost
和found
。的建议选项
之一视图Yii2 - 使数据库结构下拉列表不是db中插入的数据
<?= $form->field($model, 'type')->dropDownList(
$items,
['prompt'=>'']
利用这一点,这在控制器
$items = ArrayHelper::map(Ads::find()->all(), 'id', 'type');
但你知道它只是用在数据库,如果插入的数据我点击下拉列表,它会加载数据库中的所有丢失和找到的选项。
有什么办法可以告诉yii使用db结构和规则而不是数据吗?
我必须指出,在模型中我找不到任何指示枚举部分的规则,可以吗?这是为什么?
我用Gii创建这些。
public function rules()
{
return [
[['type', 'explanation', 'image', 'cost', 'province_id', 'address'], 'required'],
[['type', 'explanation', 'image', 'address'], 'string'],
[['cost'], 'integer'],
[['province_id'], 'string', 'max' => 20],
[['province_id'], 'exist', 'skipOnError' => true, 'targetClass' => Province::className(), 'targetAttribute' => ['province_id' => 'name']],
];
}
答
当申请类型是枚举和生成GII CRUD,警予在您的形式自动生成这种下拉列表中。
<?= $form->field($model, 'type')->dropDownList([ 'lost' => 'Lost', 'found' => 'Found', ], ['prompt' => '']) ?>
在模型类型为字符串:
public function rules()
{
return [
[['type'], 'string'],
这不是什么GII创造,这就是我做了点。 Gii创建正常的方式。像这样:'= $form-> field($ model,'type')?>' – Amir
你确定field'type'是枚举数据类型吗? –
是的,但正如我所说我不明白为什么在模型中没有任何与枚举部分有关。我已经在模型中发布了规则。 – Amir