i've some troubles with Select2 kartik plugin for yii2.
I set up my plugin with Ajax Loading and, in my create view works fine, so i can select multiple value and save it on database.
When i show the update view i want to set visible the value that i've saved in my database but it show me only a gray rectangle with x icon.
This is what i've tried.
echo $form->field($model, 'lista_art')->widget(Select2::classname(), [
'initValueText' => $art_list,// array of text to show in the tag for the selected items
'showToggleAll' => false,
'options' => ['placeholder' => 'Select...',
'multiple' =>true,
'value' => $value, // array of Id of the selected items
],
'pluginOptions' => [
'tags' => true,
'tokenSeparators' => [',', ' '],
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['lista-articoli']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { console.log(markup);return markup; }'),
'templateResult' => new JsExpression('function(lista_art) { return lista_art.art_modello; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.art_modello; }'),
],
]);
And this is the result.
$art_list and $value are array's like this
$art_list = ['name1','name2'];
$value= ['id_name1','id_name2'];
If i inspect the code with browser inspector i find this
<li class="select2-selection__choice" title="name1">
<span class="select2-selection__choice__remove" role="presentation">×</span>
</li>
UPDATE
I'll find the error, and it is very trivial..
The error is here
'templateResult' => new JsExpression('function(lista_art) { return lista_art.art_modello; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.art_modello; }')
There is no lista_art.art_modello because the object for this element is inthe format id:id_name1 and text:name1 so changing the code like this it will work
'templateResult' => new JsExpression('function(lista_art) { return lista_art.text; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.text; }')
Hi guys thanks for responding me.
I found a solution for my problem and i'll post an answer for anyone who get same problem.
This is my Select2 Field in my view:
echo $form->field($model, 'lista_art')->widget(Select2::classname(), [
'initValueText' => $art_list,// array of text to show in the tag for the selected items
'showToggleAll' => false,
'options' => ['placeholder' => 'Seleziona un prodotto',
//'tags' => true,
'multiple' =>true,
'value' => $value, // array of Id of the selected items
'class' => 'validatej'
],
'pluginOptions' => [
'tags' => true,
'tokenSeparators' => [',' , ' '],
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['lista-articoli']),
'dataType' => 'json',
'data' => new JsExpression('function(params) {return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(data) {return data.text; }'),
'templateSelection' => new JsExpression('function (data) { return data.text; }'),
],
]);
The problem isn't here but in the function called by ajax
public function actionGetArt($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;//restituisco json
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select('art_cod AS id, art_modello AS text')
->from('art')
->where(['ilike', 'art_modello', $q]);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => Catalogo::find($id)->art_modello];
}
return $out;
}
In the line where i call select Sql
$query->select('art_cod AS id, art_modello AS text')
you have to set your id table an your text table(in my case art_modello) AS id and AS text accordly with the select2 widget. This is not specified in the docs so i'll have read the code and found this solution.
You can't set initValueText as an array.
See docs:
initValueText: string, the text to displayed in Select2 widget for the initial value. This is useful and applicable when you are using the widget with ajax loaded data AND/OR you are not providing the data. Check the ajax usage section for an example.
'initValueText' => $art_text, // set the initial display text
Use data instead:
'data' => $art_list,
Related
i'm got stuck for 2 days, i got confused how to render column usind yajra/laravel-datatable
i'm using postgre as database, and yajra/laravel-datatables as package.
i have query builder like this
$data = DB::select("SELECT * FROM get_list_count_amount_transaction('chat', 'done', '2019-03-01', '2021-12-31' )")[0];
which generates a value of object : (i use var_dump() to see the value)
{ ["list_data"]=> string(2171)
"[{"id":"44649ccd-9195-4964-b48c-ed2098077dc5","kd_join":1,"status":"done","booking_date":"2021-04-18","transaction_type":"chat","price":4000.00,"date_create":"2021-04-18T19:56:57"},
{"id":"e500d2c1-99ae-4436-8ecc-8073f4f05bba","kd_join":1,"status":"done","booking_date":"2021-03-20","transaction_type":"chat","price":10000.00,"date_create":"2021-03-19T21:41:41"}
]"
["count_transaction"]=> int(12)
["total_amount_transaction"]=> string(9) "160500.00"
}
i'm confused, how to render list_data into a table using datatble
this is my html builder function :
public function html()
{
return $this->builder()
->columns($this->getColumns())
->minifiedAjax()
->addAction(['width' => '200px'])
->addColumnBefore([
'defaultContent' => '',
'data' => 'DT_Row_Index',
'name' => 'DT_Row_Index',
'title' => 'No',
'render' => function () {
return 'function(data,type,fullData,meta){return meta.settings._iDisplayStart+meta.row+1;}';
},
'orderable' => false,
'searchable' => false,
'exportable' => false,
'printable' => true,
'footer' => '',
]);
}
protected function getColumns()
{
return [
['data' => 'transaction_type', 'name' => 'transaction_type', 'title' => 'Tipe Transaksi', 'orderable' => false],
['data' => 'status', 'name' => 'status', 'title' => 'Status', 'orderable' => false],
['data' => 'booking_date', 'name' => 'booking_date', 'title' => 'Tanggal Booking', 'orderable' => false],
['data' => 'price', 'name' => 'price', 'title' => 'Jumlah', 'orderable' => false],
];
}
}
Just grab the list_data, use json_decode and laravel collection to make your needed structure. Try to use map, filter, mapWithKeys or whatever suitable.
For Instance:
collect(json_decode($listData))->mapWithKeys(function($item)){
//
}
I'm a new Yii2.I've this bug, I don't know how can I solve this problem.
Bug is very simple templateSelection called two time. this is my code.
if I submit somethings in select2, templateSelection called two time.
echo Select2::widget([
'name' => 'blogId',
'options' => ['placeholder' => 'Search for [![enter image description here][1]][1] ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'ajax' => [
'url' => Url::to(['/controller/action']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
'processResults' => new JsExpression($resultsJs),
],
'templateResult' => new JsExpression($formatRepo),
'templateSelection' => new JsExpression('function(params) { console.log("tst");}'),
],
]);
Thank you for your help.
I've found reponse myself by debuging select2.full.js
problem is right here.
just remove this code. it call two time because it's nested function.
this.$element.on('change.select2', function () { self.dataAdapter.current(function (data) {
//self.trigger('selection:update', {
data: data });
// });
});
i'm trying to use the Kartik Select2 Widget for my Yii2 project.
I'll use the Ajax Loading and everithing works find, but if i set the multiple option it gives me this error.
PHP Warning – yii\base\ErrorException array_combine(): Both parameters
should have an equal number of elements
This error is in Select2.php on this line
$this->data = $multiple ? array_combine((array)$key, (array)$val) : [$key => $val];
i think it's because the data attribute is missing, but if i add data attribute ajax doesn't work properly.
This is my view:
$form->field($model, 'lista_art')->widget(Select2::classname(), [
'initValueText' => "", // set the initial display text
//'data' => '',
'options' => ['placeholder' => 'Select a color ...',
//'multiple' =>true, // error here
],
'pluginOptions' => [
'tags' => true,
'tokenSeparators' => [',', ' '],
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['lista-articoli']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { console.log(markup);return markup; }'),
'templateResult' => new JsExpression('function(lista_art) { return lista_art.art_modello; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.art_modello; }'),
],
]);
Also tried to insert multiple option inside 'pluginOptions' array but doesnt work.
Is it possible to use multiple option with Ajax Loading?
P.s. I've check my developer toolbar and the response is correct, and gives me what i've expected.
You forgot to set data attribute
Sample how to use kartik select 2 with model and active form
$model->keywords = [1, 2]; // NOTE THIS IS AN ARRAY of keys
$form->field($model, 'keywords')->widget(Select2::className(), [
'pluginOptions' => [
'tags' => true,
'multiple' =>true,
],
'data' => [1=>'keyword1', 2=>'keyword2', 3=>'keyword3'],
])
Update
Try to set up data as empty array like
'data' => []
I am stuck with a problem that don't know how to get the value from url. I am new in backpack. please help me with this.....
I want my details on a view based on the id that is passed from another view, how to implement this?? this is my code
Adcontroller.php
public $crud = array(
"model" => "App\Larapen\Models\Ad",
"entity_name" => "ad",
"entity_name_plural" => "ads",
"route" => "admin/ad",
"reorder" => false,
"add_permission" => false,
"columns" => [
[
'name' => 'reviewed',
'label' => "Reviewed",
'type' => "model_function",
'function_name' => 'getReviewedHtml',
],
],
"fields" =>[
[ // Hidden
'name' => 'id',
'label' => "id",
'type' => 'hidden'
],
],
);
Ad.php(model)
public function getReviewedHtml()
{
if ($this->reviewed == 1) {
return '<i class="fa fa-check-square-o" aria-hidden="true"></i><span> Reviews</span>';
} else {
return '<i class="fa fa-square-o" aria-hidden="true"></i>';
}
}
route.php
CRUD::resource('ad', 'AdController');
CRUD::resource('reviews', 'AdReviewController');
AdReviewController.php
public $crud = array(
"model" => "App\Larapen\Models\AdReviews",
"entity_name" => "Reviews",
"entity_name_plural" => "Reviews",
"route" => "admin/reviews",
"reorder" => false,
"add_permission" => false,
// *****
// COLUMNS
// *****
"columns" => [
[
'name' => 'created_at',
'label' => "Date",
],
[
'name' => 'user',
'label' => "User",
'type' => "model_function",
'function_name' => 'getuser',
],
[
'name' => 'review',
'label' => "Review",
],
],
"fields" => [
[
'name' => 'review',
'label' => "Review",
],
],
);
public function __construct()
{
//$this->crud['update_fields'][1]['options'] = $this->adType();
// $this->crud['update_fields'][2]['options'] = $this->categories();
parent::__construct();
}
public function store(StoreRequest $request)
{
return parent::storeCrud();
}
public function update(UpdateRequest $request)
{
return parent::updateCrud();
}
}
"I want to display the reviews based on each Ads now it display all the reviews from the review table, where should i write the condition???"
Waiting for a response...............
I presume you have one-to-one or one-to-many relationships between AdReview and Review, defined both in your Review model and your AdReview model.
If so, you can add:
a "select" column in your table view;
a "select" / "select2" field in your create/update views;
That will show the entity it's "connected" with and allow the user to edit it.
Is this what you were trying to achieve?
I've a question about yii2 kartik-v widget select 2.
the widget is attached to a field in my view
<?=
$form->field($model, 'address')->widget(Select2::className(), [
'options' => ['placeholder' => 'Inserta an address '],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => Url::to(['register/addresses']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(address) { return address.name; }'),
'templateSelection' => new JsExpression('function (address) { return address.name; }'),
],
'pluginEvents' => [
"select2:select" => "function(e) {
// some function
}",
],
]);
?>
if in my controller i want to set to this field a value
like: $model->address = "Some Value"; on the view the field remain blank
what can i do?
UPDATE!
As the documentation say i can use the option: 'initValueText' if i use the ajax version of this plugin. So i've tried to set 'initValueText' => $model->address, but the result is the same
hey i had the same issue with #ajax neither placeholder nor initValueText were showing
what i did was this
<?php
$product = $model->product_id ? Product::findOne($model->product_id)->name : 'select ....';
echo $form->field($model, 'product_id')->widget(Select2::classname(), [
'initValueText' => $product, // set the initial display text
// 'options' => ['placeholder' => 'select ....'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => Url::to(['list']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(product_id) { return product_id.name; }'),
'templateSelection' => new JsExpression('function (product_id) { return product_id.name; }'),
],
]);?>
if the model is new 'select ....' is shown else the product's name
since "options" is not doing much either
hope this will be hopeful to someone
The problem was this:
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(address) { return address.name; }'),
'templateSelection' => new JsExpression('function (address) { return address.name; }'),
It seems that this plugin want a specific return for the keys 'templateResult' and 'templateSelection'.
I've modified the JsExpression return value with address.text (instead of adress.name) as the guide examples : Link.
And then i've modified also the PHP method that return the results:
public function actionAddresses($q = NULL, $id = NULL)
{
Yii::$app->response->format = Response::FORMAT_JSON;
$results = array();
if (!is_null($q)) {
$geocoder = new GeocodingClient();
$request = $geocoder->lookup(['address' => $q]);
$counter = 1;
foreach ($request['results'] as $key => $value) {
$results['results'][] = [
'id' => $counter,
'text' => $value['formatted_address'], // Instead of 'name'
'coordinate' => $value['geometry']['location']
];
$counter++;
}
}
return $results;
}
I hope this may help someone with a similar problem.
Its bit late.. but i too had same problem.. i resolved it by assigning value
<?=
$form->field($model, 'address')->widget(Select2::className(), [
'initValueText' => $model->address,
'value' => $model->address,
'options' => ['placeholder' => 'Inserta an address '],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => Url::to(['register/addresses']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(address) { return address.name; }'),
'templateSelection' => new JsExpression('function (address) { return address.name; }'),
],
'pluginEvents' => [
"select2:select" => "function(e) {
// some function
}",
],
]);
?>
you use kartik select2, in controller you have set a value (id/ids) and name values for 'initValueText'
$model->id = 1; // or if arrays [1,3,4,5]
$username = User::find()->select('name')->where('id' => $model->id)->scalar();
and in view kartik select2
$form->field($model, 'username')->widget(Select2::className(), [
'initValueText' => $username;
...
I was facing same problem. Then I tried value key into the options and it worked.
<?php
echo $form->field($model, 'test')->widget(Select2::classname(), [
//'data' => ['test', 'test2'],
'initValueText'=>['test','test2'],
'options' => ['multiple' => true, 'value'=>['1','2']],
'pluginOptions' => [
'multiple' => true,
'allowClear' => true,
'minimumInputLength' => 1,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => '...',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (m) { return m; }')
?>
Hope It'll be helpful for someone.
I fix this solution by using trigger function. In below method we can set default value in kartik select2 widget.
$('#id').val(11).trigger('change'); //in val() mention the hash value of your select2 list