简体   繁体   English

如何在DropDownList Yii2小部件上获取选定的文本?

[英]How to get selected text on a DropDownList Yii2 widget?

I'm trying to get a text selected from a DropDownList into my model but I keep getting the "index" value of de DropDownList (if I select the second item I get a 1). 我试图将从DropDownList中选择的文本输入到模型中,但我一直在获取de DropDownList的“索引”值(如果选择第二项,则得到1)。

I have an array like this: 我有一个像这样的数组:

Array ( [0] => some [1] => array [2] => for [3] => example ) 

And I try to get the selected text into the 'field' attribute of my model like this: 然后,我尝试将所选文本放入模型的“字段”属性中,如下所示:

<?= $form->field($model, 'field')-> dropDownList($array, ['prompt' => 'Select something']) ?>

The thing is that when I get my posted data in my controller I get the selected value (property) not the selected text. 问题是,当我在控制器中获取发布的数据时,我得到的是所选值(属性)而不是所选文本。 Lets say that I've selected 'example' then I get a '3' in my post variables. 假设我选择了“ example”,然后在post变量中得到了“ 3”。 How can I get the selected text instead of the index-like value? 如何获取所选文本而不是类似索引的值?

You can use value as key with the help of array_combine() : 您可以在array_combine()的帮助下将value用作键:

$array = [0 => "some", 1 => "array", 2 => "for", 3 => "example"];
$array = array_combine($array, $array);

Demo 演示

Output: 输出:

Array
(
    [some] => some
    [array] => array
    [for] => for
    [example] => example
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM