Odoo 12: How to disable past dates with datepicker? - datepicker

How can I use datepicker in a Date field?
I try to disable past dates like that:
<field class="delivery_date" name="delivery_date" options="{'datepicker':{'minDate': 0}}"/>
But past dates are shown nevertheless.
It seems as if the options-tag is not parsed at all. I used the debugger to get an overview what happens in addons/web/static/src/js/fields/basic_fields.js (where datepicker is initialized) but there are no options declared.
Thanks in advance!
UPDATE:
That's my field definition
delivery_date = fields.Date(string='Delivery Date', help="Date on which sales order is delivered.", default=_get_default_delivery_date)
The default-method sets the date to the day after tomorrow.
My view declaration is above. That's all I have.
I expected that the datepicker is invoked as soon as I use it in "options"-attribute.
When I enter my website the datepicker is shown, when I click on that date-field, but the past dates are not disabled..

I tried multiple modules, but nothing works for me in js Odoo 14
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(AccountInvoice, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
if view_type == 'form':
doc = etree.XML(res['arch'])
for node in doc.xpath("//field[#name='date_invoice']"):
node.set('options', "{'datepicker': {'minDate': '%sT23:59:59'}}" % fields.Date.today().strftime(DEFAULT_SERVER_DATE_FORMAT))
res['arch'] = etree.tostring(doc)
return res
Try this, This may help you

Related

Conditional formatting for dates

I'm trying to come up with a simple conditional format formula for highlighting cells that have a date that is greater than three months older than today's date. It seems though that the "Date is before" option only gives a few options, none of them seem to allow what I'm looking for. Is there a custom formula that could accomplish this?
Edit: attaching a snip of the column in question:
Formula :
=DAYS(now(),B2)>90
Go to the custom formula in the conditional formating rules and use this:
=DATEDIF(A1,TODAY(),"D")<90
try:
=1*C2>DATE(YEAR(TODAY()), MONTH(TODAY())+3, DAY(TODAY()))
also make sure you have valid dates and not plain text dates. you can test this with ISDATE formula
You can use Apps Script and a Custom Menu in order to solve your issue with setting the color in the cell depending on the date. Go to Tools->Script Editor and paste this code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Check Difference', 'dateDifference')
.addToUi();
}
function dateDifference(){
var sheet = SpreadsheetApp.getActiveSheet().getActiveRange(); // Get the selected range on the sheet
var dates = sheet.getValues(); // Get the values in the selected range
var oneDay = 1000*60*60*24;
var row = 1;
var re = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/; // This will help you to check if it's really a date
dates.forEach(function(el){ // Iterate over each value
if(typeof el[0] == 'object'){ // Check if it's really a date
var gmtZone = el[0].toString().split(" ")[4].split(":")[0]; // Take the date's GMT
var dateFormatted = Utilities.formatDate(el[0], gmtZone, "dd/MM/yyyy"); // Format the date
if(re.test(dateFormatted)){ // Test if it's the right format
// This part will calculate the difference between the current date and the future date
var futureDateMs = new Date(el[0]);
var todayDateMs = (new Date()).getTime();
var differenceInMs = futureDateMs - todayDateMs;
var differenceInDays = Math.round(differenceInMs/oneDay);
if(differenceInDays >= 91.2501){ // Test if the difference it's greater to 91.2501 days (3 motnhs)
sheet.getCell(row, 1).setBackground("#00FF00"); // Set the color to the cell
}
row++;
}
}
});
Save it by clicking on File->Save.
Then you can select a range in a column and click on Custom Menu->Check Difference as you can see in the next image:
As you can see, you will get the desired result:
Notice
It's really important to be careful with what you consider to be a "month", I mean how many days you are going to take into consideration. In my code, I took Google's suggestion of 1 = 30.4167.
Docs
These are other Docs I read to be able to help you:
Utilities.formatDate()
Working with Dates and Times.
I hope this approach can help you.

Add day to date with momentjs

I am trying to add a day to my date:
let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate);
However, this keeps returning an obscure object {_i: "2017-12-20T21:06:21+00:00", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array(7), …}
fiddle:
http://jsfiddle.net/rLjQx/4982/
Does anyone know what I might be doing wrong?
You are logging a moment object. As the Internal Properties guide states:
To print out the value of a Moment, use .format(), .toString() or .toISOString().
let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Please note that you can get the current date using moment() (no need to use new Date()) or moment.utc().
I will go with this one, simple works for me and I don't think you need other function to only add day in moment.
var yourPreviousDate = new Date();
var yourExpectedDate = moment(yourPreviousDate).add(1, 'd')._d;
The add method modifies the moment object. So when you log it, you're not getting an obscure object, you're getting the moment object you're working with. Are you expecting a formatted date? Then use format or some other method.
I agree with other answers just providing shortcut and different ways
You can do the format at the same time
moment().add(1,'d').format('YYYY-MM-DD');
or you can just format any date or date object
moment(result.StartDate).format('YYYY-MM-DD');

Utilities.formatDate() in Google Apps Script outputs previous date (e.g. input 25.05.2015 -> output 24.05.2015)

I have a problem with Google Docs' Utilities.formatDate() function.
I have a spreadsheet that contains all of the orders we place in the lab. When an order is delivered our lab manager enters the delivery date in the relevant cell in such a spreadsheet, in the following format: dd.MM.yyyy.
I created a script that, provided certain conditions, will email whoever placed that order alerting them that the order has been delivered on that particular date. Here is the code:
function DeliveryAlerts() {
try {
var email_dict = {"Y":"Y#Z.com"}
var spreadsheet = SpreadsheetApp.openById("ABC");
SpreadsheetApp.setActiveSpreadsheet(spreadsheet);
var sheet = spreadsheet.getSheetByName("Orders");
var values = sheet.getRange("A2:Q251").getValues();
var bgcolours = sheet.getRange("A2:Q251").getBackgrounds();
for(var i=0;i<=249;i++)
{
var j = i + 2;
if (values[i][16]=="Yes" && values[i][11]!="" && bgcolours[i][16]!="#b8b8b8")
{
var email_address = email_dict[values[i][13]];
var cur_date = Utilities.formatDate(values[i][11], "GMT+1", "EEE dd.MM.yyyy");
var message = "Hello there,\n\nYour order of " + values[i][4] + " has been delivered on "+ cur_date +".\n\nBest wishes";
var subject = "Delivery alert";
MailApp.sendEmail(email_address, subject, message,{replyTo:"abc#abc.com", name:"ABC"});
sheet.getRange("Q"+j).setBackground("#b8b8b8");
}
}
} catch (err) {
MailApp.sendEmail("abc#abc.com", "Delivery Alerts Script in Order Master List", err);
}
}
I use
Utilities.formatDate(values[i][11], "GMT+1", "EEE dd.MM.yyyy") to reformat the date from, say, 25.05.2015 (that is, the value in the cell) to Mon 25.05.2015. However, what I get instead is Sun 24.05.2015.
Does anybody know what is going on?
Thank you in advance.
Nicola
Check the time zone setting in the script editor. Under the FILE menu, choose PROJECT PROPERTIES in the script editor. It's possible to have a different time zone setting in Apps Script, than is in the spreadsheet. This is a common issue that arises. Apps Script allows a separate time zone setting from the spreadsheet. Also, even if the time is only off by one minute, if the time setting of the date is all zeros, it's common to get the problem that you are having. When a user enters a date, it's possible that no time setting is made. So the time is set to all zeros. The date is correct, but the time is all zeros. Even if the date was typed in at 3 in the afternoon, for example, and the date is correct, the time setting can be midnight of that day. So, even if you subtracted one second from that date, it would now be the day before.

Save date as timestamp in CQ5

I need t use the CQ5 xtype 'datefield' since I need only the date and not time tombe entered by the author.
But the issue is that 'datefield' saves the date in JCR as a String and not as a timestap [ as it does when 'datetime' is used.]
Is there a work around to save the date as a timestamp ?
I don't think it is possible to save the date as timestamp using datefield, without meddling with the default script. But as a workaround, you can use datetime and set the property hideTime to true, to hide the time part, so that the author will not be able to author it.
The json for the config is shown below.
{ "fieldLabel":"Date",
"xtype":"datetime",
"hideTime":true,
"name":"./date",
"defaultValue":"now",
"jcr:primaryType":"cq:Widget"
}
You can add defaultValue to 'now', if you want current date to be initialized as the default, if not explicitly filled in by the author, else it can be ignored.
NOTE: The defaultValue: 'now' doesnt work for me in IE (i am using IE 11 and emulating the previous versions through dev tools), but it works fine in Chrome and Mozilla.
A rough workaround for your jsp:
<%#page import="java.text.SimpleDateFormat,java.util.Date"%>
<%
SimpleDateFormat displayDateFormat = new SimpleDateFormat("dd MMM yyyy");
String dateField = properties.get("nameofdatefield", "");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
Date formattedDate = sdf.parse(dateField);
String formattedDateStr = displayDateFormat.format(formattedDate);
out.println('Example of formated string'+formattedDateStr);
%>
From the above, you can also convert it to a Date Object, depending on what you wish to manipulate.
Let me know if the above example helps

Date browsers problem - if manually changed and focus on it - did not save

I have a problem related to Date type which I'm using in smartgwt.
I set up the date to have the possibility to change it manually:
setAttribute("useTextField", true);
In Firefox and Chrome (and maybe other browsers , except Internet Explorer) if first I'm selecting a date with that pop-up calendar and than change it manually and then let the focus on the date field and going to save the document (actually is a form with multiple fields) the date changed manually it is lost, the date choosed from calendar it is saved. This is not happening in Internet Explorer.
In all browsers, if I select from Calendar a date and than change it manually and change the focus from it everythings goes fine - the manually changed date it is saved into db.
Need some advices.
Thank you a lot.
Later edit:
I'm using com.smartgwt.client.widgets.form.fields.DateItem widget.
DateItem date = new DateItem("A date");
date.setWidth(320);
date.setWrapTitle(false);
date.setAttribute("useTextField", true);
date.setAttribute("inputFormat", "yyyy/MM/dd");
date.setAttribute("displayFormat", "toJapanShortDate");
I'm adding this date on a DynamicForm:
DynamicForm form = new DynamicForm();
form.setFields(date);
and this form on a VLayout object:
VLayout editLayout = new VLayout(30);
editLayout.addMember(form);
The problem is reproducing in browsers like Firefox & Chrome when:
I'm selecting first the date from calendar - say I'm selecting 2011/02/11
I'm changing the day in 2011/02/12 manually - and I'm not changing the focus from this date field
I'm pressing the 'Save' button.
After these steps the date is 2011/02/11 and not 2011/02/12 how it should be.
In Internet Explorer browser did not happen - the date after the steps above is 2011/02/12!
Later edit:
I'm using a DataSource for updating the data.
I'm having a UserObject and in the userUpdate method I'm creating this user object first with values from fields (which are on the DynamicForm) - by calling the generateUserObjectFromForm() method
UserObject user = generateUserObjectFromForm();
Here, in this method I'm doing something like:
user.setAddedDate(date.getValueAsDate()),
but here the date.getValueAsDate() value is the one selected from calendar, not the one modified manually.
I've tried also with:
date.getValue() //Fri Feb 11 00:00:00 GMT+200 2011
date.getValueField() // null
date.getValueAsDate() //Fri Feb 11 00:00:00 GMT+200 2011
date.getDisplayField() //null
date.getDisplayValue()//l2011/02/11
but none worked properly.
I'm using an request object (UserUpdateRequest) for updating the user.
UserUpdateRequest looks like:
public class UserUpdateRequest implements IsSerializable
{
UserObject user = null;
public UserUpdateRequest ()
{
}
public UserUpdateRequest (UserObject user)
{
this.user = user;
}
public UserObject getUser ()
{
return user;
}
}
final UserUpdateRequest request = new UserUpdateRequest(user);
and on the RPC user update method I'm sending this UserUpdateRequest request.
Later edit (15 february):
I've discovered why is happening this issue related to focus, and this is because in the project I'm not using a Button object - and a com.google.gwt.event.dom.client.ClickEvent for it. I'm using a personalized widget:
package de.vogella.gwt.helloworld.client;
import com.smartgwt.client.widgets.Label;
public class buttonLabel extends Label
{
public buttonLabel (String text, String elementID)
{
super();
setContents(text);
setAutoWidth();
setBaseStyle("wwHoverLabel");
setShowRollOver(true);
}
}
and this use com.smartgwt.client.widgets.events.ClickHandler().
Anyway I do not know how to resolve this ....
I've created a small project with this issue where I've put also a Button object (Save1) and also a personalized button buttonLabel (Save2) - both with clickhandlers.
Here is the link where you can download sources of this small project I've created: link
Case1:
say for example we choose date 2011/02/16 and we change manually the date into 2011/02/17 and push the button Save1 - everything works fine - the date remains 2011/02/17
Case2-a - line
Window.alert("2 " + date.getValue()); un-commented:
say for example we choose date 2011/02/16 and we change manually the date into 2011/02/17 and push the button Save2 - in the warning message date value is 2011/02/16 but in the field date remains 2011/02/17
Case2-b - line
Window.alert("2 " + date.getValue()); uncommented:
say for example we choose date 2011/02/16 and we change manually the date into 2011/02/17 and push the button Save2 - the value from field date is automatically changed to 2011/02/16
Later later edit:
Since I can't figure out how to solve my problem I'm thinking for the moment at a temporary solution.
So, I have:
DateItem date = new DateItem("Adate");
date.setWidth(120);
date.setWrapTitle(false);
date.setAttribute("useTextField", true);
date.setAttribute("inputFormat", "yyyy/MM/dd");
date.setAttribute("displayFormat", "toJapanShortDate");
Because the attribute useTextField is set to true we can see the text entry field. How can I make this text entry field to be un-editable. Actually I want to have only the possibility to choose the date from calendar and not to change it manually.
The following code should work.
DateItem date = new DateItem("Adate");
date.setAttribute("useTextField", true);
date.setAttribute("inputFormat", "yyyy/MM/dd");
date.setAttribute("displayFormat", "toJapanShortDate");
TextItem textItem = new TextItem();
textItem.setAttribute("readOnly", "true");
date.setTextFieldProperties(textItem);