下拉選單使用元件功能
在 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())?>