Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 Kartik-V Typeahead Basic autocomplete on name but store integer value

Updates have been made below

I am trying to use the Kartik-V Typeahead Basic widget with the Yii2 Framework.

The code below is working to display the required data, the user can search via the university name and it appears in the autocomplete list.

The issue is, the model needs to the university id, not the name. Thus the rules are this field can only store an integer and returns a validation error once you select one of the typeahead results.

<?= $form->field($model, 'university_id')->widget(TypeaheadBasic::classname(), [
    'data' => ArrayHelper::map(University::find()->all(),'id','uni_name'),
    'pluginOptions' => ['highlight' => true],
    'options' => ['placeholder' => 'Filter as you type ...'],
]); ?>

I am hoping someone can help me understand if there is a setting that needs to be changed so when saving, the user friendly 'uni_name' data is changed back to the uni 'id'.

UPDATE: I have gotten the code partly working thanks to "Insane Skull".

The new code is:

<?= $form->field($model, 'name')->widget(TypeaheadBasic::classname(), [
    'data' => ArrayHelper::map(University::find()->all(),'id','uni_name'),
    'pluginOptions' => ['highlight' => true],
    'options' => ['placeholder' => 'Filter as you type ...', 'id' => 'testID'],
    'pluginEvents' => [
        'typeahead:select' => new yii\web\JsExpression("function(event, ui) { $('#testing123').val(ui.item.id); }"),
    ]
]); ?>

<?= Html::activeHiddenInput($model, 'university_id', array ('id' => 'testing123'))?>

Now I am unfortunately getting the error: Method yii\web\JsExpression::__toString() must return a string value

like image 881
william Avatar asked Sep 18 '15 05:09

william


1 Answers

I would rather use Select2 instead of Typeahead, you are basically trying to implement the functionality that already exists on Select2 but using Typeahead.

<?= $form->field($model, 'university_id')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(University::find()->all(),'id','uni_name'),
    'options' => ['placeholder' => 'Filter as you type ...'],
]); ?>
like image 73
marche Avatar answered Oct 31 '22 20:10

marche