问题描述:

I am currently using Yii2 with typeahead basic. I am trying to fetch data from the mysql table, which is 'staff_name'

Currently I am following the guide, and here is my code( i put everything in the view first for testing(model is present but nothing is defined in there),

$data = [

'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado',

'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',

'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',

'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',

'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',

'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',

'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',

'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',

'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'

];

<?php $form = ActiveForm::begin()?>

<?=$form->field($model, 'staff_name')->widget(TypeaheadBasic::classname(), [

'data' => $data,

'options' => ['placeholder' => 'Filter as you type ...'],

'pluginOptions' => ['highlight'=>true],

]);?>

<?php ActiveForm::end(); ?>

It works fine when I hardcoded like this. But I need help on how to fetch the staff_name column data inside the mysql table. I tried something like: $data = [StaffMain::find()->all()]; but I get a 'null' in the textinput field as I type.

EDIT: Based on the scaisEdge answer, I had to change the query a bit.

$data = Yii::$app->db->createCommand('SELECT staff_name FROM staff_main')->queryColumn();

OR

$data = StaffMain::find()->select(['staff_name'])->asArray()->column();

网友答案:

If you need only populate the $data with the resulf of StaffMain model column staff_name you should use

<?php $form = ActiveForm::begin()?>
   <?=$form->field($model, 'staff_name')->widget(TypeaheadBasic::classname(), [
      'data' => StaffMain::find()->select('staff_name')->asArray()column(),
       'options' => ['placeholder' => 'Filter as you type ...'],
      'pluginOptions' => ['highlight'=>true],
  ]);?>
<?php ActiveForm::end(); ?>

or

$data = StaffMain::find()->select('staff_name')->asArray()column();

<?php $form = ActiveForm::begin()?>
   <?=$form->field($model, 'staff_name')->widget(TypeaheadBasic::classname(), [
     'data' => $data,
     'options' => ['placeholder' => 'Filter as you type ...'],
     'pluginOptions' => ['highlight'=>true],
]);?>
相关阅读:
Top