-
Notifications
You must be signed in to change notification settings - Fork 558
/
s3widgets.py
9091 lines (7876 loc) · 336 KB
/
s3widgets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
""" Custom UI Widgets
@requires: U{B{I{gluon}} <http://web2py.com>}
@copyright: 2009-2016 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
NB Widgets are processed upon form submission (before form validation)
in addition to when generating new forms (so are often processed twice)
"""
__all__ = ("S3ACLWidget",
"S3AddObjectWidget",
"S3AddPersonWidget",
"S3AddPersonWidget2",
"S3AutocompleteWidget",
"S3BooleanWidget",
"S3ColorPickerWidget",
"S3CalendarWidget",
"S3DateWidget",
"S3DateTimeWidget",
"S3EmbeddedComponentWidget",
"S3GroupedOptionsWidget",
#"S3RadioOptionsWidget",
"S3HiddenWidget",
"S3HierarchyWidget",
"S3HumanResourceAutocompleteWidget",
"S3ImageCropWidget",
"S3InvBinWidget",
"S3KeyValueWidget",
# Only used inside this module
#"S3LatLonWidget",
"S3LocationAutocompleteWidget",
"S3LocationDropdownWidget",
"S3LocationLatLonWidget",
"S3PasswordWidget",
"S3PhoneWidget",
"S3Selector",
"S3LocationSelector",
"S3LocationSelectorWidget",
"S3MultiSelectWidget",
"S3OrganisationAutocompleteWidget",
"S3OrganisationHierarchyWidget",
"S3PersonAutocompleteWidget",
"S3PentityAutocompleteWidget",
"S3PriorityListWidget",
"S3SelectWidget",
"S3SiteAutocompleteWidget",
"S3SliderWidget",
"S3StringWidget",
"S3TimeIntervalWidget",
#"S3UploadWidget",
"S3FixedOptionsWidget",
"S3QuestionWidget",
"CheckboxesWidgetS3",
"s3_comments_widget",
"s3_richtext_widget",
"search_ac",
"S3XMLContents",
"ICON",
)
import datetime
import json
import os
import re
try:
from dateutil.relativedelta import relativedelta
except ImportError:
import sys
print >> sys.stderr, "ERROR: dateutil module needed for Date handling"
raise
from gluon import *
# Here are dependencies listed for reference:
#from gluon import current
#from gluon.html import *
#from gluon.http import HTTP
#from gluon.validators import *
from gluon.html import BUTTON
from gluon.languages import lazyT
from gluon.sqlhtml import *
from gluon.storage import Storage
from s3datetime import S3DateTime
from s3utils import *
from s3validators import *
ogetattr = object.__getattribute__
repr_select = lambda l: len(l.name) > 48 and "%s..." % l.name[:44] or l.name
# Compact JSON encoding
SEPARATORS = (",", ":")
# =============================================================================
class S3ACLWidget(CheckboxesWidget):
"""
Widget class for ACLs
@todo: add option dependency logic (JS)
@todo: configurable vertical/horizontal alignment
"""
@staticmethod
def widget(field, value, **attributes):
requires = field.requires
if not isinstance(requires, (list, tuple)):
requires = [requires]
if requires:
if hasattr(requires[0], "options"):
options = requires[0].options()
values = []
for k in options:
if isinstance(k, (list, tuple)):
k = k[0]
try:
flag = int(k)
if flag == 0:
if value == 0:
values.append(k)
break
else:
continue
elif value and value & flag == flag:
values.append(k)
except ValueError:
pass
value = values
#return CheckboxesWidget.widget(field, value, **attributes)
attr = OptionsWidget._attributes(field, {}, **attributes)
options = [(k, v) for k, v in options if k != ""]
opts = []
cols = attributes.get("cols", 1)
totals = len(options)
mods = totals%cols
rows = totals/cols
if mods:
rows += 1
for r_index in range(rows):
tds = []
for k, v in options[r_index*cols:(r_index+1)*cols]:
tds.append(TD(INPUT(_type="checkbox",
_name=attr.get("_name", field.name),
requires=attr.get("requires", None),
hideerror=True, _value=k,
value=(k in value)), v))
opts.append(TR(tds))
if opts:
opts[-1][0][0]["hideerror"] = False
return TABLE(*opts, **attr)
# was values = re.compile("[\w\-:]+").findall(str(value))
#values = not isinstance(value,(list,tuple)) and [value] or value
#requires = field.requires
#if not isinstance(requires, (list, tuple)):
#requires = [requires]
#if requires:
#if hasattr(requires[0], "options"):
#options = requires[0].options()
#else:
#raise SyntaxError, "widget cannot determine options of %s" \
#% field
# =============================================================================
class S3AddObjectWidget(FormWidget):
"""
This widget displays an inline form loaded via AJAX on demand.
UNUSED
In the browser:
A load request must made to this widget to enable it.
The load request must include:
- a URL for the form
after a successful submission, the response callback is handed the
response.
"""
def __init__(self,
form_url,
table_name,
dummy_field_selector,
on_show,
on_hide
):
self.form_url = form_url
self.table_name = table_name
self.dummy_field_selector = dummy_field_selector
self.on_show = on_show
self.on_hide = on_hide
def __call__(self, field, value, **attributes):
T = current.T
s3 = current.response.s3
if s3.debug:
script_name = "/%s/static/scripts/jquery.ba-resize.js"
else:
script_name = "/%s/static/scripts/jquery.ba-resize.min.js"
if script_name not in s3.scripts:
s3.scripts.append(script_name)
return TAG[""](
# @ToDo: Move to Static
SCRIPT('''
$(function () {
var form_field = $('#%(form_field_name)s')
var throbber = $('<div id="%(form_field_name)s_ajax_throbber" class="throbber"/>')
throbber.hide()
throbber.insertAfter(form_field)
function request_add_form() {
throbber.show()
var dummy_field = $('%(dummy_field_selector)s')
// create an element for the form
var form_iframe = document.createElement('iframe')
var $form_iframe = $(form_iframe)
$form_iframe.attr('id', '%(form_field_name)s_form_iframe')
$form_iframe.attr('frameborder', '0')
$form_iframe.attr('scrolling', 'no')
$form_iframe.attr('src', '%(form_url)s')
var initial_iframe_style = {
width: add_object_link.width(),
height: add_object_link.height()
}
$form_iframe.css(initial_iframe_style)
function close_iframe() {
$form_iframe.unload()
form_iframe.contentWindow.close()
//iframe_controls.remove()
$form_iframe.animate(
initial_iframe_style,
{
complete: function () {
$form_iframe.remove()
add_object_link.show()
%(on_hide)s
dummy_field.show()
}
}
)
}
function reload_iframe() {
form_iframe.contentWindow.location.reload(true)
}
function resize_iframe_to_fit_content() {
var form_iframe_content = $form_iframe.contents().find('body');
// do first animation smoothly
$form_iframe.animate(
{
height: form_iframe_content.outerHeight(true),
width: 500
},
{
duration: jQuery.resize.delay,
complete: function () {
// iframe's own animations should be instant, as they
// have their own smoothing (e.g. expanding error labels)
function resize_iframe_to_fit_content_immediately() {
$form_iframe.css({
height: form_iframe_content.outerHeight(true),
width:500
})
}
// if the iframe content resizes, resize the iframe
// this depends on Ben Alman's resize plugin
form_iframe_content.bind(
'resize',
resize_iframe_to_fit_content_immediately
)
// when unloading, unbind the resizer (remove poller)
$form_iframe.bind(
'unload',
function () {
form_iframe_content.unbind(
'resize',
resize_iframe_to_fit_content_immediately
)
//iframe_controls.hide()
}
)
// there may have been content changes during animation
// so resize to make sure they are shown.
form_iframe_content.resize()
//iframe_controls.show()
%(on_show)s
}
}
)
}
function iframe_loaded() {
dummy_field.hide()
resize_iframe_to_fit_content()
form_iframe.contentWindow.close_iframe = close_iframe
throbber.hide()
}
$form_iframe.bind('load', iframe_loaded)
function set_object_id() {
// the server must give the iframe the object
// id of the created object for the field
// the iframe must also close itself.
var created_object_representation = form_iframe.contentWindow.created_object_representation
if (created_object_representation) {
dummy_field.val(created_object_representation)
}
var created_object_id = form_iframe.contentWindow.created_object_id
if (created_object_id) {
form_field.val(created_object_id)
close_iframe()
}
}
$form_iframe.bind('load', set_object_id)
add_object_link.hide()
/*
var iframe_controls = $('<span class="iframe_controls" style="float:right; text-align:right;"></span>')
iframe_controls.hide()
var close_button = $('<a>%(Close)s </a>')
close_button.click(close_iframe)
var reload_button = $('<a>%(Reload)s </a>')
reload_button.click(reload_iframe)
iframe_controls.append(close_button)
iframe_controls.append(reload_button)
iframe_controls.insertBefore(add_object_link)
*/
$form_iframe.insertAfter(add_object_link)
}
var add_object_link = $('<a>%(Add)s</a>')
add_object_link.click(request_add_form)
add_object_link.insertAfter(form_field)
})''' % dict(
field_name = field.name,
form_field_name = "_".join((self.table_name, field.name)),
form_url = self.form_url,
dummy_field_selector = self.dummy_field_selector(self.table_name, field.name),
on_show = self.on_show,
on_hide = self.on_hide,
Add = T("Add..."),
Reload = T("Reload"),
Close = T("Close"),
)
)
)
# =============================================================================
class S3AddPersonWidget(FormWidget):
"""
Renders a person_id field as a Create Person form,
with an embedded Autocomplete to select existing people.
It relies on JS code in static/S3/s3.select_person.js
"""
def __init__(self,
controller = None,
select_existing = None):
# Controller to retrieve the person record
self.controller = controller
if select_existing is not None:
self.select_existing = select_existing
else:
self.select_existing = current.deployment_settings.get_pr_select_existing()
def __call__(self, field, value, **attributes):
T = current.T
request = current.request
appname = request.application
s3 = current.response.s3
settings = current.deployment_settings
formstyle = s3.crud.formstyle
default = dict(_type = "text",
value = (value is not None and str(value)) or "")
attr = StringWidget._attributes(field, default, **attributes)
attr["_class"] = "hide"
# Main Input
if "_id" in attr:
real_input = attr["_id"]
else:
real_input = str(field).replace(".", "_")
if self.controller is None:
controller = request.controller
else:
controller = self.controller
if self.select_existing:
# Autocomplete
select = '''S3.select_person($('#%s').val())''' % real_input
widget = S3PersonAutocompleteWidget(post_process=select,
hideerror=True)
ac_row = TR(TD(LABEL("%s: " % T("Name"),
_class="hide",
_id="person_autocomplete_label"),
widget(field,
None,
_class="hide")),
TD(),
_id="person_autocomplete_row",
_class="box_top")
# Select from registry buttons
_class ="box_top"
select_row = TR(TD(A(T("Select from Registry"),
_href="#",
_id="select_from_registry",
_class="action-btn"),
A(T("Remove selection"),
_href="#",
_onclick='''S3.select_person_clear_form()''',
_id="clear_form_link",
_class="action-btn hide",
_style="padding-left:15px"),
A(T("Edit Details"),
_href="#",
_onclick='''S3.select_person_edit_form()''',
_id="edit_selected_person_link",
_class="action-btn hide",
_style="padding-left:15px"),
DIV(_id="person_load_throbber",
_class="throbber hide",
_style="padding-left:85px"),
_class="w2p_fw"),
TD(),
_id="select_from_registry_row",
_class=_class,
_controller=controller,
_field=real_input,
_value=str(value))
else:
_class = "hide"
ac_row = ""
select_row = TR(TD(A(T("Edit Details"),
_href="#",
_onclick='''S3.select_person_edit_form()''',
_id="edit_selected_person_link",
_class="action-btn hide",
_style="padding-left:15px"),
DIV(_id="person_load_throbber",
_class="throbber hide",
_style="padding-left:85px"),
_class="w2p_fw"),
TD(),
_id="select_from_registry_row",
_class=_class,
_controller=controller,
_field=real_input,
_value=str(value))
# Embedded Form
s3db = current.s3db
ptable = s3db.pr_person
ctable = s3db.pr_contact
fields = [ptable.first_name,
ptable.middle_name,
ptable.last_name,
]
if settings.get_pr_request_dob():
fields.append(ptable.date_of_birth)
if settings.get_pr_request_gender():
fields.append(ptable.gender)
# Determine validation rule for email address
if controller == "hrm":
emailRequired = settings.get_hrm_email_required()
elif controller == "vol":
fields.append(s3db.pr_person_details.occupation)
emailRequired = settings.get_hrm_email_required()
else:
emailRequired = False
if emailRequired:
email_requires = IS_EMAIL()
else:
email_requires = IS_EMPTY_OR(IS_EMAIL())
# Determine validation rule for mobile phone number
mobile_phone_requires = IS_EMPTY_OR(IS_PHONE_NUMBER(
international = True))
# Add fields for email and mobile phone number
fields.extend([Field("email",
notnull=emailRequired,
requires=email_requires,
label=T("Email Address")),
Field("mobile_phone",
label=T("Mobile Phone Number"),
requires=mobile_phone_requires),
])
labels, required = s3_mark_required(fields)
if required:
s3.has_required = True
record_id = value if value else 0
# Generate embedded form
formname = "person_embedded"
form = SQLFORM.factory(table_name="pr_person",
labels=labels,
formstyle=formstyle,
upload="default/download",
separator = "",
record_id = record_id,
*fields)
if request.env.request_method == "POST":
# Read POST data
post_vars = request.post_vars
values = Storage(ptable._filter_fields(post_vars))
values["email"] = post_vars["email"]
values["mobile_phone"] = post_vars["mobile_phone"]
# Validate form
values["_formname"] = formname
valid = form.validate(request_vars=values,
session=None,
keepvalues=True,
hideerror=False,
formname=formname,
onsuccess=None,
onfailure=None,
onchange=None)
# Re-package the child elements of the FORM into a DIV,
# so that they can get embedded as widget in the outer FORM
trs = []
for tr in form[0]:
if "_id" in tr.attributes:
# Standard formstyle
if tr.attributes["_id"].startswith("submit_record"):
# skip submit row
continue
elif "_id" in tr[0][0].attributes:
# DIV-based formstyle
if tr[0][0].attributes["_id"].startswith("submit_record"):
# skip submit row
continue
if "_class" in tr.attributes:
tr.attributes["_class"] = "%s box_middle" % \
tr.attributes["_class"]
else:
tr.attributes["_class"] = "box_middle"
trs.append(tr)
table = DIV(*trs)
# Divider
divider = TR(TD(_class="subheading"),
TD(),
_class="box_bottom")
# JS
if s3.debug:
script = "/%s/static/scripts/S3/s3.select_person.js" % appname
else:
script = "/%s/static/scripts/S3/s3.select_person.min.js" % appname
scripts = s3.scripts
if script not in scripts:
scripts.append(script)
s3.jquery_ready.append('''S3.addPersonWidget()''')
# Overall layout of components
return TAG[""](select_row,
ac_row,
table,
divider)
# =============================================================================
class S3AddPersonWidget2(FormWidget):
"""
Renders a person_id or human_resource_id field as a Create Person form,
with an embedded Autocomplete to select existing people.
It relies on JS code in static/S3/s3.add_person.js
and s3validators.IS_ADD_PERSON_WIDGET2
@ToDo: get working AC/validator for human_resource_id
- perhaps re-implement as S3SQLFormElement
"""
def __init__(self,
controller = None,
separate_name_fields = None,
father_name = None,
grandfather_name = None,
year_of_birth = None, # Whether to use Year of Birth (as well as, or instead of, Date of Birth)
):
# Controller to retrieve the person or hrm record
self.controller = controller
self.separate_name_fields = separate_name_fields
self.father_name = father_name
self.grandfather_name = grandfather_name
self.year_of_birth = year_of_birth
def __call__(self, field, value, **attributes):
default = dict(_type = "text",
value = (value is not None and str(value)) or "")
attr = StringWidget._attributes(field, default, **attributes)
attr["_class"] = "hide"
request = current.request
POST = request.env.request_method == "POST"
if not value and POST:
# Read the POST vars:
values = request.post_vars
# @ToDo: Format these for Display?
if values.get(str(field).split(".", 1)[1], None) and \
"full_name" not in values and "first_name" not in values:
# We selected an existing user...this would fail as the non-existent gender would fail to validate
# and we can optimise by simply returning the simple widget
return INPUT(**attr)
else:
values = {}
s3db = current.s3db
field_type = field.type[10:]
if field_type == "pr_person":
# person_id
hrm = False
fn = "person"
elif field_type == "hrm_human_resource":
# human_resource_id
hrm = True
fn = "human_resource"
htable = s3db.hrm_human_resource
organisation_id = htable.organisation_id
else:
# Unsupported
raise
s3 = current.response.s3
# Test the formstyle
formstyle = s3.crud.formstyle
row = formstyle("test", "test", "test", "test")
if isinstance(row, tuple):
# Formstyle with separate row for label (e.g. old default Eden formstyle)
tuple_rows = True
else:
# Formstyle with just a single row (e.g. Bootstrap, Foundation or DRRPP)
tuple_rows = False
#if "form-row" in row["_class"]:
# # Foundation formstyle
# foundation = True
#else:
# foundation = False
settings = current.deployment_settings
separate_name_fields = self.separate_name_fields
if separate_name_fields is None:
separate_name_fields = settings.get_pr_separate_name_fields()
if separate_name_fields:
middle_name = separate_name_fields == 3
date_of_birth = None
year_of_birth = self.year_of_birth
ptable = s3db.pr_person
dtable = s3db.pr_person_details
first_name_field = ptable.first_name
middle_name_field = ptable.middle_name
last_name_field = ptable.last_name
if year_of_birth is None:
# Use Global deployment_setting
year_of_birth = settings.get_pr_request_year_of_birth()
if year_of_birth:
year_of_birth = dtable.year_of_birth
if settings.get_pr_request_dob():
date_of_birth = ptable.date_of_birth
dob_required = settings.get_pr_dob_required()
if settings.get_pr_request_gender():
gender = ptable.gender
if POST:
gender.requires = IS_EMPTY_OR(gender.requires)
else:
gender = None
req_email = settings.get_pr_request_email()
req_home_phone = settings.get_pr_request_home_phone()
req_mobile_phone = settings.get_pr_request_mobile_phone()
emailRequired = settings.get_hrm_email_required()
# Determine controller for autocomplete
controller = self.controller
if not controller:
controller = request.controller
if controller not in ("hrm", "vol"):
if hrm:
# Always use hrm for human_resource_id
controller = "hrm"
else:
# Always use pr for person_id
controller = "pr"
emailRequired = False
# Widget-Options for additional fields
father_name = self.father_name
grandfather_name = self.grandfather_name
if father_name is None:
# Use Global deployment_setting
father_name = settings.get_pr_request_father_name()
if father_name:
father_name = dtable.father_name
if grandfather_name is None:
# Use Global deployment_setting
grandfather_name = settings.get_pr_request_grandfather_name()
if grandfather_name:
grandfather_name = dtable.grandfather_name
if controller == "vol":
occupation = dtable.occupation
else:
occupation = None
if value:
db = current.db
fields = [first_name_field,
middle_name_field,
last_name_field,
ptable.pe_id,
]
details = False
if hrm:
query = (htable.id == value) & \
(htable.person_id == ptable.id)
fields.append(htable.organisation_id)
else:
query = (ptable.id == value)
if date_of_birth:
fields.append(date_of_birth)
if gender:
fields.append(gender)
if father_name:
fields.append(father_name)
details = True
if grandfather_name:
fields.append(grandfather_name)
details = True
if occupation:
fields.append(occupation)
details = True
if year_of_birth:
fields.append(year_of_birth)
details = True
if details:
left = dtable.on(dtable.person_id == ptable.id)
else:
left = None
row = db(query).select(*fields,
left=left,
limitby=(0, 1)).first()
if details or hrm:
person = row["pr_person"]
if details:
person_details = row["pr_person_details"]
if hrm:
human_resource = row["hrm_human_resource"]
else:
person = row
if hrm:
values["organisation_id"] = human_resource.organisation_id
if occupation:
values["occupation"] = person_details.occupation
if father_name:
values["father_name"] = person_details.father_name
if grandfather_name:
values["grandfather_name"] = person_details.grandfather_name
if separate_name_fields:
values["first_name"] = person.first_name
values["last_name"] = person.last_name
if middle_name:
values["middle_name"] = person.middle_name
else:
values["full_name"] = s3_fullname(person)
if year_of_birth:
values["year_of_birth"] = person_details.year_of_birth
if date_of_birth:
values["date_of_birth"] = person.date_of_birth
if gender:
values["gender"] = person.gender
# Contacts as separate query as we can't easily limitby
contact_methods = []
if req_email:
contact_methods.append("EMAIL")
if req_home_phone:
contact_methods.append("HOME_PHONE")
if req_mobile_phone:
contact_methods.append("SMS")
email = mobile_phone = home_phone = ""
if contact_methods:
ctable = s3db.pr_contact
query = (ctable.pe_id == person.pe_id) & \
(ctable.deleted == False) & \
(ctable.contact_method.belongs(contact_methods))
contacts = db(query).select(ctable.contact_method,
ctable.value,
orderby=ctable.priority,
)
for contact in contacts:
if req_email and not email and contact.contact_method == "EMAIL":
email = contact.value
elif not mobile_phone and contact.contact_method == "SMS":
mobile_phone = contact.value
elif req_home_phone and not home_phone and contact.contact_method == "HOME_PHONE":
home_phone = contact.value
if mobile_phone and \
((req_email and email) or (not req_email)) and \
((req_home_phone and home_phone) or (not req_home_phone)):
break
values["home_phone"] = home_phone
values["email"] = email
values["mobile_phone"] = mobile_phone
# Output
T = current.T
rows = DIV()
fieldname = str(field).replace(".", "_")
# Section Title
_id = "%s_title" % fieldname
label = field.label
label = LABEL(label, _for=_id)
# @ToDo: Check Permissions for existing person records to know whether we can edit the person or simply select a different one
widget = DIV(A(ICON("edit"),
_title=T("Edit Entry"), # "Edit Selection"
),
A(ICON("remove"),
_title=T("Revert Entry"), # "Clear Selection"
),
_class="add_person_edit_bar hide",
_id="%s_edit_bar" % fieldname,
)
comment = ""
#if bootstrap:
# # We would like to hide the whole original control-group & append rows, but that can't be done directly within a Widget
# # -> Elements moved via JS after page load
# label.add_class("control-label")
# _controls = DIV(widget, _class="controls")
# row = DIV(label, _controls,
# _class="control-group hide box_top",
# _id="%s__row" % _id,
# )
# rows.append(row)
#else:
if tuple_rows:
# We want label & widget in 1 row, so position abnormally
# We also want to put a margin on top of the box, which isn't possible with a TD
row = TR(TD(DIV(label,
widget,
_class="box_top_inner",
),
_class="box_top_td",
_colspan=2,
),
_id="%s__row" % _id,
)
rows.append(row)
else:
row = formstyle("%s__row" % _id, label, widget, comment)
row.add_class("box_top hide")
rows.append(row)
# Fields
# (id, label, widget, required)
data = {"c": controller,
"f": fn,
}
delay = settings.get_ui_autocomplete_delay()
if delay != 800:
data["delay"] = delay
chars = settings.get_ui_autocomplete_min_chars()
if chars != 2:
data["chars"] = chars
fields = []
fappend = fields.append
if hrm:
fappend(("organisation_id", organisation_id.label,
OptionsWidget.widget(organisation_id, values.get("organisation_id", None),
_id = "%s_organisation_id" % fieldname),
settings.get_hrm_org_required()))
if separate_name_fields:
mandatory_lastname = settings.get_L10n_mandatory_lastname()
mandatory_middlename = settings.get_L10n_mandatory_middlename()
name_format = settings.get_pr_name_format()
if name_format == "%(last_name)s %(middle_name)s %(first_name)s":
# Vietnamese Style
fappend(("last_name", last_name_field.label, INPUT(data=data, _size=40), mandatory_lastname))
if middle_name:
fappend(("middle_name", middle_name_field.label, INPUT(_size=40), mandatory_middlename))
fappend(("first_name", first_name_field.label, INPUT(_size=40), True))
elif name_format == "%(last_name)s, %(first_name)s":
# DRK Style
fappend(("last_name", last_name_field.label, INPUT(data=data, _size=40), mandatory_lastname))
fappend(("first_name", first_name_field.label, INPUT(_size=40), True))
else:
fappend(("first_name", first_name_field.label, INPUT(data=data, _size=40), True))
if middle_name:
fappend(("middle_name", middle_name_field.label, INPUT(_size=40), mandatory_middlename))
fappend(("last_name", last_name_field.label, INPUT(_size=40), mandatory_lastname))
else:
# Unified Name field
# - can search for an existing person
# - can create a new person
# - multiple names get assigned to first, middle, last
full_name_label = settings.get_pr_label_fullname()
fappend(("full_name", T(full_name_label), INPUT(data=data, _size=40), True))
if father_name:
fappend(("father_name", father_name.label, INPUT(), False))
if grandfather_name:
fappend(("grandfather_name", grandfather_name.label, INPUT(), False))
if year_of_birth:
fappend(("year_of_birth", year_of_birth.label, INPUT(), False))
elif date_of_birth:
fappend(("date_of_birth", date_of_birth.label,
date_of_birth.widget(date_of_birth, values.get("date_of_birth", None),
_id = "%s_date_of_birth" % fieldname),
dob_required))
if gender:
fappend(("gender", gender.label,
OptionsWidget.widget(gender, values.get("gender", None),
_id = "%s_gender" % fieldname),
False))
if occupation:
fappend(("occupation", occupation.label, INPUT(), False))
if req_email:
fappend(("email", T("Email"), INPUT(), emailRequired))
if req_mobile_phone:
fappend(("mobile_phone", settings.get_ui_label_mobile_phone(), INPUT(), False))
if req_home_phone:
fappend(("home_phone", T("Home Phone"), INPUT(), False))
for f in fields: