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 if (hours
.length
< 2) hours
= '0' + hours
;
62 if (minutes
.length
< 2) minutes
= '0' + minutes
;
63 date
= [year
, month
, day
].join('-');
64 time
= [hours
, minutes
, "00"].join(':');
65 currentDate
= date
+ ' ' + time
;
66 ngModel
.$setValidity('dateTimeInThePast', !($(this).val().length
&& submittedDate
< currentDate
));
67 if ($(this).val().length
&& submittedDate
< currentDate
) {
69 text
: ts('The scheduled date and time is in the past'),
76 $scope
.$watch(attrs
.crmMailingRadioDate
+ '.mode', updateParent
);
77 $scope
.$watch(attrs
.crmMailingRadioDate
+ '.datetime', function(newValue
, oldValue
) {
78 // automatically switch mode based on datetime entry
79 if (typeof oldValue
=== 'undefined') {
82 if (typeof newValue
=== 'undefined') {
85 if (oldValue
!== newValue
) {
86 if (_
.isEmpty(newValue
)) {
87 schedule
.mode
= 'now';
98 })(angular
, CRM
.$, CRM
._
);