Dojo's dijit.calendar and isDisabledDate - dojo

I'd like to use the dijit.calendar widget, but be able to set disabled dates from an array of dates. All the examples point out how to disable weekends, but I need to disable special dates too.
Can anyone point me in the right direction to utilize a custom function in the isDisabledDate, rather than just whats in dojo.date.locale?
I've tried writing a function, and putting it inside the isDisabledDate attribute, but all I get is errors.

I'm making a huge assumption here, that you're populating your array for each month displayed via an XHR request. This XHR request returns an array of strings in Y-m-d format (i.e. ['2011-11-29','2011-11-30']). Another slight assumption is that the XHR request returns an array of dates that should be enabled, but this can be reversed by swapping the disable = true; and disable = false; lines
I don't know how much detail to go into without being patronizing, so if anything is unclear I'll try to clarify afterwards.
dojo.provide("custom.Calendar");
dojo.declare("custom.Calendar", dijit.Calendar, {
_xhr: null,
// Month/Year navigation buttons clicked
_adjustDisplay: function(){
// Ensure all dates are initially enabled (prevents seepage)
this.isDisabledDate = function(date) {
return false;
};
this.inherited(arguments);
this._disableAndPopulate();
},
constructor: function(){
this.inherited(arguments);
this._disableAndPopulate();
},
// Month drop down box
_onMonthSelect: function(){
// Ensure all dates are initially enabled (prevents seepage)
this.isDisabledDate = function(date) {
return false;
};
this.inherited(arguments);
this._disableAndPopulate();
},
// Set disabled dates and re-render calendar
_disableAndPopulate: function(){
var currDate = this.currentFocus;
// Get Lower bound date
var startDate = new Date();
startDate.setFullYear(currDate.getFullYear(), currDate.getMonth(), -5);
// Create ymd dates manually (10x faster than dojo.date.locale.format)
var startMonth = (startDate.getMonth()<9 ? '0' + (startDate.getMonth()+1) : startDate.getMonth()+1);
var startDay = (startDate.getDate()<10 ? '0' + startDate.getDate() : startDate.getDate());
var ymdStartDate = startDate.getFullYear() + '-' + startMonth + '-' + startDay;
// Get Upper bound date
var endDate = new Date();
endDate.setFullYear(currDate.getFullYear(), currDate.getMonth() + 1, 14);
// Create ymd dates manually (10x faster than dojo.date.locale.format)
var endMonth = (endDate.getMonth()<9 ? '0' + (endDate.getMonth()+1) : endDate.getMonth()+1);
var endDay = (endDate.getDate()<10 ? '0' + endDate.getDate() : endDate.getDate());
var ymdEndDate = endDate.getFullYear() + '-' + endMonth + '-' + endDay;
var calendar = this;
// Get IssueDates
var issueDates;
// If an existing xhr request is still running, cancel it before starting a new one
if (this._xhr) {
this._xhr.cancel();
}
this._xhr = dojo.xhrGet({
url: "http://.....", // url of server-side script
content: {
startDate: ymdStartDate, // Earliest possible date displayed on current month
endDate: ymdEndDate, // Last possible date displayed on current month
filters: {} // Any additional criteria which your server-side script uses to determine which dates to return
},
failOk: true, // Prevent error being logged to console when previous XHR calls are cancelled
load: function(data){
issueDates = dojo.fromJson(data);
if (issueDates === undefined) {
// Error with xhr
} else {
calendar.isDisabledDate = function(date) {
var disable = true;
// Create ymdDate manually (10x faster than dojo.date.locale.format)
var month = (date.getMonth()<9 ? '0' + (date.getMonth()+1) : date.getMonth()+1);
var day = (date.getDate()<10 ? '0' + date.getDate() : date.getDate());
var ymdDate = date.getFullYear() + '-' + month + '-' + day;
// Loop through array returned from XHR request, if it contains current date then
// current date should not be disabled
for (key in issueDates) {
if (issueDates[key] == ymdDate) {
disable = false;
break;
}
}
return disable;
};
calendar._populateGrid(); // Refresh calendar display
}
},
// Log any errors to console (except when XHR request is cancelled)
error: function(args) {
if (args.dojoType == 'cancel') {
// Request cancelled
} else {
console.error(args);
}
}
});
},
onClose: function() {
// If an existing xhr request is still running, cancel it before starting a new one
if (this._xhr) {
this._xhr.cancel();
}
}
});

AMD style:
CalendarLite.js.uncompressed.js in dojo 1.7.1 contains the isDisabledDate function:
isDisabledDate: function(/*===== dateObject, locale =====*/){
// summary:
// May be overridden to disable certain dates in the calendar e.g. `isDisabledDate=dojo.date.locale.isWeekend`
// dateObject: Date
// locale: String?
// tags:
// extension
/*=====
return false; // Boolean
=====*/
},
...
You could re-implement the function using this example:
var myCalendar = declare(Calendar, {
datesToDisable : [],
constructor: function(args) {
this.inherited("constructor", arguments);
this.datesToDisable = args.datesToDisable;
},
isDisabledDate: function(/*Date*/date, /*String?*/locale){
return array.some(this.datesToDisable, function(item) {
return dojo.compare(item, date, "date") === 0;
});
}
});
Then you can use the following constructor and datesToDisable parameter to specify your array.
var someCalendar = new myCalendar({datesToDisable: [new Date(...),....,new Date(....)]},...);
or try this for a fast and dirty solution:
var someCalendar = new Calendar(...);
someCalendar.datesToDisable = [new Date(...),....,new Date(....)];
someCalendar.isDisabledDate = function(/*Date*/date, /*String?*/locale){
return array.some(this.datesToDisable, function(item) {
return date.compare(item, date, "date") === 0;
});
}
But I would recommend the first approach. The assumption is that you know AMD style in order to "import" dijit/Calendar, dojo/_base/array and dojo/date (for "date.compare()" to work).
Cheers!

You can add list of holidays in an array with its timestamp and use indexOf method to find matching dates while populating the calendar in the overriding function of isDisabledDate
var holidays = new Array();
var holidDt = new Date("October 2, 2012");
holidays.push(holidDt.getTime());
Now access the holiday array and check its presence. If present disable, else enable by overriding the isDisabledDate function
isDisabledDate: function(d) {
var dt = new Date(d);
var dayN = dt.getDay();
dt.setHours(0, 0, 0, 0);
/**
* Condition for
* 1. Weekends
* 2. Holidays (holiday array needs to be updated with holiday times)
*/
return ((!((dayN > 0) && (dayN < 6))) || (arrayUtil.indexOf(holidays, dt.getTime()) >= 0));
}

Related

How to add new fileds/values to line widgets in Barcode mobile view in Odoo14 EE?

Hi i am trying to add two new fields to the Barcode mobile view. I went through the default js code of odoo, but didn't find a way to add my custome fields to it.
Here is the default code
stock_barcode/static/src/js/client_action/lines_widget.js
init: function (parent, page, pageIndex, nbPages) {
this._super.apply(this, arguments);
this.page = page; #don't know where this argument page coming from in argument list.
this.pageIndex = pageIndex;
this.nbPages = nbPages;
this.mode = parent.mode;
this.groups = parent.groups;
this.model = parent.actionParams.model;
this.show_entire_packs = parent.show_entire_packs;
this.displayControlButtons = this.nbPages > 0 && parent._isControlButtonsEnabled();
this.displayOptionalButtons = parent._isOptionalButtonsEnabled();
this.isPickingRelated = parent._isPickingRelated();
this.isImmediatePicking = parent.isImmediatePicking ? true : false;
this.sourceLocations = parent.sourceLocations;
this.destinationLocations = parent.destinationLocations;
// detect if touchscreen (more complicated than one would expect due to browser differences...)
this.istouchSupported = 'ontouchend' in document ||
'ontouchstart' in document ||
'ontouchstart' in window ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0;
},
In _renderLines function,
_renderLines: function () {
//Skipped some codes here
// Render and append the lines, if any.
var $body = this.$el.filter('.o_barcode_lines');
console.log('this model',this.model);
if (this.page.lines.length) {
var $lines = $(QWeb.render('stock_barcode_lines_template', {
lines: this.getProductLines(this.page.lines),
packageLines: this.getPackageLines(this.page.lines),
model: this.model,
groups: this.groups,
isPickingRelated: this.isPickingRelated,
istouchSupported: this.istouchSupported,
}));
$body.prepend($lines);
for (const line of $lines) {
if (line.dataset) {
this._updateIncrementButtons($(line));
}
}
$lines.on('click', '.o_edit', this._onClickEditLine.bind(this));
$lines.on('click', '.o_package_content', this._onClickTruckLine.bind(this));
}
In the above code, you can see this.page.lines field, i need to add my custom two more fields.
Actually it's dead-end for me.
Any solution?

QZ TRAY PRINITING ORDER NOT IN SEQ

I'm trying to print qz tray from javascript.
I have barcode with number in ascending order 1,2,3,4, 5 and so on.
I looping the seq correctly . but when printed out, it was not in order.
setTimeout("directPrint2()",1000);
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function directPrint2(){
var data;
var xhttp;
var v_carton = "' || x_str_carton ||'";
var carton_arr = v_carton.split('','');
var v1 = "' ||
replace(x_zebra_printer_id, '\', '|') ||
'".replace(/\|/g,"\\");
if(v1 == ""){
alert("Please setup ZPL Printer");
}
else{
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = [ toNative(this.responseText) ];
printZPL(data, v1);
}
};
for (var j = 0; j < carton_arr.length; j++){
var url = "' || x_wms_url ||
'WWW_URL.direct_print_label?in_carton_no="+toValidStr(carton_arr[j]);
xhttp.open("GET", url, false);
xhttp.send();
sleep(5000);
}
}
};
',
'javascript'
What's missing from your example:
I do not see any looping logic in the example calling the printZPL function,
printZPL isn't a QZ Tray function and you're missing the code snippet which it calls. Usually this would be qz.print(config, data);.
Regardless of the missing information, the qz.print(...) API is ES6/Promise/A+ based meaning if you want to call qz.print multiple times in a row you need to use a Promise-compatible technique. (e.g. .then(...) syntax) between your print calls as explained in the Chaining Requests guide.
To avoid this, you can concatenate all ZPL data into one large data array. Be careful not to spool too much data at once.
If you know exactly how many jobs you'll be appending, you can hard-code the promise chain:
qz.websocket.connect()
.then(function() {
return qz.printers.find("zebra"); // Pass the printer name into the next Promise
})
.then(function(printer) {
var config = qz.configs.create(printer); // Create a default config for the found printer
var data = ['^XA^FO50,50^ADN,36,20^FDRAW ZPL EXAMPLE^FS^XZ']; // Raw ZPL
return qz.print(config, data);
})
.catch(function(e) { console.error(e); });
Finally, if you do NOT know in advanced how many calls to qz.print(...) you can use a Promise loop as explained in the Promise Loop guide.
function promiseLoop() {
var data = [
"^XA\n^FO50,50^ADN,36,20^FDPRINT 1 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 2 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 3 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 4 ^FS\n^XZ\n"
];
var configs = [
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" }
];
var chain = [];
for(var i = 0; i < data.length; i++) {
(function(i_) {
//setup this chain link
var link = function() {
return qz.printers.find(configs[i_].printer).then(function(found) {
return qz.print(qz.configs.create(found), [data[i_]]);
});
};
chain.push(link);
})(i);
//closure ensures this promise's concept of `i` doesn't change
}
//can be .connect or `Promise.resolve()`, etc
var firstLink = new RSVP.Promise(function(r, e) { r(); });
var lastLink = null;
chain.reduce(function(sequence, link) {
lastLink = sequence.then(link);
return lastLink;
}, firstLink);
//this will be the very last link in the chain
lastLink.catch(function(err) {
console.error(err);
});
}
Note: The Promise Loop is no longer needed in QZ Tray 2.1. Instead, since 2.1, an array of config objects and data arrays can be provided instead.

Mouseover or div in the blocked elements in DHTMLX Scheduler in mvc 4

I am using DHTMLX scheduler in my MVC application. I am blocking some times in the scheduler. While mouseovering or clicking the blocked elements i need to display a div or just a message is it possible to do ?
My controller code to display the blocked elements in the scheduler
public ContentResult Data(DateTime from, DateTime to)
{
var scheduler = new DHXScheduler(this);
var user = (int)Session["UserID"];
//var data = new SchedulerAjaxData(
// new SYTEntities().tblBusinessUserHolidays.Where(a => a.BusinessUserId == id && a.UserTypeId == 5).Select(e => new { id = e.Id, start_date = e.HolidayDate, text = e.HolidayDesc, end_date = "2015-07-08 10:30:00.000" })
// );
var data = new SchedulerAjaxData(
new SYTEntities().tblApps.Where(a => a.UserId1 == user).Select(e => new { id = e.AppointmentID, start_date = e.StartDate, end_date = e.EndDate, text = e.Description, event_length = e.Event_length, event_pid = e.Event_pid, rec_type = e.rec_type })
);
var blocked = new SYTEntities().tblApps
.Where(e => e.UserId1 != user && e.StartDate < to && e.EndDate >= from)
.Select(e => new { e.StartDate, e.EndDate }).ToList();
// var res = new SchedulerAjaxData(data);`
data.ServerList.Add("blocked_time", blocked);
return Content(data);
}
Script file is
[![window.schedulerClient = {
init: function () {
scheduler.serverList("blocked_time");//initialize server list before scheduler initialization
scheduler.attachEvent("onXLS", function () {
scheduler.config.readonly = true;
});
scheduler.attachEvent("onXLE", function () {
var blocked = scheduler.serverList("blocked_time");
schedulerClient.updateTimespans(blocked);
blocked.splice(0, blocked.length);
//make scheduler editable again and redraw it to display loaded timespans
scheduler.config.readonly = false;
scheduler.setCurrentView();
});
},
updateTimespans: function (timespans) {
// preprocess loaded timespans and add them to the scheduler
for (var i = 0; i < timespans.length; i++) {
var span = timespans\[i\];
span.start_date = scheduler.templates.xml_date(span.StartDate);
span.end_date = scheduler.templates.xml_date(span.EndDate);
// add a label
span.html = scheduler.templates.event_date(span.start_date) +
" - " +
scheduler.templates.event_date(span.end_date);
//define timespan as 'blocked'
span.type = "dhx_time_block";
scheduler.deleteMarkedTimespan(span);// prevent overlapping
scheduler.addMarkedTimespan(span);
$(".dhx_scale_holder ").mouseover(function () {
alert("hi");
})
}
}
};
<script type="text/javascript">
$(".dhx_cal_container").delegate(".dhx_time_block", "mouseover", function (event) {
dhtmlx.message("Blocked ");
});
</script>
I added the script code like this after that only it works.
You can either use onMouseMove event from scheduler api, or you can catch event manually.
If you do the later - note that DOM elements of marked timespans are added and removed silently, i.e. it's better not to attach listeners directly to them but use event delegation instead:
// .dhx_cal_container - top node of dhtmlxScheduler
$(".dhx_cal_container").on("mouseover", ".dhx_time_block", function(event) {
// do something
});
Here is a complete example:
http://docs.dhtmlx.com/scheduler/snippet/263a0dfa

dojo 1.8: populate select box with items from database including null values

Hi I just want to populate the select or comboBox.
I am able to populate both with the searchAttr to any string from JSON. But not so when there are null values.
JSON string :
[{"batch":"0000001000"},{"batch":"0000"},{"batch":""},{"batch":null}]
dojo code:
var selBatch = new ComboBox //located at the left side of the page and it is the second select box in a row
(
{ id:'ID_selBatch',
value:'',
searchAttr:'batch',
placeHolder:'Select...',
style:{width:'150px'},
}, 'node_selBatch'
);
on(selTest, 'change', function(valueCard)
{
var selectedTest = this.get('displayedValue');
var selBatch = registry.byId('ID_selBatch');
console.debug('Connecting to gatherbatches.php ...');
request.post('gatherbatches.php',
{ data:{nameDB:registry.byId('ID_selPCBA').value, nameCard : valueCard},
handleAs: "json"}).then
(
function(response)
{
var memoStore2 = new Memory({data:response});
selBatch.set('store', memoStore2);
selBatch.set('value','');
console.debug('List of batches per Test is completed! Good OK! ');
},
function(error)
{
alert("Batch's Error:"+error);
console.debug('Problem: Listing batches per Test in select Test is BAD!');
}
);
selBatch.startup();
});
Error :
TypeError: _32[this.searchAttr] is null
defer() -> _WidgetBase.js (line 331)
_3() -> dojo.js (line 15)
_f.hitch(this,fcn)(); -> _WidgetBase.js (line 331)
Please advise though it might strange to have null values populate in the select box but these null values are related to data in other columns in database, so the null values included so that I can apply mysql scripts later. Or do you have other better suggestion?
Clement
You can create a QueryFilter as in this jsfiddle to achieve what you want, but it might be simpler to have two data items. Your original model with possibly null batch properties, and the model you pass to the store which is used by the ComboBox.
But anyway, this can work:
function createQueryFilter(originalQuery, filter) {
return function () {
var originalResults = originalQuery.apply(this, arguments);
var results = originalResults.filter(filter);
return QueryResults(results);
};
}
and
var memoStore = new Memory({
data: data
});
memoStore.query = createQueryFilter(memoStore.query, function (item) {
console.log(item);
return !!item.batch;
});
and the dummy data:
function createData1() {
var data = [];
for (var i = 0; i < 10; i++) {
data.push({
name: "" + i,
batch: (0 === i % 2) ? "batch" + i : null
});
}
return data;
}
Screenshot. The odd numbered batch items are null in my example.

Not updating list in the panel at the run time in sencha

i have two panel. when i'm click on the left panel items its calling web service and populating the right panel and same time its updating the number of items in the right panel to the left panel item which is clicked.
for first time its updating the left panel items but when i click on the other left panel item its not updating left panel items again.
its updating only first time.
my code is:
onInboxListTap:function (dataview, index, item, record) {
console.log('Inside onInboxListTap function');
var queuestore = dataview.getStore();
var rec = queuestore.getAt(index);
console.log(rec.data.workSetName);
var store = Ext.getStore('InboxWorkitemStore');
store.clearData(); //Function To clear WorkitemStore
//creating object of InboxQueueServices class
var inboxQueueServiceObject =
Ext.create('InfoImage.common.services.InboxQueueServices', {
config:{
scope:this
}
}, this.onQueueContentRetrievalSuccess, this.onQueueContentRetrievalFailure());
// calling loadQueueContent function to load queue contents
inboxQueueServiceObject.loadQueueContent(rec.data.workSetName);
},
//To call Function onQueueContentRetrievalSuccess after loadQueueContent successful
onQueueContentRetrievalSuccess:function () {
console.log('Inside onQueueContent Retrieval Success function');
var store = Ext.getStore('InboxWorkitemStore');
//Getting componenet queueDetails list
var inboxWorkitemList = Ext.getCmp('inboxWorkitemList');
var queueDetails = Ext.getCmp('queueDetails');
var queueList = Ext.getCmp('queuelist'); //Getting component list
var queueViewPanel = Ext.getCmp('queueViewPanel'); //Getting queueViewPanel
queueDetails.setStore(store);
store.sync();
var queueCount = store.getCount();
if (queueCount > 0) {
var queueItem = store.getAt(0);
var queueStore = queueList.getStore();
queueStore.each(function (record) {
if (record.get('workSetName') == queueItem.get('sourceWorkstep')) {
record.data.queueName = queueItem.get('sourceWorkstep') + '(' +
queueCount + ')';
}
});
queueList.setStore(queueStore);
queueStore.sync();
queueList.getStore().each(function (record) {
console.log('queueList:' + record.data.queueName);
});
console.log('store UPDATED');
}
queueList.refresh();
console.log('store count: ' + store.getCount());
console.log(queueDetails);
// navigates the panel
queueViewPanel.animateActiveItem(
inboxWorkitemList, {
type:'slide',
direction:'up',
duration:250
});
},
Please help me on this isssue.
i have to set record for that i resolve it.
queueStore.each(function (record) {
if (record.get('workSetName') == workitem.get('sourceWorkset')) {
record.data.queueName = workitem.get('sourceWorkset')
+ '(' + queueCount + ')';
// queueStore.updateRecord(record.data.queueName);
record.set(record.data.queueName);
}
});