How to populate Yii2 Autocomplete with AJAX call - autocomplete

I am trying to switch to Yii2 from Yii 1.1. This was source attribute of TextAreaJuiAutoComplete widget
'source'=>"js:function(request, response) {
$.getJSON('".$url"', {
term: extractLast(request.term)
}, response);
}",
This is not working in Yii2 with yii\jui\AutoComplete anymore. Can anyone give me a hint what is the cause? Underlying JavaScript objects should be the same.
If I put following code it works, but I want to use ajax calls instead.
'source' => [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ],

Try this:
use yii\web\JsExpression;
.....
.....
'source'=>new JsExpression("function(request, response) {
$.getJSON('".$url."', {
term: request.term
}, response);
}"),

Try this:
AutoComplete::widget([
'name'=>'myacfield',
'clientOptions' => [
'source' => Url::to(['autocomplete']),
'minLength'=>'2',
],
'options'=>[
'class' => 'form-control'
]
]);
But your AutoComplete action must return a one dimensional array like
...
$rs = Yii::$app->db->createCommand($sql)->queryAll();
$row_set = [];
foreach ($rs as $row)
{
$row_set[] = $row['name']; //build an array
}
echo json_encode($row_set); //format the array into json data

Examle with like.
Controller:
public function actionSearch($term)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$rs = Cure::find()->where(['like', 'name_uz', $term])->all();
if($rs !=null){
$row_set = [];
foreach ($rs as $row)
{
$row_set[] = $row->name_uz; //build an array
}
return $row_set;
}else{
false;
}
}
In view:
<? use yii\jui\AutoComplete;?>
<?= AutoComplete::widget([
'model' => $model,
'attribute' => 'country',
'options' => ['class' => 'form-control'],
'clientOptions' => [
'source' => Url::to(['cure/search']),
'minLength'=>'2',
],
]); ?>

Related

Magento 2 ; Unable to pass custom params into the Save Button Of a UI Form

I want to pass a value/params via the save button of my ui adminform.
i tried this:
public function getButtonData()
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('Magento\Framework\App\RequestInterface');
$id = $request->getParam('id');
return
[
'label' => __('Save'),
'class' => 'save primary',
'on_click' => '',
'sort_order' => 80,
'data_attribute' => [
'mage-init' => [
'Magento_Ui/js/form/button-adapter' => [
'actions' => [
[
'targetName' => 'thechateau_magenest_bookable_save',
'actionName' => 'save',
'params' => [
true,
['multidome_id' =>$id],
]
]
]
]
],
]
];
}
I can indeed see the values in the save button of the phtml page.
<button id="save" title="Save" type="button" class="action- scalable save primary" data-mage-init="{"Magento_Ui\/js\/form\/button-adapter":{"actions":[{"targetName":"thechateau_magenest_bookable_save","actionName":"save","params":[true,{"multidome_id":"1"}]}]}}" data-ui-id="save-button" >
<span>Save</span>
</button>
however when i try to retreive these values it comes up null.
$request = $this->_objectManager->create('Magento\Framework\App\RequestInterface');
$multiDome = $request->getParam('multidome_id');
I also tried to add it as part of the URL of the save button but it does not even show up on this:
public function getSaveUrl()
{
return $this->getUrl('*/*/save',['param'=>'value']);
}

fuction() not working in Detailview yii2

When i am going to show user details in Detailview than it throws:
htmlspecialchars() expects parameter 1 to be string, object given
Below is my code for Detailview:
view.php
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'userID',
'userEmail:email',
'userName',
'userMobile',
'userBirthDate',
'userGender',
[
'attribute' => 'interestName',
'format' => 'raw',
'label' => 'Interest',
'value' => $model->getUserinterest(),
],
'userStatus',
'userType',
],
]);
?>
function getUserinterest() {
foreach ($model->userinterest as $userinterest) {
$interestNames[] = $userinterest->interestName;
}
return implode("\n", $interestNames);
}
Since version 2.0.11 value can be defined as closure. Upgrade Yii version to developer version 2.0.11+ and it will work.
Follow the final answer as below:
view.php
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'userID',
'userEmail:email',
'userName',
'userMobile',
'userBirthDate',
'userGender',
[
'attribute' => 'interestName',
'format' => 'raw',
'label' => 'Interest',
'value' => $model->getviewinterest(),
],
'userStatus',
'userType',
],
]);
?>
Users.php(Model)
public function getviewinterest()
{
foreach ($this->userinterest as $userinterest)
{
$interestNames[] = $userinterest->interestName;
}
if(!empty($interestNames)){
return implode("<br/>", $interestNames);
}else{
return "(not set)";
}
}

yii2: Undefined variable: model

I am just starting Yii2 framework.
I want to create a dropdown list which is 1 to 10 and a submit button
Once select the option and click the button should go to next page to show the number I choose.
In my view file : index.php
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'QTY')->dropDownList(range(1, 10)) ?>
<?= Html::submitButton('Buy', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
Then when I go to the page it gave me 'Undefined variable: model' at dropdown list there.
What should I do to make it correct?
And what is the different between Html and CHtml?
Thanks.
this code is form.php not index.php.
because we can see, there are active form.
your model is undefined maybe you write the wrong code
this is example of controller index.php
public function actionIndex()
{
$searchModel = new PersediaanBarangSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Html and Chtml is the same
in Yii1=CHtml
in Yii2=Html
This is ment to be pagination? If yes use default functionality of the grid view.
This goes to controller:
$query = Post::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC,
'title' => SORT_ASC,
]
],
]);
return $this->render('path_to_view',['dataProvider'=>$provider]);
Read more
This goes to view:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
'created_at:datetime',
// ...
],
]);
Read more
Actually you model is not loaded, Please check below example.
public function actionIndex($id = Null)
{
$data=array();
$data['model'] = !empty($id) ? \app\models\YourModel::findOne($id) : new \app\models\YourModel();
return $this->render('index', $data);
}

Yii2-advanced : dataProvider

I want to increment my dataProvider in siteController. That is, at each iteration, my dataProvider should be incremented by 1 & renamed as dataProvider1,dataProvider2,dataProvider3,....& so on.
I tried to append $i to dataProvider, but it says 'dataProvider can't be converted to String...!'
My actionIndex is as follows :
public function actionIndex()
{
$query = new \yii\db\Query;
for ($i = 1; $i <= 20; $i++) {
$query->select('*')->from('business_main_categories')->where(['bmc_id' => $i]);
$query->createCommand();
$dataProvider.$i = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
]);
return $this->render('index', [
'dataProvider' => $dataProvider.$i,
]);
}
}
And, I also want to user that dataProvider in my 'index.php' with iterations; I tried to insert a for loop & written all statements in 'echo', but I'm unable to get it done.
My way to access it in 'index.php' is as follows :
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => '',
'columns' => [
[
'attribute' => 'bmc_image',
'format' => 'html',
'label' => '',
'value' => function ($data) {
return Html::img($data['bmc_image'],
['width' => '190px']);
},
],
]
]); ?>
Please help me to solve my issue.
I solved my problem without using gridview. As follows -
My SiteController -
public function actionIndex()
{
$searchModel = new BusinessMainCategoriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize = $dataProvider->getTotalCount(); //-1 : disable
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
using this code I get all records in dataProvider from my db.
(Note that, I'm using ActiveDataProvider in my 'BusinessMainCategoriesSearch' model)
And, my index.php is -
<?php
$m = $dataProvider->getModels();
foreach ($m as $dp) {
echo "<img src = '".$dp['bmc_image']."' />";
echo '<center><font color = "white">'.$dp['bmc_name'].'<font/></center>';
} ?>
It worked great for me & it's a easiest way to do so.

how to pass variables "$tid, $id" into raw function?

when i call $id and $tid in raw function to fetch some data from sub document of mongodb collection it show me an error these two variables are undefined($tid,$id)?
<?php
$id=IntValue;
$tId=IntValue;
if($tId==0)
{
$maxPlayers=0;
}
else
{
$result = DB::collection('PrizeDistributionTemplate')->raw(function($collection)
{
return $collection->aggregate(array(
array(
'$match' => array( 'id' => $id,'templates.tId' => $tid)
),
array( '$unwind' => '$templates' ),
array(
'$match' => array( 'id' => $id,'templates.tId' => $tid)
),
));
});
$result=json_decode(json_encode($result),true);
$maxPlayers=$result['result'][0]['templates']['maxPlayers'];
$maxPlayers=intval($maxPlayers)+2;
}
?>
When you use a callback function in PHP, the function as it own scope and can't access variables from outside of it's scope.
$foo = true;
DB::collection('something')->raw(function ($collection) {
echo $foo;// $foo is undefined here, this create an error
});
echo $foo;// here it work
But you can feed your callback with variables using the PHP use keyword:
$foo = true;
DB::collection('something')->raw(function ($collection) use ($foo) {
echo $foo;// now it works
});
It will work great with bulk addition, this way you just need to create on array and pass it.
$temp = [
[
'item' => "envelopes"
],
[
'item' => "envelopesas"
],
[
'item' => "lala"
]
];
$userData = DB::table('log') - > raw(function ($collection) use($temp)
{
return $collection - > insertMany($temp);
});