I am using w2ui to display a table of a django model. Instead of loading all the elements at once I am using autoLoading to load a 100 elements at a time. Below is the code for the table:
var config = {
grid: {
name: "grid",
url: "retrieveData/",
show: {
footer:true,
toolbar:true
},
header: "List of RTNs",
columns: [
{ field:"number", caption:"Number", size:"30%" },
{ field:"name", caption:"Name", size:"30%" },
{ field:"release", caption:"Release", size:"30%" }
]
}
}
$(function() {
$("#grid").w2grid(config.grid);
});
The code that handles the json request is done via a django view, below is the code for it:
#csrf_exempt
def retrieveData(request):
cmd = request.POST.get("cmd", False)
if cmd == "get-records":
offset = int(request.POST.get("offset", False))
limit = int(request.POST.get("limit", False))
entries = Data.objects.all()[offset:limit+offset]
json_list = {"status":"success"}
records = []
def notNone(x):
if x != None and x != "":
return x.strftime("%Y-%m-%dT%H:%M:%S")
else:
return ""
for entry in entries:
records.append({
"recid":entry.id,
"number":entry.number,
"name":entry.name,
"release":entry.release,})
total = len(records)
json_list["total"] = total
json_list["records"] = records
return HttpResponse(json.dumps(json_list), content_type="application/json")
else:
json_list = {"status":"error"}
json_list["message"] = "CMD: {0} is not recognized".format(cmd)
json_list["postData"] = request.GET
return HttpResponse(json_dumps(json_list), content_type="application/json")
The table is able to retrieve the first 100 elements, but when I scroll all the way to the bottom the table does not load more elements. Instead of loading more elements it does nothing. I turned off autoLoad, but this still didn't do anything (the "Load More" button did not appear). There are a thousand elements in my table.
There are no errors being reported, and everything seems to be working except that it is not loading more elements when I scroll.
I am following the example below from the w2ui site:
http://w2ui.com/web/demos/#!combo/combo-9
The way total is being set at line
json_list["total"] = total
is wrong. Because it is saying that the total amount of elements is 100, even though you have more than 100 elements. "total" is used to indicate the total amount of elements you have not the total amount of elements you are sending in the json response.
Change the code to the following:
#csrf_exempt
def retrieveData(request):
cmd = request.POST.get("cmd", False)
if cmd == "get-records":
offset = int(request.POST.get("offset", False))
limit = int(request.POST.get("limit", False))
--> entries = Data.objects.all()
--> total = len(entries)
--> entries = entries[offset:limit+offset]
json_list = {"status":"success"}
records = []
def notNone(x):
if x != None and x != "":
return x.strftime("%Y-%m-%dT%H:%M:%S")
else:
return ""
for entry in entries:
records.append({
"recid":entry.id,
"number":entry.number,
"name":entry.name,
"release":entry.release,})
json_list["total"] = total
json_list["records"] = records
return HttpResponse(json.dumps(json_list), content_type="application/json")
else:
json_list = {"status":"error"}
json_list["message"] = "CMD: {0} is not recognized".format(cmd)
json_list["postData"] = request.GET
return HttpResponse(json_dumps(json_list), content_type="application/json")
Related
After downloading the xlsx file, i need to sum the value and shows in average total count,
kindly help me to fix this issue. i have attached the screenshot of current situation is showing 0
TS code
public exportAsExcelFile(summary:any[], json: any[], excelFileName: string): void {
let report = "Global Service Desk SLA";
let ReportName = [{"Report":`Report Name : ${report}`}];
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(ReportName ,{skipHeader:true});
if(worksheet['A2'] == undefined){
worksheet['A2'] = {"t":"s","v":`Date Range : ${summary[0].FromDate +" - "+summary[0].ToDate}`};
}
if(worksheet['A3'] == undefined){
worksheet['A3'] = {"t":"s","v":`Bot : ${summary[0].Bot}`}
}
if(worksheet['A4'] == undefined){
worksheet['A4'] = {"t":"s","v":`Timezone : ${summary[0].timeZone}`}
}
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data']};
XLSX.utils.sheet_add_json(worksheet,json,{origin:"A7"});
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
if i remove single 0 in that column cell the average total is showing please see in my screenshot how to fix in my TS code.
0 removed img
If iam select the queue time column like screenshot average total is showing 0 i need the sum of total values in Average section
I added a filed company(It's a char field), when creating a payment ,I want to set default value.
When creating new payment, the value wasn't displayed in the form view . But , when printing 'my_company' , I got the correct result.
What's wrong please?
class AccountPayment(models.Model):
_inherit = "account.payment"
#api.model
def get_company(self):
if self.move_type == 'in_invoice':
my_company = self.env.user.company_id.name
self.company = my_company
else:
self.company = ''
company = fields.Char(string='Company ', default=get_company)
Thanks.
You need to return the value.
Here is the correct code
class AccountPayment(models.Model):
_inherit = "account.payment"
def get_company(self):
if self.move_type == 'in_invoice':
my_company = self.env.user.company_id.name
return my_company
else:
return None
company = fields.Char(string='Company Name', default=get_company)
I'm using vuejs for this project, but this problem is not necessarily connected - but if there is a vue-way, I would prefer that.
I'm building a table, that enables the user to have per-column-filters (in this case simple inputs). The columns are dynamic, so is the amount of data (thousands of rows, but less than 100.000 entries).
// example data
var columns = ['id', 'title', 'date', 'colour']
var data = [{ id: 1, title: 'Testentry 1', date: '2017-02-21T07:10:55.124Z', colour: 'green'}]
Here is the problem: I'm iterating over the columns, checking if a search-input exists, and if so, I try to filter the data based on the searchquery. In case of the ID, the time complexity is O(n). If I know search for a title additionally, I can reuse the result of the first searchquery, dramatically reducing the amount of data has to be looked at.
The searchqueries are stored in an object search, and the filtered data is a computed property, that gets updated whenever search changes. The way how that works though is, that if I change the searchquery for title, it would re-evaluate the searchquery even for the ID, although the searchquery for that didn't change.
This would require some kind of caching of data filtered for each column. And only the proceeding columns need to be queried upon.
edit: added code for the filtering:
filteredRows () {
var rows = this.data
for (var i = 0; i < this.columns.length; i++) {
var column = this.columns[i].name
var search = this.tSearch[column]
if (!search && search.length === 0) continue
console.log(column + ': ' + ' (' + search + ') -> ' + rows.length)
rows = _.filter(rows, (row) => {
var value = '' + row[column]
value.search(search) > -1
})
}
return rows
}
Just a suggestion, but did you try to use a watcher to get old and new value of input.
data: function() {
return {
propertyToWatch: 'something'
}
},
computed: {
...
},
watch: {
'propertyToWatch': function (val, oldVal) {
console.log(oldVal); // logs old value
console.log(val); // logs current value
// here you can call a function and send both of these args and detect diff
}
},
....
I tried using:
$('#Table').jqGrid('setGridParam', { sortname: mycol });
$('#Table').jqGrid('setGridParam', { sortorder: myorder });
$('#Table').jqGrid('sortGrid', mycol)
the grid doesn't do anything. My data is in remote server, and I sort it remotely (using the DB server once the correct column and order sequence is pushed via ajax. I basically want to be able to sort the grid programmatically once the correct grid settings have been loaded, those settings store for each column: (1)position, (2)size, (3)status(show/hide), (4)sorting status. So far I've been able to store/retrieve and apply (once retrieved) for 1, 2, and 3. But I am having a hard time applying those (I can store/retrieve it as json objects the sortname and sortorder) into/from the DB. By the way if you click on any column it does the sorting (sends the right request to the DB) and shows the right icon (ASC>DESC>UNSORTED.....) in sequence after each click and shows the right data.
The closest I have it to the solution is this:
$('#TableData').jqGrid('setGridParam', { sortname: mysortname, sortorder: myortorder });
$('#TableData').trigger('reloadGrid');
The actual data gets loaded onto the grid, the right query is sent to the DB server: 'order by col1 asc, col2 desc, col3 asc, ... coln ordern'
The problem is the sorting icons, I use this function to set it right before calling 'reloadGrid':
var setSortingIcon = function (colName, sortOrder) {
var $self = $(this),
colModel = $self.jqGrid("getGridParam", "colModel"),
cmLength = colModel.length,
cm,
i;
for (i = 0; i < cmLength; i++) {
cm = colModel[i];
if (cm.name === colName) {
var icons = $($self[0].grid.headers[i].el).find('>div.ui-jqgrid-sortable>span.s-ico');
if (sortOrder === 'asc') { // this.p.sortorder doesn't work!
icons.find('>span.ui-icon-asc').show();
icons.find('>span.ui-icon-asc')[0].style.display = '';
icons.find('>span.ui-icon-desc').hide();
}
else if (sortOrder === 'desc') {
icons.find('>span.ui-icon-desc').show();
icons.find('>span.ui-icon-desc')[0].style.display = '';
icons.find('>span.ui-icon-asc').hide();
}
else {
icons.find('>span.ui-icon-desc').hide();
icons.find('>span.ui-icon-asc').hide();
}
// no need to proceed
break;
}
}
};
It works for setting the column to not sorted (clearing the pyramid icon by sending an empty string as sortOrder), but for some of ASC, DESC, it shows the incorrect icon on the column, e.g. for an ASC order which is a bold pyramid, it might give me any combination of: a lighted (not bold) pyramid, a lighted normal inverted pyramid (DESC), a bold normal inverted pyramid (DESC).
I also tried to use this function that I got from some other post:
var setSorting = function (colName, sortOrder) {
var $self = $(this),
colModel = $self.jqGrid("getGridParam", "colModel"),
headers = $self[0].grid.headers,
showSortIconsInAllCols = $self.jqGrid("getGridParam", "viewsortcols")[0],
cmLength = colModel.length,
cm,
$sortSpan,
i;
for (i = 0; i < cmLength; i++) {
cm = colModel[i];
if (cm.name === colName) {
cm.lso = String(sortOrder).toLowerCase() === "desc" ? "desc" : "asc";
}
$sortSpan = $(headers[i].el).find(">div.ui-jqgrid-sortable>span.s-ico");
if (showSortIconsInAllCols || cm.lso) {
$sortSpan.show();
if (cm.lso) {
$sortSpan.find(">span.ui-icon-" + cm.lso)
.removeClass("ui-state-disabled");
}
}
}
};
Doesn't do the job either. Again so far the data is nice. I'd like to change the icons successfully. The reason I decided to go with sortGrid at the beginning of this post is because it does the icon things for you (so it says) or may be sortGrid is not the way to go. Thanks for any help.
I'm having a problem with my JSON array. On first load, the order is not as it should be (as defined in the SQL query).
So the main problem is, on page load, i.e. when the SQL query is called with lastPoll=null - the results are not sorted by time1 DESC, yet they are sorted by the s.id ASC. When I enter a new result, and then run the query with the lastPoll set in the query, then the latest is added to the top, as it should be.
Weird part is - if I view the raw JSON response at push.php with the correct params in the URL, the response is correct and in the correct order. So, the problem must lie in the parsing?
Here is the SQL Query:
$getActivityUpdates1 = mysql_query("
SELECT
s.id, u.name, u.profilePic, s.userid, s.content, s.time1, s.imageKey
FROM
status_updates s
INNER JOIN
users1 u ON u.id = s.userid
WHERE
competitionId = '$competitionId' AND s.time1 > '$lastPoll'
ORDER BY s.time1 DESC");
$results = array('items' => array());
while ($row = mysql_fetch_array($getActivityUpdates1))
{
$results['items'][] = array(
'statusid' => $row['id'],
'name' => $row['name'],
'profilePic' => $row['profilePic'],
'content' => $row['content'],
'time1' => $row['time1'],
'imageKey' => $row['imageKey'],
);
}
die(json_encode($results));
?>
Here is the Javascript where I re-run the query.
var lastPoll = null;
function loadActivity(onDone) {
var competitionId = $("body").attr("data-competitionId");
console.log(lastPoll);
if (lastPoll == null) { // We have never polled, we want to pull everything and populate the list.
url = "push.php?competitionId=" + competitionId + "&lastPoll=1999-01-01 22:00:00";
} else { // We have polled once, send the date and time of that last poll to capture only new entries.
url = "push.php?competitionId=" + competitionId + "&lastPoll=" + lastPoll;
}
$.get(url, function(data) {
jsonData = $.parseJSON(data);
var spot = $("#activityspot");
var template = spot.find(".template");
for (var j = 0; j < jsonData.items.length; j++) {
var entryData = jsonData.items[j];
var entry = template.clone();
entry.removeClass("template");
entry.find(".message").text(entryData.statusid);
spot.prepend(entry);
}
if (onDone) {
onDone();
}
lastPoll = js_yyyy_mm_dd_hh_mm_ss();
});
}
You are producing your results in reverse time order, but then also adding them to the page in reverse order (with .prepend). The net result is that the two reversals cancel each other out such that each batch of results is added to the top of the list in ascending time order.
If the intent is to actually have them displayed in reverse order just get rid of the DESC qualifier from the query and rely on the .prepend call to add each successive entry to the top of the page.