下拉列表使用组件功能

在 MyComponent.php 中创建函数

    namespace app\components;

    use Yii;
    use yii\base\Component;
    use yii\base\InvalidConfigException;
    use yii\helpers\Url;
    use yii\helpers\ArrayHelper;
    
    use app\models\User;
    
        class MyComponent extends Component
        {
        
          // Function return list of  id & user Names,used for dropdownlist
          public function getUserID()
          {
            $code = User::find()->select('id,name')
            ->where(['is_deleted'=>'n'])
            ->all();
        
            $result = ArrayHelper::map($code, 'id', 'name');
            if($result)
                return $result;
            else
                return ["null"=>"No User"];
          }
        }

- >在 web.php 中注册组件

components' => [
        'mycomponent' => [
             'class' => 'app\components\MyComponent',
            ],
         ]

- >在你的视图中使用它

<?= $form->field($model, 'user_id')->dropDownList(Yii::$app->mycomponent->getUserID())?>