Helli我有简单的表格,在我的表格中插入数据,问题是我不知道如何: 1)获取所选下拉列表项的字符串值; 2)获取所选无线电元素的字符串值 3)像所选复选框的String arrray一样获得smthng; 这是表格
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'first_name') ?>
<?= $form->field($model, 'last_name') ?>
<?= $form->field($model, 'gender')->radioList([
1 => 'Male',
2 => 'Female'
]) ?>
<?= $form->field($model, 'faculty')->dropdownList([
1 => 'Faculty of Information Technology',
2 => 'Faculty of Math Science',
3 => 'Faculty of Ukrainian Literature',
4 => 'Faculty of Health'
]) ?>
<?= $form->field($model, 'languages')->checkboxList([
1 => 'Java',
2 => 'C++',
3 => 'C#',
4 => 'Python',
5 => 'PHP',
6 => 'Java Script'
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
ActiveRecord类
class Users extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'users';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['first_name', 'last_name', 'gender', 'faculty', 'languages'], 'required'],
[['first_name', 'last_name'], 'string', 'max' => 15],
[['gender'], 'string', 'max' => 7],
[['faculty'], 'string', 'max' => 20],
[['languages'], 'string', 'max' => 50],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'first_name' => 'First Name',
'last_name' => 'Last Name',
'gender' => 'Gender',
'faculty' => 'Faculty',
'languages' => 'Programming Languages',
];
}
public static function primaryKey()
{
return ['customer_id','group_id'];
}
}
所以问题是在接受表单后插入db中的值是所选值的索引,但我需要值
答案 0 :(得分:1)
1)要从下拉列表中获取字符串值,您应该使用字符串作为数组中的索引,例如:
<?= $form->field($model, 'faculty')->dropdownList([
'Faculty of Information Technology' => 'Faculty of Information Technology',
'Faculty of Math Science' => 'Faculty of Math Science',
'Faculty of Ukrainian Literature' => 'Faculty of Ukrainian Literature',
'Faculty of Health' => 'Faculty of Health'
]) ?>
2)在选定的无线电元素中采用相同的方式。
3)要获取已检查元素的数组,您应该在ActiveRecord类中创建额外的属性:
public $languagesIds = [];
并在视图中使用此:
<?= $form->field($model, 'languagesIds')->checkboxList([
1 => 'Java',
2 => 'C++',
3 => 'C#',
4 => 'Python',
5 => 'PHP',
6 => 'Java Script'
]) ?>
从帖子数据加载模型后,$model->languagesIds
将填充选中的值。如果您想拥有字符串数组,请将索引(1,2,3,4 ..)替换为字符串,如第1点和第2点所示。