ag-grid react exportMultipleSheetsAsExcel with coulmnKeys - reactjs

I'm novice in ag-grid react. Currently I want to export the grid data as excel with multiple sheets. The requirement is, export only selected columns(User will be prompted to choose columns to be present in the excel on click of Export button). I know, we should be using columnKeys attribute. But something, I'm missing here. After clicking columns , I'm getting this error when I click export option
AG Grid: Invalid params supplied to getMultipleSheetsAsExcel() - ExcelExportParams.data is empty.
getRefsFromParent(childRefs) {
this.setState({
myRequestedRefs: childRefs
});
/* Export multiple sheets commence here */
var spreadsheets = []; // var for storing multiple sheets data
for (let i = 0; i < this.state.checkedSheets.length; i++) {
if (this.state.checkedSheets[i] == 'Engagements') {
spreadsheets.push(
//Referring Engagement Reference passed from Parent Component
this.state.engRef.current.api.getSheetDataForExcel({
sheetName: 'Engagements'
})
)
}
else {
spreadsheets.push(
//Sheets will be created based on the selected items from the sheetsList
this.state.ref.current.api.getSheetDataForExcel({
onlySelected: false,
sheetName: this.state.checkedSheets[i]
})
)
}
console.log("Spreadsheets ", spreadsheets);
}
this.state.ref.current.api.exportMultipleSheetsAsExcel({
data: spreadsheets,
columnKeys: this.state.pickedColumns, //columns selected in the modal by user
fileName: 'client-details.xlsx',
});
}

Related

How to hide a certain column of a table using antd?

Sample code below
{
title: 'Site',
dataIndex: 'site'
}
I want to hide the site column and im still new to the antd react ui.
And theres no show/hide function in column API of antd docs.
I want to hide it after a certain condition has been met like there are 2 user types. Admin user and General user.
if(user_role = admin_user){
show column
elseif(user_role = general_user){
hide column
}
getColumns = (userRole) => {
switch(userRole){
case 'AdminUser': { return //return admin user columns here }
case 'GeneralUser': { return //return the genral user columns here }
default: { return //handle other cases.. or raise error}
}
}
In your table component call the function.(Assuming your state has the user role)
<Table columns = {this.getColumns(this.state.userRole)} />

Wix Corvid Database Filtering Conditional

I have setup a filter using the code queen video-works great except one part-
I got two dropdowns,
Category and subcategory,I am trying to setup simple conditional filtering
When I click category, on change event happens -> subcategory gets activated(this is working)
Subcategory should conditionally filter and show only relevant/matching results,however shows all the results from the field.
For eg. Category dropdown we choose - industrial houses -> Subcategory becomes active and shows only the results that match for the industrial category
Currently shows every element from the field,can anyone help me?
Here is the code.Thank you
$w.onReady(function () { //code that clears the search
$w('#clear').onClick(() => {
$w('#dropdown1 , #dropdown2 , #dropdown3, #dropdown4, #dropdown5 , #dropdown6').value = "";
$w('#dataset1').setFilter(wixData.filter())
.then();
});
});
export function button1_click(event, $w) { //filter on click even
let searchValue = $w("#locationSearch").value;
$w("#dataset1").setFilter(wixData.filter()
.contains("bathrooms",$w('#dropdown1').value)
.contains("bedrooms", $w('#dropdown2').value)
.contains("typesOfProperties", $w('#dropdown5').value) //CATEGORY DROPDOWN
.eq("subcategory", $w("#dropdown6").value) //SUBCATEGORY DROPDOWN
.contains('propertyAddress', searchValue)
.contains('averagePrice', $w('#dropdown7').value))
.then((results) => {
console.log("Dataset is now Filtered");
$w("#repeater1").data = results.items;
})
.catch((err) => {
console.log(err);
});
$w("#repeater1").expand();}
//FILTER FROM THE CODE QUEEN VIDEO THAT SHOULD SHOW ONLY MATCHING RESULTS
export function dropdown5_change(event, $w) {
SubCatFilter(); }
function SubCatFilter (){
$w("#dropdown6").enable(); //SUBCATEGORY DROPDOWN
$w("#dataset1").setFilter(wixData.filter() //BOTH FIELDS IN THE SAME DATASET
.eq("subcategory", $w("#dropdown5").value) //SUBCATEGORY KEY FIELD
)
}

Dropdown list not showing default item

I am using the semantic-ui-react dropdown list, which I have working just fine. The problem is, on my form I am pulling data from a database using the Mobx store. I have a array setup for the options in the dropdown list. when the form loads from the store the text field for the dropdown list is blank, if I click on the dropdown I can see that the selected option is highlight (bold). How do I get the text field to show the default options. I have included some code below if anyone can look at it and give me an idea of what I need to do.
Thanks for all your help.
Here is the code for the dropdown list:
<div className="col-sm-3">
<div className="bg-primary text-white text-center">
Driver
</div>
<div>
<Dropdown
selection
fluid
id="driver"
name="driver"
ref="driver"
onChange={this.handleChange}
value={this.props.EquipmentStore.truck_detail.driver}
options={this.props.EquipmentStore.driver_list}/>
</div>
</div>
Here is how I am building the driver_list, I am basically getting a list of users from the database and create an array with value and text fields
let newUserItem = {
value: getUser.id,
text: getUser.first_name + " " + getUser.last_name
};
this.driver_list.push(newUserItem)
The value in the truck_detail.driver is a numberic value that the same value in the value field in the driver_list value field...that is all working fine, I can not get the text value to show in the text field for the dropdown list by default.
Here is the code that I use to build the options list:
async loadDriverList() {
let endpoint = '/api/users/profile/?owner=True';
this.driver_list.length = 0;
let lookupOptions = {
method: "GET",
headers: {
'Content-Type': 'application/json'
}
};
try {
const response = await fetch(endpoint, lookupOptions);
const profile_list = await response.json();
const userItem = {value:0, text:'Select Driver'};
this.driver_list.push(userItem);
let array_length = profile_list.length;
for (let i = 0; i < array_length; i++) {
let ownerId = profile_list[i].user;
let endpoint = '/api/users/users/' + ownerId + '/';
let userList = await fetch(endpoint, lookupOptions);
let getUser = await userList.json();
let newUserItem = {
value: getUser.id,
text: getUser.first_name + " " + getUser.last_name
};
this.driver_list.push(newUserItem)
}
} catch(e) {
console.log(e)
}
}
After a lot of conversation with Predrag Beocanin I have solved this issue. What it boils down to is my form (with the Dropdown) was getting render before the options list was fully populated. In my application I have a form that shows a list of items, once you click on the item it will render a detailed form of that listed item. Originally I wall trying to populate my options list once you click on the item you wanted to view the details on. Because the options list is basically a static list, I am now populating that list when you are view the first form. Now when you click on the item to view the Dropdown options are fully populated and working just as I had expected.
Thanks for your help Predrag.

How to select Multiple rows in Kendogrid with out select Checkbox in Angular5

I am working KendoUi angular 5. I need How to select Multiple rows with out Using Ctrl key And check check boxes in kendogrid in angular 5?
I am able to Select Multiple rows using Ctrl key or select check boxes as per telerik kendo grid but i want to select multiple rows with out select check box or Ctrl key
You can use the rowSelected function and override the built-in Grid selection behavior, replacing it with a custom one:
DOCS
For example you can use the cellClick event handler where the data item, associated with the row the clicked cell is in, is available as event data and store the selected items in a collection that you can manipulate as necessary:
import { Component } from '#angular/core';
import { products } from './products';
import { RowArgs } from '#progress/kendo-angular-grid';
#Component({
selector: 'my-app',
template: `
<kendo-grid
[data]="gridData"
[height]="500"
[selectable]="true"
[rowSelected]="isRowSelected"
(cellClick)="onCellClick($event)"
>
<kendo-grid-column field="ProductName" title="Product Name" [width]="300"></kendo-grid-column>
<kendo-grid-column field="UnitsInStock" title="Units In Stock"></kendo-grid-column>
<kendo-grid-column field="UnitsOnOrder" title="Units On Order"></kendo-grid-column>
<kendo-grid-column field="ReorderLevel" title="Reorder Level"></kendo-grid-column>
</kendo-grid>
`
})
export class AppComponent {
public gridData: any[] = products;
public mySelection: any[] = [];
public onCellClick({dataItem}) {
const idx = this.mySelection.indexOf(dataItem.ProductID);
if(idx > -1) {
// item is selected, remove it
this.mySelection.splice(idx, 1);
} else {
// add item to the selection
this.mySelection.push(dataItem.ProductID);
}
}
// Use an arrow function to capture the 'this' execution context of the class.
public isRowSelected = (e: RowArgs) => this.mySelection.indexOf(e.dataItem.ProductID) >= 0;
}
PLUNKER EXAMPLE
I found an alternate workaround which doesn't require rebuilding the row selection, which I prefer as it feels less risky.
All this does is hijacks any click event on a row in the grid, hides it from Kendo, and then sends a fake click event with ctrl down instead; therefore causing Kendo to do the proper selection behaviour for us.
It must be done in databind as when the page is changed or a filter added the event needs to be bound to the new rows.
$("#yourGrid").kendoGrid({
...
dataBound: dataBound
...
});
...
function dataBound() {
$(".k-master-row").click(function (e) {
// Prevent stack overflow by exiting if we have already done the below logic
// and let kendo handle it
if (e.ctrlKey === true)
return;
// Prevent Kendo from handling this click event as we are going to send another one with ctrl this time
e.preventDefault();
e.stopPropagation();
// Create a fake click with ctrl pressed on this particular row (Kendo will keep previous rows selected in this case)
var e2 = jQuery.Event("click");
e2.ctrlKey = true; // Ctrl key pressed
$(this).trigger(e2);
});
}

How to verify sorting of multiple ag-grid columns in Protractor

I am using protractor for e2e testing.
There is a ag-grid table where multiple columns are sorted in ascending order.
How do i go about verifying this?
Picture of Sample table
In AgGrid the rows might not always be displayed in the same order as you insert them from your data-model. But they always get assigned the attribute "row-index" correctly, so you can query for it to identify which rows are displayed at which index.
So in your E2E-tests, you should create two so-called "page objects" (a selector fo something in your view, separated from the text-execution code, google for page object pattern) like this:
// list page object
export class AgGridList {
constructor(private el: ElementFinder) {}
async getAllDisplayedRows(): Promise<AgGridRow[]> {
const rows = $('div.ag-body-container').$$('div.ag-row');
await browser.wait(EC.presenceOf(rows.get(0)), 5000);
const result = await rows.reduce((acc: AgGridRow[], elem) => [...acc, new AgGridArtikelRow(elem)], []);
return await this.sortedRows(result);
}
private async sortedRows(rows: AgGridRow[]): Promise<AgGridRow[]> {
const rowsWithRowsId = [];
for (const row of rows) {
const rowIndex = await row.getRowIndex();
rowsWithRowsId.push({rowIndex, row});
}
rowsWithRowsId.sort((e1, e2) => e1.rowIndex - e2.rowIndex);
return rowsWithRowsId.map(elem => elem.row);
}
}
// row page object
export class AgGridRow {
constructor(private el: ElementFinder) {}
async getRowIndex(): Promise<number> {
const rowIndexAsString: string = await this.el.getAttribute('row-index');
return parseInt(rowIndexAsString, 10);
}
}
And in your test:
it('should display rows in right order', async () => {
const rows = await gridList.getCurrentDisplayedRows(); // gridList is your AgGridList page object, initialised in beforeEach()
// now you can compare the displayed order to the order inside your data model
});
What this code does: you make page objects for accessing the table as a whole and for accessing elements within a row. To accessing the list in the same order as it is displayed in the view, you have to get all displayed rows (with lazy loading or pagination it should be below 100, otherwise your implementation is bad), get the rowIndex from each of them, sort by it and only then return the grid-list to the test-execution (.spec) file.

Resources