Is there a way to make api call when expanding table to show nested table? - antd

In Ant Nested table - When expanding a row, I want to make an api call and get the data to show the nested table.
The function expandedRowRender, expects to return the nested table, it does not accept a promise.
How can I show a nested Ant table using ajax call?
I have tried to recreate the scenario for reference.
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Table } from "antd";
import reqwest from "reqwest";
const nestedColumns = [
{
title: "Name",
dataIndex: "name",
sorter: true,
render: name => `${name.first} ${name.last}`,
width: "20%"
},
{
title: "Gender",
dataIndex: "gender",
filters: [
{ text: "Male", value: "male" },
{ text: "Female", value: "female" }
],
width: "20%"
},
{
title: "Email",
dataIndex: "email"
}
];
class App extends React.Component {
state = {
data: []
};
fetch = (params = {}) => {
console.log("params:", params);
reqwest({
url: "https://randomuser.me/api",
method: "get",
data: {
results: 10,
...params
},
type: "json"
}).then(data => {
return (
<Table
columns={nestedColumns}
dataSource={data.results}
pagination={false}
/>
);
// this.setState({
// data: data.results
// });
});
};
expandedRowRender = () => {
this.fetch();
return <table columns={nestedColumns} dataSource={this.state.data} />;
};
render() {
const columns = [
{ title: "Name", dataIndex: "name", key: "name" },
{ title: "Platform", dataIndex: "platform", key: "platform" },
{ title: "Version", dataIndex: "version", key: "version" }
];
const data = [
{
key: 1,
name: "Screem",
platform: "iOS",
version: "10.3.4.5654"
}
];
return (
<Table
columns={columns}
dataSource={data}
pagination={false}
expandedRowRender={this.expandedRowRender}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));

I try my level best to answer your question. Here is the reduced type of code and you can get an idea of how to do that.
In state,
state = {
data: null,
loading: false,
};
Here is your function to make API call,
fetch = (expanded, record) => {
axios.get(`put your api to load nested table`)
.then(res => {
const data = res.data;
this.setState({
...this.state.data,
data,
loading: true
})
}).catch(error => {
console.log(error, "error")
})
}
After that,
expandedRowRender=() => {
if(this.state.loading){
const nestedTableData = this.state.data.map(row => ({
key: row.id,
Id: row.id,
name: 'test',
gender: 'gender',
}))
const nestedColumns = [
{ title: "Name", dataIndex: "name", key: "name" },
{ title: "Gender", dataIndex: "gender", key: "gender" },
];
return <Table columns={nestedColumns} dataSource={nestedTableData } pagination={false} />
}
};
And put following code below return
<Table
className="components-table-demo-nested"
columns={columns}
dataSource={tableData}
expandable={{
expandedRowRender: this.expandedRowRender,
rowExpandable: record => true,
onExpand: this.fetch
}}
/>
I hope it may help you and let me know if it does. :)

Related

How to validate select2?

I have a select2 as below:
<select class="form-select" id="ds" name="ds" tabindex="1" required></select>
I populate it using:
var data = [{ id: "0", text: "" }, { id: "1", text: "List" }, { id: "2", text: "Tags" }];
$('#ds').select2({
data: data
})
I try to validate it using below, but it's not working, what did I do wrong?
$form.each(function() {
var $this = $(this);
$this.validate({
rules: {
data_source: {
required: true
}
},
messages: {
data_source: {
required: 'Data source field is required'
}
}
});
});

Ant deisgn 4 table summary issue in the Table.Summary.Cell

Im usiing My react typescript project for Ant design 4 table . so when i adding ant design Summary table, got a following error
TS2741: Property 'index' is missing in type '{ children: Element; colSpan: number; }' but required in type 'SummaryCellProps'.
any one know how to fix that issue.
Thanks
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Typography } from 'antd';
const { Text } = Typography;
const columns = [
{
title: 'Name',
dataIndex: 'name',
},
{
title: 'Borrow',
dataIndex: 'borrow',
},
{
title: 'Repayment',
dataIndex: 'repayment',
},
];
const data = [
{
key: '1',
name: 'John Brown',
borrow: 10,
repayment: 33,
},
{
key: '2',
name: 'Jim Green',
borrow: 100,
repayment: 0,
},
{
key: '3',
name: 'Joe Black',
borrow: 10,
repayment: 10,
},
{
key: '4',
name: 'Jim Red',
borrow: 75,
repayment: 45,
},
];
const fixedColumns = [
{
title: 'Name',
dataIndex: 'name',
fixed: true,
width: 100,
},
{
title: 'Description',
dataIndex: 'description',
},
];
const fixedData = [];
for (let i = 0; i < 6; i += 1) {
fixedData.push({
key: i,
name: i % 2 ? 'Light' : 'Bamboo',
description: 'Everything that has a beginning, has an end.',
});
}
ReactDOM.render(
<>
<Table
columns={columns}
dataSource={data}
pagination={false}
bordered
summary={pageData => {
let totalBorrow = 0;
let totalRepayment = 0;
pageData.forEach(({ borrow, repayment }) => {
totalBorrow += borrow;
totalRepayment += repayment;
});
return (
<>
<Table.Summary.Row>
<Table.Summary.Cell>Total</Table.Summary.Cell>
<Table.Summary.Cell>
<Text type="danger">{totalBorrow}</Text>
</Table.Summary.Cell>
<Table.Summary.Cell>
<Text>{totalRepayment}</Text>
</Table.Summary.Cell>
</Table.Summary.Row>
<Table.Summary.Row>
<Table.Summary.Cell>Balance</Table.Summary.Cell>
<Table.Summary.Cell colSpan={2}>
<Text type="danger">{totalBorrow - totalRepayment}</Text>
</Table.Summary.Cell>
</Table.Summary.Row>
</>
);
}}
/>
</>,
document.getElementById('container'),
);
Had this issue yesterday as well, looking at the SummeryCellProps the rc-table team made index required. So I just added <Table.Summary.Row index={1}> you need to iterate through your pagedata to add the index of the that column

how to hide columns of antd data table for small devices(mobile view)?

If the table has five columns i want to display only 2 columns for mobile view
https://ant.design/components/table
you can keep columns in component state and dynamically filter the columns on window resize. Something like this
useEffect(() => {
window.addEventListener("resize", <callback function to update columns>);
// cleanup
return() => window.removeEventListener("resize");
});
Inside render method you need to declare columns with let and change them if window.innerWidth < 480 (I made it less then 500 px to be safe). By changing, I mean filtering from an array of columns only those columns that you want. The best way to filter is by key, because it's unique. This is how the code looks in react:
import React, { PureComponent } from "react";
import { Table } from "antd";
export default class MainPage extends PureComponent {
renderMobileTable = columns => {
return columns.filter(
column => column.key === "name" || column.key === "city"
);
};
render() {
const dataSource = [
{
key: "1",
name: "Mike",
lastName: "Willins",
age: 32,
address: "10 Downing Street",
city: "Chicago"
},
{
key: "2",
name: "John",
lastName: "Billards",
age: 42,
address: "5th Blvd",
city: "New York"
}
];
let columns = [
{
title: "Name",
dataIndex: "name",
key: "name"
},
{
title: "Last Name",
dataIndex: "lastName",
key: "lastName"
},
{
title: "Age",
dataIndex: "age",
key: "age"
},
{
title: "Address",
dataIndex: "address",
key: "address"
},
{
title: "City",
dataIndex: "city",
key: "city"
}
];
const isMobile = window.innerWidth < 500;
if (isMobile) {
columns = this.renderMobileTable(columns);
}
return <Table dataSource={dataSource} columns={columns} />;
}
}
For the source code you may refer to my repository on GitHub.
NOTE: if you are testing mobile view in Chrome Dev Tools, make sure you reload the page after resizing, as we put the logic into render method and the application has to be re-rendered or reloaded.
In antd v4 you can use column prop 'responsive'
const columns = [{
title: 'identification number',
dataIndex: 'ID',
responsive: ['sm'],
}]
https://ant.design/components/table/#Column

Using unescaped '#' characters on Ag Grid Enterprise React on Context Menu

When I am using the Ag-Grid context menu on application, I get a message on console saying:
[Deprecation] Using unescaped '#' characters in a data URI body is deprecated and will be removed in M68, around July 2018. Please use '%23' instead. See https://www.chromestatus.com/features/5656049583390720 for more details.
I really don't get any error, but I'm afraid on the message. Can any one update any thing about this message?
This is the component that use this.sate.columnDefs with renderframework like that:
<AgGridReact
// properties
columnDefs={this.state.columnDefs}
rowData={consumers.items}
animateRows
enableColResize
enableSorting={true}
rowSelection="single"
suppressMenuHide={true}
enableFilter={true}
onCellClicked={this.onCellClicked.bind(this)}
onGridReady={this.state.onGridReady}
paginationPageSize={10}
pagination={true}
multiSortKey="ctrl"
getContextMenuItems={this.state.getContextMenuItems}
/>
columnDefs: [
{
headerName: "",
suppressFilter: true,
width: 30,
cellRendererFramework: function (params) {
if (params.data.permissions.length > 0) {
return <i className="fa fa-ellipsis-v" />;
}
}
},
{
headerName: language.LAST_NAME,
field: "person.last_name",
enableRowGroup: true,
filter: "agSetColumnFilter",
},
{
headerName: language.FIRST_NAME,
field: "person.first_name",
enableRowGroup: true,
filter: "agSetColumnFilter",
}
],
sortingOrder: ["desc", "asc", null],
getContextMenuItems: this.getContextMenuItems.bind(this),
onGridReady: function (params) {
var sort = [
{
colId: "person.last_name",
sort: "asc"
},
{
colId: "person.first_name",
sort: "asc"
},
{
colId: "medical_id",
sort: "asc"
},
{
colId: "person.date_of_birth",
sort: "asc"
}
];
this.gridApi = params.api;
this.gridApi.setSortModel(sort);
params.api.sizeColumnsToFit();
}
getContextMenuItems(params) {
let language = languageActions.getLanguage();
const { props } = this;
this.setState({
showActionDiv: false
});
var aResult = [];
params.node.data.permissions.map((permision, index) => {
let language = languageActions.getLanguage();
switch (permision) {
case "Update":
aResult.push(
{
name: language.VIEW_DETAIL,
icon: '<span class="fa fa-edit icon-ag-grid"></span>',
action: () => {
//console.log(this.props);
this.props.toggleShowProfile();
}
}
);
break;
case "Read":
aResult.push(
{
name: language.VIEW_SCHEDULE,
icon: '<span class="fa fa-calendar icon-ag-grid"></span>',
action: () => {
this.props.toggleShowScheduledServices();
}
}
);
break;
}
});
aResult.push(
"separator",
"copy",
"csvExport",
"excelExport",
"autoSizeAll");
return aResult;
}

Bind results from search

I cannot bind results from search in kendo grid. I've tried many times, I'm in trouble four days, I don't know what is wrong here,
When i debug action everything is working perfect,data is OK, return grid result are OK, but results aren't shown in kendo.
Here is my code:
<script>
$(function() {
$("a.k-button").on('click', function (e) {
debugger;
e.preventDefault();
var dataObj = serializeByFieldsWrap(".invoiceForm");
var dataUrl = $(this).data('url');
// dataObj.ToolboxId = toolboxId;
$('body').css('cursor', 'wait');
var result = $.ajax({
type: "POST",
url: dataUrl,
dataType: 'json',
data: dataObj,
//complete: $("#invoices-grid").data("kendoGrid").data.read(),
});
result.done(function (data) {
console.log(data);
var grid = $('#invoices-grid').data("kendoGrid");
grid.dataSource.data(data);
});
result.fail(function (error) {
console.log(error);
});
});
});
</script>
Controller:
public ActionResult List(DataSourceRequest command, FinanceListModel model)
{
var searchString = model.SearchJobItemNumber;
var isChecked = model.IsChecked;
var invoices = _invoiceService.GetAllInvoices(searchString, isChecked);
var gridModel = new DataSourceResult
{
Data = invoices.Select(x => {
var jobModel = x.ToModel();
return jobModel;
}),
Total = invoices.TotalCount
};
return Json(gridModel, "application/json", JsonRequestBehavior.AllowGet);
}
Kendo UI Grid:
<script>
$(function() {
$("#invoices-grid").kendoGrid({
dataSource: {
data: #Html.Raw(JsonConvert.SerializeObject(Model.Invoices)),
schema: {
model: {
fields: {
JobNumber: { type: "string" },
CustomerName: { type: "string" },
DepartmentName: { type: "string" },
DateInvoice: { type: "string" },
ValidDays: { type: "number" },
Delivery: { type: "string" },
IsPayed: { type: "boolean" },
Payed: { type: "number" },
Status: { type: "boolean" },
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: function () {
var row = this.element.find('tbody tr:first');
this.select(row);
},
columns: [
#*{
field: "Status",
title: "#T("gp.Jobs.Fields.Status")",
template: '#= Status #'
},*#
{
field: "JobNumber",
title: "#T("gp.Invoice.Fields.JobNumber")",
template: '#= JobNumber #'
},
{
field: "CustomerName",
title: "#T("gp.Invoice.Fields.CustomerName")",
template: '#= CustomerName #'
},
{
field: "DepartmentName",
title: "#T("gp.Invoice.Fields.DepartmentName")",
template: '#= DepartmentName #'
},
{
field: "DateInvoice",
title: "#T("gp.Invoice.Fields.DateInvoice")",
template: '#= DateInvoice #'
},
{
field: "ValidDays",
title: "#T("gp.Invoice.Fields.ValidDays")",
template: '#= ValidDays #'
},
{
field: "Delivery",
title: "#T("gp.Invoice.Fields.Delivery")",
template: '#= Delivery #'
},
{
field: "Payed",
title: "#T("gp.Invoice.Fields.IsPayed")",
template: '#= (Payed == 2) ? "Комп." : ((Payed == 1) ? "ДЕ" : "НЕ") #'
},
{
field: "Id",
title: "#T("Common.Edit")",
width: 100,
template: '#T("Common.Edit")'
}
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "popup"
},
scrollable: false,
selectable: true,
change: function(e) {
var selectedRows = this.select();
var jobId = parseInt($(selectedRows).data('job-id'));
var jobItemId = parseInt($(selectedRows).data('job-item-id'));
var result = $.get("#Url.Action("SideDetails", "Production")/" + jobItemId);
result.done(function(data) {
if (data) {
$(".job-edit .jobItemDetails").html(data);
}
});
},
rowTemplate: kendo.template($("#invoiceRowTemplate").html()),
});
});
</script>
DataSourceResult formats your server response like this:
{
Data: [ {JobNumber: "...", FieldName: "bar", ... } ],
Total: 100
}
In other words, the data items array is assigned to a Data field, and the total items count is assigned to a Total field. The Kendo UI DataSource configuration must take this into account by setting schema.data and schema.total:
http://docs.telerik.com/kendo-ui/framework/datasource/crud#schema
http://docs.telerik.com/kendo-ui/framework/datasource/crud#read-remote
schema: {
data: "Data",
total: "Total"
}

Resources