Get selected row in Gridview yii2 selectioncolumn undefined error - javascript

i am getting error while selecting the rows and sending keys to controller.
In firebug on the button click event it displays error something like this
Uncaught TypeError: Cannot read property 'selectionColumn' of undefined
Here is my view code. its simple gridview
<?= Button::widget([
'label' => 'Message',
'options' => ['class' => 'btn-danger','id' => 'message'],
]);
?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'showOnEmpty'=>true,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
[
'attribute' => 'event_id',
'label' => 'Event Title',
'value' => 'event.title'
],
[
'attribute' => 'fullName',
'label' => 'Name',
'value' => 'users.fullname',
],
],
]);
?>
And here is the script i am using for onclick event
$script = '
jQuery(document).ready(function() {
btnCheck = $("#message");
btnCheck.click(function() {
var keys = $("#w1").yiiGridView("getSelectedRows");
alert(keys);
$.ajax({
type: "POST",
url: "'.\yii\helpers\Url::to(['/checkin/message']).'",
dataType: "json",
data: {keylist: keys}
});
});
});';
$this->registerJs($script, \yii\web\View::POS_END);
Which doesnt seems to work somehow on the button onclick event only instead of that if i use this script it works fine
$this->registerJs('
$(document).ready(function(){
$("#w1 input[type=checkbox]").click(function(){
var keys = $("#w1").yiiGridView("getSelectedRows");
$.ajax({
type:"POST",
url: "../message", // your controller action
dataType: "json",
data: {keylist: keys},
success: alert(keys)
});
});
});
Which is almost same but in the second script the ajax request is sent every time i click on the checkbox.
I want users to select the rows first and do action on the button click event
Hope you understand
I know its very common error but i tried different options and none of it seems to work
thank you.......

When you see an error message, the first thing you should check the line it is occurring at. There you will find the most important information. In our case, this is the line of code where the problem was:
var keys=$("#w1").yiiGridView("getSelectedRows");
Here, your code searched for an element having the id of w1 and called yiiGridView for that. Somewhere inside the function a selectioncolumn was referred, but the element whose member with that name was referred was not initialized properly.

Related

Fullcalendar - Problem with JSON DATA from External File

I would like to pull some events from the database. But first of all, one would be enough. I don´t know whats wrong cause i dont get any error messages...
JS:
$(document).ready(function() {
$('#calendar').fullCalendar({
locale: 'de',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: 'example.org/termine/PartnerTermine/&id=Xsdfeecvsdfgerger}'
});
});
If i am goin to call my events url, the answer is:
{"title":"Termin 1","start":"1575675560"}
And also, when i´m going to array it to
[{"title":"Termin 1","start":"1575675560"}]
the Event wont be showed, i dont know why.
The other php-file:
$meine_termine = array( // OR $meine_termine[] = array( - both doesnt work.
"title" => 'Termin 1',
"start" => '1575675560'
);
$json_termine = json_encode($meine_termine);
echo $json_termine;
exit;
The question is:
What is wrong and why doenst it pull the event from my file...
thanks a lot in advance.
Andre
Question closed, found a solution.
JS-Side:
eventSources: [
// your event source
{
url: 'https://example.org/termine/PartnerTermine/&id=hash_id',
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
}
}
]
php-side:
foreach ($termine AS $termin)
{
$meine_termine[] = array(
"allDay" => "",
"title" => $termin['title'],
"id" => $termin['title'],
"end" => "",
"start" => $termin['datum']
);
}
$json_termine = json_encode($meine_termine);
echo ($json_termine);
exit;
The Fields for the calendar has to be id, title, allday,end,start. works fine if the json will be echo'ed.

JS function is not defined. How to reference the function?

In my mvc view I have a DropDownList that gets values from a dictionary
<div class="InputPart">
#(Html.Telerik().DropDownListFor(model => model.PasportAddressRegionID)
.Name("ddlfRegions1")
.BindTo(new SelectList((IEnumerable<Dictionary>)ViewData["Regions"], "ID", "Title"))
.ClientEvents(e => e.OnChange("changeRegion1"))
.HtmlAttributes(new { style = "min-width:200px" }))
</div>
and I have JS function changeRegion1() that gets these values.
<script type="text/javascript">
function changeRegion1() {
var rgnId = $('#ddlfRegions1').data('tDropDownList').value();
$.ajax({
url: '#(Url.Action("_GetDistrict", "Staffs"))',
data: { regionId: rgnId },
type: "POST",
success: function (result) {
var combobox = $('#ddlfDistricts1').data('tDropDownList');
combobox.dataBind(result);
combobox.enable();
}
});
} </script>
I put the function in the same view, below all the code, but when run I got Uncaught ReferenceError: changeRegion1 is not defined. The function itself is OK, but it seems to me that event handler does not see it here.
So I just wonder what is wrong here? And how should I reference the function?
Any help is appreciated
Here is an example for the Kendu UI Dropdown list Event handling for ASP.Net and MVC. Compare to your code. The example shows Events, you call ClientEvents otherwise looks ok.
http://docs.telerik.com/aspnet-mvc/helpers/dropdownlist/overview
#(Html.Kendo().DropDownList()
.Name("dropdownlist")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select("dropdownlist_select")
.Change("dropdownlist_change")
)
)
<script>
function dropdownlist_select() {
//Handle the select event.
}
function dropdownlist_change() {
//Handle the change event.
}

TinyMCE Dynamic Buttons/Methods

I'm attempting to create a Wordpress plugin which allows you to easily add a dropdown menu with items in for inserting shortcodes. To do this, I need to 'hook' into TinyMCE, registering a custom plugin. My plan is to allow users to setup the shortcode menu items using a simple PHP array.
The following class is instantiated which registers a new button and the plugin script:
<?php
namespace PaperMoon\ShortcodeButtons;
defined('ABSPATH') or die('Access Denied');
class TinyMce {
public function __construct()
{
$this->add_actions();
$this->add_filters();
}
private function add_actions()
{
add_action('admin_head', [$this, 'print_config']);
}
public function print_config()
{
$shortcodes_config = include PMSB_PLUGIN_PATH . 'lib/shortcodes-config.php'; ?>
<script type='text/javascript' id="test">
var pmsb = {
'config': <?php echo json_encode($shortcodes_config); ?>
};
</script> <?php
}
private function add_filters()
{
add_filter('mce_buttons', [$this, 'register_buttons']);
add_filter('mce_external_plugins', [$this, 'register_plugins']);
}
public function register_buttons($buttons)
{
array_push($buttons, 'shortcodebuttons');
return $buttons;
}
public function register_plugins($plugin_array)
{
$plugin_array['shortcodebuttons'] = PMSB_PLUGIN_URL . 'assets/js/tinymce.shortcodebuttons.js';
return $plugin_array;
}
}
A user would create a PHP array like so (which is included in the above class and output as a javascript variable in the header):
<?php
return [
[
'title' => 'Test Shortcode',
'slug' => 'text_shortcode',
'fields' => [
'type' => 'text',
'name' => 'textboxName',
'label' => 'Text',
'value' => '30'
]
],
[
'title' => 'Test Shortcode2',
'slug' => 'text_shortcode2',
'fields' => [
'type' => 'text',
'name' => 'textboxName2',
'label' => 'Text2',
'value' => '30'
]
]
];
Finally, here's the actual plugin script:
"use strict";
(function() {
tinymce.PluginManager.add('shortcodebuttons', function(editor, url) {
var menu = [];
var open_dialog = function(i)
{
console.log(pmsb.config[i]);
editor.windowManager.open({
title: pmsb.config[i].title,
body: pmsb.config[i].fields,
onsubmit: function(e) {
editor.insertContent('[' + pmsb.config[i].slug + ' textbox="' + e.data.textboxName + '" multiline="' + e.data.multilineName + '" listbox="' + e.data.listboxName + '"]');
}
});
}
for(let i = 0; i <= pmsb.config.length - 1; i++) {
menu[i] = {
text: pmsb.config[i].title,
onclick: function() {
open_dialog(i)
}
}
}
console.log(menu);
editor.addButton('shortcodebuttons', {
text: 'Shortcodes',
icon: false,
type: 'menubutton',
menu: menu
});
});
})();
The button registers fine, the menu items also register fine but when it comes to click on to open up a modal window, I get this error:
Uncaught Error: Could not find control by type: text
I think it's something to do with the fact that the 'fields' is coming from a function which, for some reason, TinyMCE doesn't like - even though it's built correctly.
I had thought of doing this a different way - by creating a PHP file which outputs the correct JS but if I do that, I can't register it as a TinyMCE plugin when using the mce_external_plugins action hook.
I found another question which ran in to the same problem with no answer.
I've really hit a wall with this one, any help would be hugely appreciated!
Well, the typical thing happened - as soon as I post the question, I stumble upon the answer. Maybe I need to get myself a rubber desk duck?
Anyway, the clue is in the error message. Despite having looked at quite a number of tutorials which all suggest using 'text' as the control type, it's actually 'textbox'. I'm guessing this is a more recent change in TinyMCE and the tutorials I was looking at were a bit older.
I searched for yet another tutorial and found the answer staring me right in the face.

Zend_Dojo_Form Elements aren't proper working

Now I tried a bit around with Zend_Dojo_Form. The elements do not work like expected. The only element which is working is the checkBox.
To see for everybody here a screenshot:
Here a snippet of my formclass:
$this->addElement('DateTextBox','datum',array(
'label' => 'datum',
'datePattern' => 'dd-MM-yyyy',
'required' => 'true'
));
$this->addElement('TimeTextBox','zeit',array(
'label' => 'Uhrzeit',
'timePattern' => 'HH:mm',
'required' => 'true'
));
$this->addElement('CheckBox','test',array(
'label' => 'ja Nein',
'checkedValue' => 'yes',
'uncheckedValue' => 'nein',
'checked' => 'true'
));
$this->addElement('editor','test1',array(
'label' => 'Editor',
'plugins' => array('redo',
'undo','|','bold','italic','underline'),
'editActionInterval' => 2,
'height' => '100px'
));
My form extends Zend_Dojo_Form
I want to use date and time, don't mind I tried the others also to see if Zend_Dojo is found.
The date and time elements don't drop down on click, they just show like in the screenshot an X and a second row.
EDIT:
I have the dojo like follows in my application.ini
resources.view.helperPath.Zend_Dojo_View_Helper = "Zend/Dojo/View/Helper"
In my layout.phtml:
if ($this->dojo()->isEnabled()){
$this->dojo()->setCdnBase(Zend_Dojo::CDN_BASE_GOOGLE);
$this->dojo()->setCdnDojoPath(Zend_Dojo::CDN_DOJO_PATH_GOOGLE);
//$this->dojo()->requireModule('dijit.form.DateTextBox');
echo $this->dojo();
}
Do I need something else?
now it works, because I tried around to solve my errors the stylesheet was missing. So I added in my layout.phtml the stylesheet:
$this->dojo()->addStyleSheetModule('dijit.themes.tundra');

How to customize default data-confirm dialog box in Yii2 Gridview

I want to change the browser's default confirm dialog (data-confirm) box which comes on click of delete button.
I want to replace this with custom dialog box.
Following is my Gridview Code:
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
'account',
'code',
[
'class' => 'yii\grid\ActionColumn',
'header' => 'Action',
'template' => ' {update} {delete}',
'buttons' => [
'update' => function ($url, $model) {
return Html::a('<span class="btn-xs btn-primary">Edit</span>', $url, [
'title' => Yii::t('app', 'Edit'),
]);
},
'delete' => function ($url, $model) {
return Html::a('<span class="btn-xs btn-danger">Delete</span>', $url, [
'title' => Yii::t('app', 'Delete'),
//'data-confirm'=>'Are you sure you want to delete this item?',
'data-method'=>'POST'
]);
}
]
],
],
]);
?>
My JQuery code:
confirm: function (message, title, okAction) {
$("<div></div>").dialog({
// Remove the closing 'X' from the dialog
open: function (event, ui) {
$(".ui-dialog-titlebar-close").hide();
},
buttons: {
"Ok": function () {
$(this).dialog("ok");
okAction();
},
"Cancel": function () {
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
},
resizable: false,
title: title,
modal: true
}).text(message);
}
});
$(document).ready(function () {
$(".delete-row").click(function () {
$.confirm("Are you sure you want to delete this item?", "Production Control WF");
});
});
However the confirm dialog box appearing after implementation of this code but simultaneously its redirecting as well without clicking on any button.
Any help would be appreciated.
My answer contains two parts:
Replacing the default confirm-dialog
Using SweetAlert as the replacement
In the first part I explain the procedure to replace the default confirmation-dialog. This is the official and proper way to replace the Yii2-confirm-dialog globally.
In the second (optional) part I show how to use SweetAlert in Yii2 to replace the dialog.
Replacing the default confirm-dialog
Its pretty easy actually since the yii.js was overhauled since the launch of Yii2. You have to create a JS-file which you deploy to your web folder. This is done as follows:
1. Create folder for JS-File
In your web folder create a folder named js (or whatever name you wish)
2. Create the actual JS-File
In the folder from step 1 create a JS-file named for example yii_overrides.js
In this file you override the yii.confirm variable with your own handler-method.
My yii_overrides.js looks like this:
/**
* Override the default yii confirm dialog. This function is
* called by yii when a confirmation is requested.
*
* #param string message the message to display
* #param string ok callback triggered when confirmation is true
* #param string cancelCallback callback triggered when cancelled
*/
yii.confirm = function (message, okCallback, cancelCallback) {
swal({
title: message,
type: 'warning',
showCancelButton: true,
closeOnConfirm: true,
allowOutsideClick: true
}, okCallback);
};
The swal function calls the SweetAlert-Projects beautiful alert-box. Feel free to use whatever confirmation-style or -extension you want. SweetAlert looks awesome though...
3. Add JS-File to your Yii2-asset-bundle
Open assets\AppAsset.php and add your JS-File to assure it will be added to your HTML-header. Your file should look something like this now:
class AppAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'css/site.css',
];
public $js = [
//HERE!
'js/yii_overrides.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
//additional import of third party alert project
'app\assets\SweetAlertAsset',
];
}
Also make sure to include the asset of your custom alert-library if necessary. You can see this on the last line of the $depends-variable in the code above.
Adding SweetAlert
If you want to use SweetAlert as well, here is how you do it. There is a yii2-extension available providing you with an asset-bundle, but it is not current and uses old filenames. It therefore doesn't work. But its VERY easy to do it yourself.
1. Add dependency to SweetAlert
In your composer.json add
"bower-asset/sweetalert": "1.1.*"
to the required section and trigger composer update. You now have the necessary files.
2. Create SweetAlertAsset
Create a file named SweetAlertAsset.php next to your AppAsset in the assets-folder of your project. This is the content:
<?php
namespace app\assets;
class SweetAlertAsset extends \yii\web\AssetBundle
{
public $sourcePath = '#bower/sweetalert/dist';
public $css = [
'sweetalert.css',
];
public $js = [
'sweetalert.min.js'
];
}
Reference it within AppAsset as seen further above.
3. Done
Easy, wasn't it!?
Based on Sweet Alert 2.0 updates
i've modify the answer by PLM57
SweetAlert has changed callback functions to promises.
Here is the example override code for promise implementation:
/**
* Override the default yii confirm dialog. This function is
* called by yii when a confirmation is requested.
*
* #param string message the message to display
* #param string ok callback triggered when confirmation is true
* #param string cancelCallback callback triggered when cancelled
*/
yii.confirm = function (message, okCallback, cancelCallback) {
swal({
title: message,
icon: 'warning',
buttons: true
}).then((action) => {
if(action){
okCallback()
}
});
}
For more info on update from 1.x to 2.x, refer to this
Short and simple way.
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {update} {delete}',
'buttons' => [
'delete' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'data-method' => 'post',
'data-pjax' => 0,
'data-confirm' => 'Your message text'
]);
},
]
i think you only need to change $url to #
return Html::a('<span class="btn-xs btn-danger">Delete</span>', "#", [
'title' => Yii::t('app', 'Delete'),
//'data-confirm'=>'Are you sure you want to delete this item?',
'data-method'=>'POST'
]);

Categories