How to get old and new value of dynamically generated checkbox column in agGrid - checkbox

I am using agGrid where the columns are dynamically created. My objective is to get the old value and new value after checking the checkboxes. I try to use "onCellValueChanged" but it didnt work. If I use "onCellClicked" then I am not getting Old Value and New Value.
For your understanding I want to mean by Old Value and New Value that if user checked then Old Value is false and New Value is true.
HTML
<ag-grid-angular class="ag-theme-balham" [gridOptions]="siteJobDeptGridOptions"
[rowData]="siteJobDeptRowData" [columnDefs]="siteJobDeptColDef" [paginationPageSize]=10 [domLayout]="domLayout"
(gridReady)="onGridReady($event)">
</ag-grid-angular>
TS File
export class SiteJobDeptConfigComponent implements OnInit {
ngOnInit() {
this.domLayout = "autoHeight";
this.getAllSiteJobConfig();
this.generateColumns();
}
onGridReady(params: any) {
params.api.sizeColumnsToFit();
params.api.resetRowHeights();
}
generateColumns()
{
let deptColDef = [];
let colSiteJob = {
field: 'SiteJobName', headerName: 'Site Job Name',resizable: true,
sortable: true, filter: true, editable: false,
}
this.siteJobDeptCommonService.getEntityData('getpublisheddepts')
.subscribe((rowData) => {
deptColDef.push(colSiteJob);
for(let dept of rowData)
{
deptColDef.push({
field: dept.DeptName, headerName: dept.DeptName, width:100,resizable: true,
cellClass: 'no-border',
cellRenderer : params => {
var input = document.createElement('input');
input.type="checkbox";
input.checked=params.data[dept.DeptName];
return input;
},
onCellValueChanged: this.siteDeptCellValueChanged.bind(this),
})
}
this.siteJobDeptColDef = deptColDef;
},
(error) => { alert(error) });
}
siteDeptCellValueChanged(dataCol: any) {
let checkedOldValue = "Old Check Value - " + dataCol.oldValue;
let checkedNewValue = "New Check Value - " + dataCol.newValue;
}
getAllSiteJobConfig()
{
let siteJobRowData = [];
this.siteJobDeptCommonService.getEntityData('getallsitedeptjob')
.subscribe((rowData) => {
for(let siteJobDetail of rowData)
{
for(let deptAllow of siteJobDetail.DeptAllow)
{
tempArray[deptAllow["DeptName"]] = deptAllow["IsAllow"];
}
siteJobRowData.push(tempArray);
}
this.siteJobDeptRowData = siteJobRowData;
},
(error) => { alert(error) });
}
}
The grid looks like below:-
Can you please help me how to get Old Data and New Data value from checkbox that is dynamically generated?

It should be "cellValueChanged" not "onCellValueChanged" in the column definition creation.
You can find here.

When you declare your method in the params object, there are oldValue and newValue properties that give the result that you are looking for:
onCellValueChanged: function(params) {
console.log(params.oldValue);
console.log(params.newValue)
}

Related

How to prevent the suggestedResult from collapsing after clicking result using SearchWidget?

How to prevent the suggestedResult from collapsing after clicking result using SearchWidget?
CodePen, copied below
// An open data address search API for France
const url = "https://api-adresse.data.gouv.fr/";
const map = new Map({
basemap: "streets-vector"
});
const view = new MapView({
container: "viewDiv",
map: map,
center: [2.21, 46.22], // lon, lat
scale: 3000000
});
const customSearchSource = new SearchSource({
placeholder: "example: 8 Boulevard du Port",
// Provide a getSuggestions method
// to provide suggestions to the Search widget
getSuggestions: (params) => {
// You can request data from a
// third-party source to find some
// suggestions with provided suggestTerm
// the user types in the Search widget
return esriRequest(url + "search/", {
query: {
q: params.suggestTerm.replace(/ /g, "+"),
limit: 6,
lat: view.center.latitude,
lon: view.center.longitude
},
responseType: "json"
}).then((results) => {
// Return Suggestion results to display
// in the Search widget
return results.data.features.map((feature) => {
return {
key: "name",
text: feature.properties.label,
sourceIndex: params.sourceIndex
};
});
});
},
// Provide a getResults method to find
// results from the suggestions
getResults: (params) => {
// If the Search widget passes the current location,
// you can use this in your own custom source
const operation = params.location ? "reverse/" : "search/";
let query = {};
// You can perform a different query if a location
// is provided
if (params.location) {
query.lat = params.location.latitude;
query.lon = params.location.longitude;
} else {
query.q = params.suggestResult.text.replace(/ /g, "+");
query.limit = 6;
}
return esriRequest(url + operation, {
query: query,
responseType: "json"
}).then((results) => {
// Parse the results of your custom search
const searchResults = results.data.features.map((feature) => {
// Create a Graphic the Search widget can display
const graphic = new Graphic({
geometry: new Point({
x: feature.geometry.coordinates[0],
y: feature.geometry.coordinates[1]
}),
attributes: feature.properties
});
// Optionally, you can provide an extent for
// a point result, so the view can zoom to it
const buffer = geometryEngine.geodesicBuffer(
graphic.geometry,
100,
"meters"
);
// Return a Search Result
const searchResult = {
extent: buffer.extent,
feature: graphic,
name: feature.properties.label
};
return searchResult;
});
// Return an array of Search Results
return searchResults;
});
}
});
// Create Search widget using custom SearchSource
const searchWidget = new Search({
view: view,
sources: [customSearchSource],
includeDefaultSources: false
});
// Add the search widget to the top left corner of the view
view.ui.add(searchWidget, {
position: "top-right"
});
3d version of code sample above
There is no documented way to do this through the API, as far as I can tell. But by adding the esri-search--show-suggestions to the SearchWidget, the suggestions will reappear:
const searchWidget = new Search({
view: view,
sources: [customSearchSource],
includeDefaultSources: false,
//autoSelect: false,
goToOverride: function(view, { target, options }) {
view.goTo(target, options);
const widget = document.querySelector('.esri-search__container')
widget.className += ' esri-search--show-suggestions'
},
});
Working CodePen here

Autocomplete off on Angular Directive for Date Picker

I have a directive for JQuery Date picker which injects date picker into input HTML control. This was developed by a previous developer and I am pretty new to Angular at this moment.
My question is that is there any way to prevent showing auto complete on all the date pickers that we inject via this directive?
export class DanialDatePickerDirective implements ControlValueAccessor {
constructor(protected el: ElementRef, private renderer: Renderer) { }
#Input() dateformat: string = "DD-MMM-YY";
#Input() ngModel: any;
#Input() setDefaultDate: boolean;
onModelChange: Function = () => { };
onModelTouched: Function = () => { };
writeValue(value: any) {
if (value) {
var ff = new Date(value);
$(this.el.nativeElement).datepicker("setDate", ff);
}
else {
$(this.el.nativeElement).datepicker("setDate", "");
}
}
registerOnChange(fn: Function): void {
this.onModelChange = fn;
}
registerOnTouched(fn: Function): void {
this.onModelTouched = fn;
}
onBlur() {
this.onModelTouched();
}
ngAfterViewInit() {
var self = this;
$(this.el.nativeElement).datepicker({
dateFormat: 'dd-M-y',
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true
});
if (this.setDefaultDate) {
var ff = new Date(self.ngModel);
setTimeout(function () {
$(self.el.nativeElement).datepicker("setDate", ff);
}, 200);
}
$(this.el.nativeElement).on('change', (e: any) => {
var model = e.target.value;
var date = null;
var monthstring = '';
if (model.indexOf("-") > 0){
monthstring = model.substring(model.indexOf("-") + 1, 5);
}
if (isNaN(parseInt(monthstring))) {
var tt = moment(model, "DD-MMM-YY").format('YYYY-MM-DD');
date = tt;
model = moment(model, "DD-MMM-YYYY").format('MM-DD-YYYY')
}
else {
date = moment(model, "DD-MM-YYYY").format('YYYY-MM-DD');
model = moment(model, "DD-MM-YYYY").format('MM-DD-YYYY')
}
$(".ui-datepicker a").removeAttr("href");
self.onModelChange(date);
self.writeValue(date.toString());
});
}
}
The only approach who works for me:
First, make sure to set autocomplete="off" on both, the input element itself and the parent form.
Second, make sure to assign an unique name to your input field always.
This can be achieved by simply generating a random number and using this number in the name of the field.
private getUniqueName() {
return Math.floor(Math.random() * Date.now());
}
Explanation:
In the past, many developers would add autocomplete="off" to their
form fields to prevent the browser from performing any kind of
autocomplete functionality. While Chrome will still respect this tag
for autocomplete data, it will not respect it for autofill data.
https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill.
So autocomplete="off" solves the autocomplete issue. But to solve the autofill you need to play dirty with the browser by changing the name of the input over an over again, that way the browser will never know how to autofill ;)

Shopware - Extjs - How to get value of the table element?

For some time I have a problem with my Shopware plugin. I extended article listWindow, added a column with checkbox. When customer clicks on checkbox I need to get article number that is in another column.
The way I first did it seems unreliable because it depends on position of a columns that can change.
//{block name="backend/article_list/view/main/grid"}
//{$smarty.block.parent}
//{namespace name=backend/article_list/main}
Ext.define('Shopware.apps.ArticleList.view.main.etsy_attribute.Grid', {
override: 'Shopware.apps.ArticleList.view.main.Grid',
...
getToolbar: function () {
var me = this, buttons;
buttons = me.callParent();
me.equaliseEtsyBtn = Ext.create('Ext.button.Button', {
text: 'Etsy equalise',
iconCls: 'sprite-drive-upload',
onClick: function () {
var i,
recPerPage = me.items.items[0].all.elements,
for (i = 0; i < recPerPage.length; i++) {
var productNumber = recPerPage[i].children[2].innerText;
if( recPerPage[i].children[numOfChildren].children[0].children[0].checked === true) {
Ext.Ajax.request({
method: 'POST',
url: '{url controller="someController" action="someAction"}',
params: Object.assign({
productNumber: productNumber
}),
success: function (res) {
//var parsed = JSON.parse(res.responseText);
},
failure: function () {
}
});
} else {
});
}
}
}
});
buttons.add(me.equaliseEtsyBtn);
return buttons;
},
})
What is bad here is this:
recPerPage[i].children[numOfChildren].children[0].children[0].checked === true
And similar lines. How to get value I need in some smarter and more accurate way?
Alse tried with .down and .up
Please give me some direction!

customizing ag-grid to set a max number of selectable rows

I am trying to customize a data table using ag-grid in my Angular 1.5 based project. The customization is that the user is allowed to select a maximum number of rows in the table, for example, the maximum is 2.
I have the following code by using node.setSelected(false) that I found in the documentation page here, but I got the error: node.setSelected is not a function when the selection exceeds the maximum of 2.
var gridOptions = {
columnDefs: columnDefs,
rowSelection: 'multiple',
onRowSelected: onRowSelected
};
function onRowSelected(event) {
var curSelectedNode = event.node;
var selectionCounts = vm.gridOptions.api.getSelectedNodes().length;
if (selectionCounts > 2) {
var oldestNode = vm.gridOptions.api.getSelectedNodes()[0]; // get the first node, to be popped out
oldestNode.setSelected(false); // causes the above 'not a function' error
}
}
Does anyone know what might be wrong with ag-grid for its setSelected() API? or any better way to do this customization?
it turns out that setSelected(false) method is outdated in its current ag-grid API, and I found that I can use deselectIndex() method to deselect the oldest node:
if (selectionCounts > 2) {
vm.gridOptions.api.deselectIndex(0, true); // This works!
}
Hope this will help someone else in the future!
var columnDefs =[{
headerName: 'Name',
field: 'name',
width: 108,
minLength: 1,
maxLength: 20,
editable: true
}]
- Modify prototype in file .js
TextCellEditor.prototype.init = function (params) {
var eInput = this.getGui();
var startValue;
// Set min & max length
if (params.column.colDef.maxLength)
eInput.maxLength = params.column.colDef.maxLength;
if (params.column.colDef.minLength)
eInput.minLength = params.column.colDef.minLength;
// cellStartedEdit is only false if we are doing fullRow editing
if (params.cellStartedEdit) {
this.focusAfterAttached = true;
var keyPressBackspaceOrDelete = params.keyPress === constants_1.Constants.KEY_BACKSPACE
|| params.keyPress === constants_1.Constants.KEY_DELETE;
if (keyPressBackspaceOrDelete) {
startValue = '';
}
else if (params.charPress) {
startValue = params.charPress;
}
else {
startValue = params.value;
if (params.keyPress !== constants_1.Constants.KEY_F2) {
this.highlightAllOnFocus = true;
}
}
}
else {
this.focusAfterAttached = false;
startValue = params.value;
}
if (utils_1.Utils.exists(startValue)) {
eInput.value = startValue;
}
this.addDestroyableEventListener(eInput, 'keydown', function (event) {
var isNavigationKey = event.keyCode === constants_1.Constants.KEY_LEFT || event.keyCode === constants_1.Constants.KEY_RIGHT;
if (isNavigationKey) {
event.stopPropagation();
}
});
};

Loading store dynamically based on visible page data for Ext.grid.Panel column

Below is a renderer for an Ext.grid.Panel column. Suppose contactStore has 2,000 values in it and all I care about is the name of the record based on the id (value parameter in this case), and my grid only has 25 rows/records in it for the page I'm on. How can I dynamically get the store so that I grab the relevant associated records (based on the foreign key) of the id of my grid column, rather than loading all 2,000 records? Is there a way to load the store and then in the callback, somehow have this "renderer" function display the values after the callback succeeded?
columns: [{
...
}, {
header: 'Contact Name',
flex: 1,
sortable: true,
dataIndex: 'contact_id',
renderer: function(value) {
var contactStore = Ext.StoreManager.lookup('Contacts');
return contactStore.getById(value).get('full_name');
}
}, {
You can adjust the collectData(records, startIndex) in the viewConfig for that:
Ext.create('Ext.grid.Panel', {
(...)
viewConfig: {
//this method needs to be adjusted
collectData: function(records, startIndex) {
var me = this;
//we can use a custom function for this
if (me.onBeforeCollectData) {
me.onBeforeCollectData(records);
}
var data = me.superclass.collectData.call(me, records, startIndex);
return data;
},
onBeforeCollectData: function(records) {
var newExtraParams = [];
var oldExtraParams;
var needToLoadStore = false;
var contactStore = Ext.StoreManager.lookup('Contacts');
if (contactStore) {
oldExtraParams = contactStore.oldExtraParams;
} else {
//don't use autLoad: true, this will be a local store
contactStore = Ext.create('Ext.data.Store', {
storeId:'Contacts',
(...)
});
needToLoadStore = true;
}
for (var x in records) {
//contact_id is read out here
var param = records[x].get('contact_id');
if (param) {
if (needToLoadStore == false && Ext.Array.contains(oldExtraParams, param) == false) {
needToLoadStore = true;
}
newExtraParams.push(param);
}
}
if (needToLoadStore == true) {
//we use this to load the store data => because of async: false property
Ext.Ajax.request({
scope: this,
//this is for synchronous calls
async: false,
url: (...),
method: (...),
params: newExtraParams,
success: function (res, opt) {
var responseObj = Ext.decode(res.responseText, false);
contactStore.loadData(responseObj); //or deeper in the responseObj if needed
contactStore.oldExtraParams = newExtraParams;
}
});
}
}
}
});

Resources