branch.php
<?PHPnamespaceApp\models;use Yii;/** * the Model Class for table "branch". * * @property integer $id * @property string $name **/classBranch extends \yii\db\activerecord{/** * @inheritdoc*/ Public Staticfunction TableName () {return 'Branch'; } /** * @inheritdoc*/ Publicfunction Rules () {return [ [['name'],'string','Max'= $], ]; } /** * @inheritdoc*/ Publicfunction Attributelabels () {return [ 'ID'='ID', 'name'='Name', ]; } Public Staticfunction Getkeyvaluepairs () {$sql='SELECT ID, name from'. Self::tablename ().'ORDER by name ASC'; returnYii:: $app->db->createcommand ($sql)Queryall (\pdo::fetch_key_pair); }}
Call
$model->getkeyvaluepairs () obtained as follows:
Display on front end:
<?phpuse yii\helpers\html;use yii\widgets\activeform;use app\models\branch;/*@var $this Yii\web\view*//*@var $model App\models\pos*//*@var $form yii\widgets\activeform*/? ><divclass="Pos-form"> <?php $form = Activeform::begin ();?> <?= $form->field ($model,'Serial')->textinput (['maxlength'=true])?> <?= $form->field ($model,'branch_id')->dropdownlist (Branch::getkeyvaluepairs ())?> <?= $form->field ($model,'is_enable')->checkbox ()?> <divclass="Form-group"> <?= Html::submitbutton ($model->isnewrecord?'Create':'Update', ['class'= $model->isnewrecord?'btn btn-success':'btn Btn-primary'])?> </div> <?php activeform::end ();?></div>
YII2 returns an array with the primary key ID as the key name