Yii2 Kartik-V Typeahead Advanced Widget: How to store result in Mysql

时间:2015-11-12 10:55:17

标签: mysql json yii2 typeahead.js

Tearing my hair out at this point, hopefully someone can help me out!

I am using the Kartik-V Typeahead Advanced widget with Yii2.

The plugin works, in that the functionality is working perfectly on the page, I search and the results appear in the auto complete list.

Unfortunately, I am unable to store the result in my database. I am seeing an issue on the following line:

->where([ 'name' => $model->name ])//This variable is returning null

Am I trying to store the data incorrectly? I have tried everything I can think of, but I am sure someone here will come up with something better!

See below for the full code.

My controller:

public function actionIndex()
{
$model = new Member();

if ($model->load(Yii::$app->request->post())) {
    $test = Test::find()
            ->where([ 'name' => $model->name ])//This variable is returning null
            ->one();

    $test->updateCounters(['times_used' => 1]);
}

return $this->render('index', [
    'model' => $model,
]);

}

/*************
* Initial prefetch of results
*************/
public function actionPrefetchlist() {
$query = new Query;

$query->select('name')
      ->from('test_table')
      ->limit(10)
      ->orderBy('times_used');
$command = $query->createCommand();
$data = $command->queryAll();
$out = [];
foreach ($data as $d) {
    $out[] = ['value' => $d['name']];
}
echo Json::encode($out);
}

/*************
* Remote results
*************/
public function actionRemotelist() {
$query = new Query;

$query->select('name')
      ->from('test_table')
      ->where('name LIKE "%' . $q .'%"')
      ->limit(10)
      ->orderBy('times_used');
$command = $query->createCommand();
$data = $command->queryAll();
$out = [];
foreach ($data as $d) {
    $out[] = ['value' => $d['name']];
}
echo Json::encode($out);
}

The view file:

echo $form->field($model, 'name')->label(false)->widget(Typeahead::classname(), [
   'name' => 'name',
   'options' => ['placeholder' => 'Filter as you type ...'],
   'pluginOptions' => ['highlight'=>true],
   'dataset' => [
   [
        'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')",
        'display' => 'value',
        'prefetch' => Url::to(['prefetchlist']),
        'remote' => [
            'url' => Url::to(['remotelist']) . '?q=%QUERY',
            'wildcard' => '%QUERY'
        ]
   ]
   ]
]);

2 个答案:

答案 0 :(得分:0)

你在这里问一个新模型:

$model = new Member();

所以你得到一个空模型 所以$model->name是空的 如果您设置模型$model->name='test'; 比它将被填充,首先填写模型

答案 1 :(得分:0)

事实证明这是一个巨大的菜鸟错误。

如果其他人偶然发现类似内容,我会从模型中删除属性name" rules()"

我需要数据库中的整数,但我希望用户输入一个字符串(我会在控制器中将其转换)。从规则中删除它会破坏一切。

希望这有助于其他人:)