Yii2 kartik typeahead - get number of suggestions - widget

I'm using kartik's typeahead widget for Yii2 in a view:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus"
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { add_item(item.id); return false;}",
],
]);
How can i get the number of loaded suggestions after the remote dataset is retrieved to execute a javascript function like:
displaynumber(NUMBEROFSUGGESTIONS);

After checking through the source of kartiks widget i came up with the following solution:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus",
'id' => 'serial_product'
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => [
'url' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'ajax' => ['complete' => new JsExpression("function(response)
{
jQuery('#serial_product').removeClass('loading');
checkresult(response.responseText);
}")]
],
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { checkresult2(item); return false;}",
],
]);
where response.responseText is containing the response from server (json).
function checkresult(response) {
var arr = $.parseJSON(response);
console.log(arr.length);
}
With this function i can get then count of suggestions delivered from server.

Related

Update data in Kartik Detailview is not working

I've detail showed using Kartik Detail View. This widget has Edit inline function by clicking pencil icon button in top right side like this.
But then the table doesn't be editable :
And nothing happen, my data still the same, my update not success. It's possible to solve my problem? Thanks.
I have read the official guide and it looks identical:
https://demos.krajee.com/detail-view
This is my view code:
<?php echo DetailView::widget([
'model' => $modelAnagrafiche,
'responsive' => true,
'mode' => 'edit',
'enableEditMode' => true,
'buttons1' => '{update}',
'panel' => [
'type' => 'primary',
'heading' => 'Contratto' . ' : ' . $modelAnagrafiche >cognome_ragione_sociale . ' ' . $modelAnagrafiche->nome
],
'attributes' => [
[
'group'=>true,
'label'=>'Sezione Anagrafica',
'rowOptions'=>['class'=>'table-primary']
],
[
'columns' => [
[
'attribute' => 'cognome_ragione_sociale',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%']
],
[
'attribute' => 'nome',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true,
'type' => DetailView::INPUT_TEXT,
],
],
],
[
'columns' => [
[
'attribute' => 'codice_fiscale',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%']
],
[
'attribute' => 'partita_iva',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true
],
],
],
[
'columns' => [
[
'attribute' => 'tipo_documento',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%'],
'format' => 'raw',
'value' => $modelAnagrafiche->tipoDocumento,
],
[
'attribute' => 'numero_documento',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true
],
],
],
[
'columns' => [
[
'attribute' => 'data_nascita',
'displayOnly' => true,
'format' => 'date',
'type' => DetailView::INPUT_DATE,
'widgetOptions' => [
'pluginOptions' => ['format' => 'yyyy-mm-dd']
],
],
[
'attribute' => 'id_provincia_nascita',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%'],
'format' => 'raw',
'value' => $modelAnagrafiche->provinciaNascitaNome,
'label' => 'Provincia Nascita'
],
],
],
[
'columns' => [
[
'attribute' => 'id_comune_nascita',
'displayOnly' => true,
'format' => 'raw',
'value' => $modelAnagrafiche->comuneNascitaNome,
'label' => 'Comune Nascita'
],
],
],
],
]);
?>
This is the action in my controller:
public function actionUpdateAnagrafica()
{
$post = Yii::$app->request->post();
if (empty($post['Anagrafiche']['id'])) {
throw new NotFoundHttpException('Non esiste nessuna anagrafica.');
}
$modelAnagrafiche = Anagrafiche::findOne($post['Anagrafiche']['id']);
if ($modelAnagrafiche->load($post) && $modelAnagrafiche->save()) {
return $this->redirect(['view', 'id' => $modelAnagrafiche->id]);
} else {
return $this->render('update-anagrafica', [
'modelAnagrafiche' => $modelAnagrafiche,
]);
}
}
You have to remove all the displayOnly attributes.
According to the official guide:
displayOnly: boolean|Closure, if the input is to be set to as display
only in edit mode. If set to true, no editable form input will be
displayed, instead this will display the formatted attribute value.

Kartik Select2 error when try to use it with ajax

I've used kartiks select2 many time with ajax before. Now when I tried to implement it again this error is thrown in console:
jquery.js:3850 Uncaught Error: Option 'ajax' is not allowed for Select2 when attached to a <select> element.
There is no other errors. My implementation looks like:
<?php
echo $form->field($model, 'destination_from')->widget(Select2::class, [
'initValueText' => isset($_GET['MassManagementSearch']) ? $_GET['MassManagementSearch']['destination_from'] : [], // set the initial display text
'options' => [
'placeholder' => 'Destination from ...',
'multiple' => true
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['destination-from']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(city) { return city.text; }'),
'templateSelection' => new JsExpression('function (city) { return city.text; }'),
],
]); ?>
EDIT This my select2 version in composer.json:
"kartik-v/yii2-widget-select2": "#dev"

PendalF89/yii2-filemanager upload error. (Call to a member function saveAs() on null)

getting
Call to a member function saveAs() on null
error from ajax request while uploading image via filemanager.
Config:
...
'modules' => [
'site' => [
'class' => 'app\modules\site\Module',
],
'user' => [
'class' => 'app\modules\user\Module',
'controllerNamespace' => 'app\modules\user\controllers\frontend',
'viewPath' => '#app/modules/user/views/frontend',
],
'admin' => [
'class' => 'app\modules\admin\Module',
'layout' => '#app/views/layouts/admin',
'modules' => [
'user' => [
'class' => 'app\modules\user\Module',
'controllerNamespace' => 'app\modules\user\controllers\backend',
'viewPath' => '#app/modules/user/views/backend',
],
'pages' => [
'class' => 'bupy7\pages\Module',
'controllerNamespace' => 'bupy7\pages\controllers\backend',
'controllerMap' => [
'manager' => [
'class' => 'bupy7\pages\controllers\backend\ManagerController',
],
],
],
'gallery' => [
'class' => 'sadovojav\gallery\Module',
'basePath' => '#webroot/galleries',
],
'filemanager' => [
'class' => 'pendalf89\filemanager\Module',
// Upload routes
'routes' => [
// Base absolute path to web directory
'baseUrl' => '',
// Base web directory url
'basePath' => '#webroot',
// Path for uploaded files in web directory
'uploadPath' => 'uploads',
],
// Thumbnails info
'thumbs' => [
'small' => [
'name' => 'Small',
'size' => [100, 100],
],
'medium' => [
'name' => 'Medium',
'size' => [300, 200],
],
'large' => [
'name' => 'Big',
'size' => [500, 400],
],
],
],
],
],
...
actionUpload() in Controller
public function actionUpload()
{
$model = new Mediafile();
$routes = $this->module->routes;
$rename = $this->module->rename;
$model->saveUploadedFile($routes, $rename);
Yii::$app->response->format = Response::FORMAT_JSON;
$tagIds = Yii::$app->request->post('tagIds');
if ($tagIds !== 'undefined') {
$model->setTagIds(explode(',', $tagIds));
}
$bundle = FilemanagerAsset::register($this->view);
if ($model->isImage()) {
$model->createThumbs($routes, $this->module->thumbs);
}
$response['files'][] = [
'url' => $model->url,
'thumbnailUrl' => $model->getDefaultThumbUrl($bundle->baseUrl),
'name' => $model->filename,
'type' => $model->type,
'size' => $model->file->size,
'deleteUrl' => Url::to(['file/delete', 'id' => $model->id]),
'deleteType' => 'POST',
];
return $response;
}
Checked in the model,
$this->file = UploadedFile::getInstance($this, 'file');
in saveUploadedFile() returns null instead of object.
The problem is that the function saveUploadedFile() is been executed, the file is saved and the record is created in the database, but it returns error.

ZF3 zend-mvc generic route for many controllers in one module not working

I'm in ZF3, using the zend-mvc-skeleton and trying to configure a generic route that will match as many URLs as possible as I want to be able to create new controllers (including action methods of course), and have them immediately available.
The common approach described in the documentation is to write a route that matches the controller and action (same with ZF2).
Here is my module.config.php
namespace Application;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'default' => [
'type' => Segment::class,
'options' => [
'route' => '/application[/:controller[/:action]]',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
'constraints' => [
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
],
],
],
],
],
'controllers' => [/* ... */],
'view_manager' => [/* ... */],
],
It works like a charm for http://localhost/ and http://localhost/application calling the indexAction() function of the IndexController class inside the /module/Application/src/IndexController.php file.
However, it's not working when I try to get the fooAction() function in the same Controller (i.e. IndexController). It's not resolving correctly http://localhost/application/foo. and I get the following error:
A 404 error occurred
Page not found.
The requested controller could not be mapped to an existing controller class.
Controller:
foo (resolves to invalid controller class or alias: foo)
No Exception available
Same error if I try http://localhost/bar/foo to get the fooAction() in the barController.
Do you have any idea of what's wrong with this? Any help will be appreciated. Many thanks.
The route http://localhost/application/foo won't resolve to fooAction() in the index controller, since /foo in the URL will match the controller not the action. With that route setup you would need to visit http://localhost/application/index/foo.
To get it working you'll also need to make sure you have aliased your controller in the config, e.g. assuming you have:
'controllers' => [
'invokables' => [
'Application\Controller\Index' => \Application\Controller\IndexController::class
]
],
Then alias the controller so it matches the route parameter:
'controllers' => [
'invokables' => [
'Application\Controller\Index' => \Application\Controller\IndexController::class
],
'aliases' => [
'index' => 'Application\Controller\Index'
]
],
You'll need to add aliases that match the route parameter for each controller that isn't registered using the string you want for the route, e.g. a controller Namespace\Controller\BarController should be aliased to bar, etc.
I came here with similar problem. I have created two controllers in
"Application" module, and two in new module "Account" with the same name.
Application/Controller/IndexController
Application/Controller/OverviewController
Account/Controller/IndexController
Account/Controller/OverviewController
here are my modules.config.php
module/Account/config/module.config.php
return [
'router' => [
'routes' => [
'Account-account' => [
'type' => Segment::class,
'options' => [
'route' => '/account[/][:controller[/][:action][/]]',
'defaults' => [
'__NAMESPACE__' => 'Account\Controller',
'controller' => Account\Controller\IndexController::class,
'action' => 'index',
'locale' => 'en_us'
],
],
'may_terminate' => true,
'child_routes' => [
'wildcard' => [
'type' => 'Wildcard'
],
],
],
],
],
'controllers' => [
'factories' => [
Controller\IndexController::class => AccountControllerFactory::class,
Controller\OverviewController::class => AccountControllerFactory::class,
],
'aliases' => [
'index' => IndexController::class,
'overview' => OverviewController::class
]
],
and my
module/Application/config/module.config.php
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'Application-application' => [
'type' => Segment::class,
'options' => [
'route' => '/application[/][:controller[/][:action][/]]',
'defaults' => [
'__NAMESPACE__' => 'Application\Controller',
'controller' => Application\Controller\IndexController::class,
'action' => 'index',
'locale' => 'en_US'
],
],
'may_terminate' => true,
'child_routes' => [
'wildcard' => [
'type' => 'Wildcard'
],
],
],
],
],
'controllers' => [
'factories' => [
Controller\IndexController::class => IndexControllerFactory::class,
Controller\OverviewController::class => IndexControllerFactory::class,
],
'aliases' => [
'index' => IndexController::class,
'overview' => OverviewController::class,
]
],
With this configuration if aliases sections are commented there is a error message which says that there is invalid controller or alias (index/overview).
If there are aliases
route: "application/overview/index" goes into Account module.

Yii2: Select2, How to set initValueText in Gridview or Tabularform?

I need to set initValueText for Select2, which is in loop, like gridview or Tabularform. but I don't know how to set right value for each.
<?= TabularForm::widget([
'dataProvider' => $dataProvider,
'form' => $form,
'actionColumn' => false,
'checkboxColumn' => false,
'attributeDefaults' => [
'type' => TabularForm::INPUT_RAW,
],
'attributes' => [
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
'initValueText' => 'Selected Text' /// how can I set this in gridview or Tabularform?
],
],
]
]) ?>
Of course this is not working,
'initValueText' => function($model){
retur $model->textValue;
}
Any help would be appreciated.
Into tabularform if you want dynamic initValueText, you can use options closure in this manner:
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => function($model, $key, $index, $widget) {
$initValueText = empty($model['textValue']) ? '' : $model['textValue'];
return [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'initValueText' => $initValueText,
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
];
}
],
If for example attribute for city, so try this..
$cityDesc = empty($model->city) ? '' : City::findOne($model->city)->description;
'initValueText' => $cityDesc, // set the initial display text
For init value first assign value to $model attribute, if you should not assign so this attribute can take value.
Set the data parameter with the array including the option you want to show. For example for cities:
'options' => [
'data' => \yii\helpers\ArrayHelper::map(\app\models\City::find()->orderBy('id')->asArray()->all(), 'id', 'name'),
]
try to put inside the options instead ouside
'widgetClass' => Select2::className(),
'options' => [
'initValueText' => 'Selected Text'
Don't use isset it return error if more the one filter are use there.
[
'attribute' => 'ad_partner_id',
'value' => function ($model, $key, $index, $widget) {
return $model->partner->name;
},
'filter' => Select2::widget([
'model' => $searchModel,
'initValueText' => !empty($searchModel->ad_partner_id) ? $searchModel->partner->name : "",
'attribute' => 'ad_partner_id',
'options' => ['placeholder' => Yii::t('app', 'Search Partner ...')],
'pluginOptions' => ['allowClear' => true, 'autocomplete' => true,
'ajax' => ['url' => Url::base() . '/partner/get-partners',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
],
],
]),
],