Yii2 DropDownList 全名

Yii2 DropDownList with full names

我正在尝试用此人的全名填充 Yii2 中的下拉列表,名字和姓氏在我的数据库中的不同列中。

我个人table

...

在我的 Person.php 模型中,我有

public function getFullName()
{
    return $this->first_name . ' ' . $this->last_name;
}

这是我在 GridView 中取回全名的辅助函数,工作正常。但是我在填充下拉菜单时遇到问题。

    // Get person
    $person = Person::find()
                ->orderBy('last_name')
                ->asArray()
                ->all();

    // Person drop down
    $personMap = ArrayHelper::map($person, 'fullName', 'dep_id'); 

这样我在下拉列表中什么也得不到,但人员 ID 是正确的。那么我需要如何正确处理呢?

你不能那样使用 ArrayHelper::map() 因为 fullName 没有出现在模型属性中。

但是您可以指定闭包而不是属性名称来实现所需的结果:

$person = Person::find()
    ->orderBy('last_name')               
    ->all();

$personMap = ArrayHelper::map(
    $person,
    function ($person, $defaultValue) {
        return $person->getFullName();
    }
    'dep_id'
);

如果您应用 asArray(),您将无法调用模型方法,但您仍然可以像这样包含全名:

$person = Person::find()
    ->orderBy('last_name')               
    ->asArray()
    ->all();

$personMap = ArrayHelper::map(
    $person,
    function ($person, $defaultValue) {
        return $person['first_name'] . ' ' . $person['last_name'];
    }
    'dep_id'
);

我不建议使用它,因为它是获取全名的重复逻辑。

至于细节:在map()方法中$from$to参数getValue()方法将被调用()。如果您检查 official documentation 该方法,您会发现一些将 $key 指定为闭包的示例。

通常这样的列表也是这样形成的,反之亦然:由 id 索引的字符串变量。

在这种情况下,您可以将其作为 $items 传递以显示 drop-down list

在您的情况下,当模型集包含至少两个同名的人时,可能会出现一些问题。

要更改它,只需切换第二个和第三个参数即可。

//use yii\helpers\ArrayHelper;


//use app\models\Users;


//replace lastname with field you want to order by in your database  table

$person = Users::find()

->orderBy('LastName')               

->all();

$personMap = ArrayHelper::map(

    $person,'UserID',


    function ($person, $defaultValue)

       {
        return $person->getFullName();
      }

          );

       ?>
//replace UserID 

    <?= $form->field($model, 'UserID')->dropDownList(
$personMap, ['prompt'=>'[--select person--]',
        ]) 
?>  

//get getFullname function should placed in your model 

function getFullName()
{
     return $this->FirstName."".$this->LastName;
    }
//Firstname and lastname are the fields in your database