yii2在表单字段中添加额外的值

时间:2016-08-28 11:02:40

标签: php forms yii2

我在yii2项目中工作。我有一个带有文本字段的表单。形式中的一个字段是长度。目前我使用文本字段。我需要的是一个值的文本字段,后跟一个下拉框,我们可以选择厘米或英寸或像素。怎么做以及如何在控制器中获得价值。

1 个答案:

答案 0 :(得分:1)

您可以通过两种方式实现:

首先,

使用 html helper 类获取输入字段和一个 dropDownList ,或者您可以使用html创建简单的dropDownList

<?= $form->field($model, 'length')->textInput(['maxlength' => 255]); ?>
<?= Html::dropDownList('length_type', null,[ 'cm' => 'cm', 'inch' => 'inch', 'pixel' => 'pixel'],['class' => 'form-control','id'=>'length_type']) ?>

如果你想使用html helper类而不是导入Html类,如下所示

use yii\helpers\Html;

现在,在控制器中使用长度类型

if(isset($_POST['length_type']) && $_POST['length_type'] !=null)
{
  $len_type=$_POST['length_type'];
  // use this variable  according to yuor need
}

其次,

模型类中的

decalare varibale length_type

在视野中,

<?= $form->field($model, 'length')->textInput(['maxlength' => 255]); ?>
<?= $form->field($model, 'length_type')->dropDownList([ 'cm' => 'cm', 'inch' => 'inch', 'pixel' => 'pixel'], ['class' => 'priority_list']) ?>

在控制器中,您可以使用模型变量directry作为

$len=$model->length;
$len=$model->length_type;