1 (function(angular
, $, _
) {
2 // Represent a datetime field as if it were a radio ('schedule.mode') and a datetime ('schedule.datetime').
3 // example: <div crm-mailing-radio-date="mySchedule" ng-model="mailing.scheduled_date">...</div>
4 angular
.module('crmMailing').directive('crmMailingRadioDate', function(crmUiAlert
) {
7 link: function($scope
, element
, attrs
, ngModel
) {
9 var schedule
= $scope
[attrs
.crmMailingRadioDate
] = {
14 ngModel
.$render
= function $render() {
15 var sched
= ngModel
.$viewValue
;
16 if (!_
.isEmpty(sched
)) {
18 schedule
.datetime
= sched
;
21 schedule
.mode
= 'now';
22 schedule
.datetime
= '';
26 var updateParent
= (function() {
27 switch (schedule
.mode
) {
29 ngModel
.$setViewValue(null);
30 schedule
.datetime
= '';
33 schedule
.datetime
= schedule
.datetime
|| '?';
34 ngModel
.$setViewValue(schedule
.datetime
);
37 throw 'Unrecognized schedule mode: ' + schedule
.mode
;
42 // Open datepicker when clicking "At" radio
43 .on('click', ':radio[value=at]', function() {
44 $('.crm-form-date', element
).focus();
46 // Reset mode if user entered an invalid date
47 .on('change', '.crm-hidden-date', function(e
, context
) {
48 if (context
=== 'userInput' && $(this).val() === '' && $(this).siblings('.crm-form-date').val().length
) {
50 schedule
.datetime
= '?';
53 month
= '' + (d
.getMonth() + 1),
54 day
= '' + d
.getDate(),
55 year
= d
.getFullYear(),
56 hours
= '' + d
.getHours(),
57 minutes
= '' + d
.getMinutes();
58 var submittedDate
= $(this).val();
59 if (month
.length
< 2) month
= '0' + month
;
60 if (day
.length
< 2) day
= '0' + day
;
61 date
= [year
, month
, day
].join('-');
62 time
= [hours
, minutes
, "00"].join(':');
63 currentDate
= date
+ ' ' + time
;
64 ngModel
.$setValidity('dateTimeInThePast', !($(this).val().length
&& submittedDate
< currentDate
));
65 if ($(this).val().length
&& submittedDate
< currentDate
) {
67 text
: ts('The scheduled date and time is in the past'),
74 $scope
.$watch(attrs
.crmMailingRadioDate
+ '.mode', updateParent
);
75 $scope
.$watch(attrs
.crmMailingRadioDate
+ '.datetime', function(newValue
, oldValue
) {
76 // automatically switch mode based on datetime entry
77 if (typeof oldValue
=== 'undefined') {
80 if (typeof newValue
=== 'undefined') {
83 if (oldValue
!== newValue
) {
84 if (_
.isEmpty(newValue
)) {
85 schedule
.mode
= 'now';
96 })(angular
, CRM
.$, CRM
._
);