forked from jpetazzo/web2py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlhtml.py
2282 lines (2008 loc) · 90.1 KB
/
sqlhtml.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <[email protected]>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Holds:
- SQLFORM: provide a form for a table (with/without record)
- SQLTABLE: provides a table for a set of records
- form_factory: provides a SQLFORM for an non-db backed table
"""
from http import HTTP
from html import XML, SPAN, TAG, A, DIV, CAT, UL, LI, TEXTAREA, BR, IMG, SCRIPT
from html import FORM, INPUT, LABEL, OPTION, SELECT, MENU
from html import TABLE, THEAD, TBODY, TR, TD, TH, STYLE
from html import URL, truncate_string
from dal import DAL, Table, Row, CALLABLETYPES, smart_query
from storage import Storage
from utils import md5_hash
from validators import IS_EMPTY_OR, IS_NOT_EMPTY, IS_LIST_OF
import urllib
import re
import cStringIO
table_field = re.compile('[\w_]+\.[\w_]+')
widget_class = re.compile('^\w*')
def trap_class(_class=None,trap=True):
return (trap and 'w2p_trap' or '')+(_class and ' '+_class or '')
def represent(field,value,record):
f = field.represent
if not callable(f):
return str(value)
n = f.func_code.co_argcount-len(f.func_defaults or [])
if getattr(f, 'im_self', None): n -= 1
if n==1:
return f(value)
elif n==2:
return f(value,record)
else:
raise RuntimeError, "field representation must take 1 or 2 args"
def safe_int(x):
try:
return int(x)
except ValueError:
return 0
def safe_float(x):
try:
return float(x)
except ValueError:
return 0
class FormWidget(object):
"""
helper for SQLFORM to generate form input fields
(widget), related to the fieldtype
"""
_class = 'generic-widget'
@classmethod
def _attributes(cls, field,
widget_attributes, **attributes):
"""
helper to build a common set of attributes
:param field: the field involved,
some attributes are derived from this
:param widget_attributes: widget related attributes
:param attributes: any other supplied attributes
"""
attr = dict(
_id = '%s_%s' % (field._tablename, field.name),
_class = cls._class or \
widget_class.match(str(field.type)).group(),
_name = field.name,
requires = field.requires,
)
attr.update(widget_attributes)
attr.update(attributes)
return attr
@classmethod
def widget(cls, field, value, **attributes):
"""
generates the widget for the field.
When serialized, will provide an INPUT tag:
- id = tablename_fieldname
- class = field.type
- name = fieldname
:param field: the field needing the widget
:param value: value
:param attributes: any other attributes to be applied
"""
raise NotImplementedError
class StringWidget(FormWidget):
_class = 'string'
@classmethod
def widget(cls, field, value, **attributes):
"""
generates an INPUT text tag.
see also: :meth:`FormWidget.widget`
"""
default = dict(
_type = 'text',
value = (not value is None and str(value)) or '',
)
attr = cls._attributes(field, default, **attributes)
return INPUT(**attr)
class IntegerWidget(StringWidget):
_class = 'integer'
class DoubleWidget(StringWidget):
_class = 'double'
class DecimalWidget(StringWidget):
_class = 'decimal'
class TimeWidget(StringWidget):
_class = 'time'
class DateWidget(StringWidget):
_class = 'date'
class DatetimeWidget(StringWidget):
_class = 'datetime'
class TextWidget(FormWidget):
_class = 'text'
@classmethod
def widget(cls, field, value, **attributes):
"""
generates a TEXTAREA tag.
see also: :meth:`FormWidget.widget`
"""
default = dict(value = value)
attr = cls._attributes(field, default,
**attributes)
return TEXTAREA(**attr)
class BooleanWidget(FormWidget):
_class = 'boolean'
@classmethod
def widget(cls, field, value, **attributes):
"""
generates an INPUT checkbox tag.
see also: :meth:`FormWidget.widget`
"""
default=dict(_type='checkbox', value=value)
attr = cls._attributes(field, default,
**attributes)
return INPUT(**attr)
class OptionsWidget(FormWidget):
@staticmethod
def has_options(field):
"""
checks if the field has selectable options
:param field: the field needing checking
:returns: True if the field has options
"""
return hasattr(field.requires, 'options')
@classmethod
def widget(cls, field, value, **attributes):
"""
generates a SELECT tag, including OPTIONs (only 1 option allowed)
see also: :meth:`FormWidget.widget`
"""
default = dict(value=value)
attr = cls._attributes(field, default,
**attributes)
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
opts = [OPTION(v, _value=k) for (k, v) in options]
return SELECT(*opts, **attr)
class ListWidget(StringWidget):
@classmethod
def widget(cls, field, value, **attributes):
_id = '%s_%s' % (field._tablename, field.name)
_name = field.name
if field.type=='list:integer': _class = 'integer'
else: _class = 'string'
requires = field.requires if isinstance(field.requires, (IS_NOT_EMPTY, IS_LIST_OF)) else None
items=[LI(INPUT(_id=_id, _class=_class, _name=_name, value=v, hideerror=True, requires=requires)) \
for v in value or ['']]
script=SCRIPT("""
// from http://refactormycode.com/codes/694-expanding-input-list-using-jquery
(function(){
jQuery.fn.grow_input = function() {
return this.each(function() {
var ul = this;
jQuery(ul).find(":text").after('<a href="javascript:void(0)>+</a>').keypress(function (e) { return (e.which == 13) ? pe(ul) : true; }).next().click(function(){ pe(ul) });
});
};
function pe(ul) {
var new_line = ml(ul);
rel(ul);
new_line.appendTo(ul);
new_line.find(":text").focus();
return false;
}
function ml(ul) {
var line = jQuery(ul).find("li:first").clone(true);
line.find(':text').val('');
return line;
}
function rel(ul) {
jQuery(ul).find("li").each(function() {
var trimmed = jQuery.trim(jQuery(this.firstChild).val());
if (trimmed=='') jQuery(this).remove(); else jQuery(this.firstChild).val(trimmed);
});
}
})();
jQuery(document).ready(function(){jQuery('#%s_grow_input').grow_input();});
""" % _id)
attributes['_id']=_id+'_grow_input'
return TAG[''](UL(*items,**attributes),script)
class MultipleOptionsWidget(OptionsWidget):
@classmethod
def widget(cls, field, value, size=5, **attributes):
"""
generates a SELECT tag, including OPTIONs (multiple options allowed)
see also: :meth:`FormWidget.widget`
:param size: optional param (default=5) to indicate how many rows must
be shown
"""
attributes.update(dict(_size=size, _multiple=True))
return OptionsWidget.widget(field, value, **attributes)
class RadioWidget(OptionsWidget):
@classmethod
def widget(cls, field, value, **attributes):
"""
generates a TABLE tag, including INPUT radios (only 1 option allowed)
see also: :meth:`FormWidget.widget`
"""
attr = cls._attributes(field, {}, **attributes)
attr['_class'] = attr.get('_class','web2py_radiowidget')
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
options = [(k, v) for k, v in options if str(v)]
opts = []
cols = attributes.get('cols',1)
totals = len(options)
mods = totals%cols
rows = totals/cols
if mods:
rows += 1
#widget style
wrappers = dict(
table=(TABLE,TR,TD),
ul=(DIV,UL,LI),
divs=(CAT,DIV,DIV)
)
parent, child, inner = wrappers[attributes.get('style','table')]
for r_index in range(rows):
tds = []
for k, v in options[r_index*cols:(r_index+1)*cols]:
checked={'_checked':'checked'} if k==value else {}
tds.append(inner(INPUT(_type='radio',
_id='%s%s' % (field.name,k),
_name=field.name,
requires=attr.get('requires',None),
hideerror=True, _value=k,
value=value,
**checked),
LABEL(v,_for='%s%s' % (field.name,k))))
opts.append(child(tds))
if opts:
opts[-1][0][0]['hideerror'] = False
return parent(*opts, **attr)
class CheckboxesWidget(OptionsWidget):
@classmethod
def widget(cls, field, value, **attributes):
"""
generates a TABLE tag, including INPUT checkboxes (multiple allowed)
see also: :meth:`FormWidget.widget`
"""
# was values = re.compile('[\w\-:]+').findall(str(value))
if isinstance(value, (list, tuple)):
values = [str(v) for v in value]
else:
values = [str(value)]
attr = cls._attributes(field, {}, **attributes)
attr['_class'] = attr.get('_class','web2py_checkboxeswidget')
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
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
#widget style
wrappers = dict(
table=(TABLE,TR,TD),
ul=(DIV,UL,LI),
divs=(CAT,DIV,DIV)
)
parent, child, inner = wrappers[attributes.get('style','table')]
for r_index in range(rows):
tds = []
for k, v in options[r_index*cols:(r_index+1)*cols]:
if k in values:
r_value = k
else:
r_value = []
tds.append(inner(INPUT(_type='checkbox',
_id='%s%s' % (field.name,k),
_name=field.name,
requires=attr.get('requires', None),
hideerror=True, _value=k,
value=r_value),
LABEL(v,_for='%s%s' % (field.name,k))))
opts.append(child(tds))
if opts:
opts[-1][0][0]['hideerror'] = False
return parent(*opts, **attr)
class PasswordWidget(FormWidget):
_class = 'password'
DEFAULT_PASSWORD_DISPLAY = 8*('*')
@classmethod
def widget(cls, field, value, **attributes):
"""
generates a INPUT password tag.
If a value is present it will be shown as a number of '*', not related
to the length of the actual value.
see also: :meth:`FormWidget.widget`
"""
default=dict(
_type='password',
_value=(value and cls.DEFAULT_PASSWORD_DISPLAY) or '',
)
attr = cls._attributes(field, default, **attributes)
return INPUT(**attr)
class UploadWidget(FormWidget):
_class = 'upload'
DEFAULT_WIDTH = '150px'
ID_DELETE_SUFFIX = '__delete'
GENERIC_DESCRIPTION = 'file'
DELETE_FILE = 'delete'
@classmethod
def widget(cls, field, value, download_url=None, **attributes):
"""
generates a INPUT file tag.
Optionally provides an A link to the file, including a checkbox so
the file can be deleted.
All is wrapped in a DIV.
see also: :meth:`FormWidget.widget`
:param download_url: Optional URL to link to the file (default = None)
"""
default=dict(_type='file',)
attr = cls._attributes(field, default, **attributes)
inp = INPUT(**attr)
if download_url and value:
if callable(download_url):
url = download_url(value)
else:
url = download_url + '/' + value
(br, image) = ('', '')
if UploadWidget.is_image(value):
br = BR()
image = IMG(_src = url, _width = cls.DEFAULT_WIDTH)
requires = attr["requires"]
if requires == [] or isinstance(requires, IS_EMPTY_OR):
inp = DIV(inp, '[',
A(UploadWidget.GENERIC_DESCRIPTION, _href = url),
'|',
INPUT(_type='checkbox',
_name=field.name + cls.ID_DELETE_SUFFIX,
_id=field.name + cls.ID_DELETE_SUFFIX),
LABEL(cls.DELETE_FILE,
_for=field.name + cls.ID_DELETE_SUFFIX),
']', br, image)
else:
inp = DIV(inp, '[',
A(cls.GENERIC_DESCRIPTION, _href = url),
']', br, image)
return inp
@classmethod
def represent(cls, field, value, download_url=None):
"""
how to represent the file:
- with download url and if it is an image: <A href=...><IMG ...></A>
- otherwise with download url: <A href=...>file</A>
- otherwise: file
:param field: the field
:param value: the field value
:param download_url: url for the file download (default = None)
"""
inp = cls.GENERIC_DESCRIPTION
if download_url and value:
if callable(download_url):
url = download_url(value)
else:
url = download_url + '/' + value
if cls.is_image(value):
inp = IMG(_src = url, _width = cls.DEFAULT_WIDTH)
inp = A(inp, _href = url)
return inp
@staticmethod
def is_image(value):
"""
Tries to check if the filename provided references to an image
Checking is based on filename extension. Currently recognized:
gif, png, jp(e)g, bmp
:param value: filename
"""
extension = value.split('.')[-1].lower()
if extension in ['gif', 'png', 'jpg', 'jpeg', 'bmp']:
return True
return False
class AutocompleteWidget(object):
_class = 'string'
def __init__(self, request, field, id_field=None, db=None,
orderby=None, limitby=(0,10),
keyword='_autocomplete_%(fieldname)s',
min_length=2):
self.request = request
self.keyword = keyword % dict(fieldname=field.name)
self.db = db or field._db
self.orderby = orderby
self.limitby = limitby
self.min_length = min_length
self.fields=[field]
if id_field:
self.is_reference = True
self.fields.append(id_field)
else:
self.is_reference = False
if hasattr(request,'application'):
self.url = URL(args=request.args)
self.callback()
else:
self.url = request
def callback(self):
if self.keyword in self.request.vars:
field = self.fields[0]
rows = self.db(field.like(self.request.vars[self.keyword]+'%'))\
.select(orderby=self.orderby,limitby=self.limitby,*self.fields)
if rows:
if self.is_reference:
id_field = self.fields[1]
raise HTTP(200,SELECT(_id=self.keyword,_class='autocomplete',
_size=len(rows),_multiple=(len(rows)==1),
*[OPTION(s[field.name],_value=s[id_field.name],
_selected=(k==0)) \
for k,s in enumerate(rows)]).xml())
else:
raise HTTP(200,SELECT(_id=self.keyword,_class='autocomplete',
_size=len(rows),_multiple=(len(rows)==1),
*[OPTION(s[field.name],
_selected=(k==0)) \
for k,s in enumerate(rows)]).xml())
else:
raise HTTP(200,'')
def __call__(self,field,value,**attributes):
default = dict(
_type = 'text',
value = (not value is None and str(value)) or '',
)
attr = StringWidget._attributes(field, default, **attributes)
div_id = self.keyword+'_div'
attr['_autocomplete']='off'
if self.is_reference:
key2 = self.keyword+'_aux'
key3 = self.keyword+'_auto'
attr['_class']='string'
name = attr['_name']
if 'requires' in attr: del attr['requires']
attr['_name'] = key2
value = attr['value']
record = self.db(self.fields[1]==value).select(self.fields[0]).first()
attr['value'] = record and record[self.fields[0].name]
attr['_onblur']="jQuery('#%(div_id)s').delay(3000).fadeOut('slow');" % \
dict(div_id=div_id,u='F'+self.keyword)
attr['_onkeyup'] = "jQuery('#%(key3)s').val('');var e=event.which?event.which:event.keyCode; function %(u)s(){jQuery('#%(id)s').val(jQuery('#%(key)s :selected').text());jQuery('#%(key3)s').val(jQuery('#%(key)s').val())}; if(e==39) %(u)s(); else if(e==40) {if(jQuery('#%(key)s option:selected').next().length)jQuery('#%(key)s option:selected').attr('selected',null).next().attr('selected','selected'); %(u)s();} else if(e==38) {if(jQuery('#%(key)s option:selected').prev().length)jQuery('#%(key)s option:selected').attr('selected',null).prev().attr('selected','selected'); %(u)s();} else if(jQuery('#%(id)s').val().length>=%(min_length)s) jQuery.get('%(url)s?%(key)s='+escape(jQuery('#%(id)s').val()),function(data){if(data=='')jQuery('#%(key3)s').val('');else{jQuery('#%(id)s').next('.error').hide();jQuery('#%(div_id)s').html(data).show().focus();jQuery('#%(div_id)s select').css('width',jQuery('#%(id)s').css('width'));jQuery('#%(key3)s').val(jQuery('#%(key)s').val());jQuery('#%(key)s').change(%(u)s);jQuery('#%(key)s').click(%(u)s);};}); else jQuery('#%(div_id)s').fadeOut('slow');" % \
dict(url=self.url,min_length=self.min_length,
key=self.keyword,id=attr['_id'],key2=key2,key3=key3,
name=name,div_id=div_id,u='F'+self.keyword)
if self.min_length==0:
attr['_onfocus'] = attr['_onkeyup']
return TAG[''](INPUT(**attr),INPUT(_type='hidden',_id=key3,_value=value,
_name=name,requires=field.requires),
DIV(_id=div_id,_style='position:absolute;'))
else:
attr['_name']=field.name
attr['_onblur']="jQuery('#%(div_id)s').delay(3000).fadeOut('slow');" % \
dict(div_id=div_id,u='F'+self.keyword)
attr['_onkeyup'] = "var e=event.which?event.which:event.keyCode; function %(u)s(){jQuery('#%(id)s').val(jQuery('#%(key)s').val())}; if(e==39) %(u)s(); else if(e==40) {if(jQuery('#%(key)s option:selected').next().length)jQuery('#%(key)s option:selected').attr('selected',null).next().attr('selected','selected'); %(u)s();} else if(e==38) {if(jQuery('#%(key)s option:selected').prev().length)jQuery('#%(key)s option:selected').attr('selected',null).prev().attr('selected','selected'); %(u)s();} else if(jQuery('#%(id)s').val().length>=%(min_length)s) jQuery.get('%(url)s?%(key)s='+escape(jQuery('#%(id)s').val()),function(data){jQuery('#%(id)s').next('.error').hide();jQuery('#%(div_id)s').html(data).show().focus();jQuery('#%(div_id)s select').css('width',jQuery('#%(id)s').css('width'));jQuery('#%(key)s').change(%(u)s);jQuery('#%(key)s').click(%(u)s);}); else jQuery('#%(div_id)s').fadeOut('slow');" % \
dict(url=self.url,min_length=self.min_length,
key=self.keyword,id=attr['_id'],div_id=div_id,u='F'+self.keyword)
if self.min_length==0:
attr['_onfocus'] = attr['_onkeyup']
return TAG[''](INPUT(**attr),DIV(_id=div_id,_style='position:absolute;'))
class SQLFORM(FORM):
"""
SQLFORM is used to map a table (and a current record) into an HTML form
given a SQLTable stored in db.table
generates an insert form::
SQLFORM(db.table)
generates an update form::
record=db.table[some_id]
SQLFORM(db.table, record)
generates an update with a delete button::
SQLFORM(db.table, record, deletable=True)
if record is an int::
record=db.table[record]
optional arguments:
:param fields: a list of fields that should be placed in the form,
default is all.
:param labels: a dictionary with labels for each field, keys are the field
names.
:param col3: a dictionary with content for an optional third column
(right of each field). keys are field names.
:param linkto: the URL of a controller/function to access referencedby
records
see controller appadmin.py for examples
:param upload: the URL of a controller/function to download an uploaded file
see controller appadmin.py for examples
any named optional attribute is passed to the <form> tag
for example _class, _id, _style, _action, _method, etc.
"""
# usability improvements proposal by fpp - 4 May 2008 :
# - correct labels (for points to field id, not field name)
# - add label for delete checkbox
# - add translatable label for record ID
# - add third column to right of fields, populated from the col3 dict
widgets = Storage(dict(
string = StringWidget,
text = TextWidget,
password = PasswordWidget,
integer = IntegerWidget,
double = DoubleWidget,
decimal = DecimalWidget,
time = TimeWidget,
date = DateWidget,
datetime = DatetimeWidget,
upload = UploadWidget,
boolean = BooleanWidget,
blob = None,
options = OptionsWidget,
multiple = MultipleOptionsWidget,
radio = RadioWidget,
checkboxes = CheckboxesWidget,
autocomplete = AutocompleteWidget,
list = ListWidget,
))
FIELDNAME_REQUEST_DELETE = 'delete_this_record'
FIELDKEY_DELETE_RECORD = 'delete_record'
ID_LABEL_SUFFIX = '__label'
ID_ROW_SUFFIX = '__row'
def __init__(
self,
table,
record = None,
deletable = False,
linkto = None,
upload = None,
fields = None,
labels = None,
col3 = {},
submit_button = 'Submit',
delete_label = 'Check to delete',
showid = True,
readonly = False,
comments = True,
keepopts = [],
ignore_rw = False,
record_id = None,
formstyle = 'table3cols',
buttons = ['submit'],
separator = ': ',
**attributes
):
"""
SQLFORM(db.table,
record=None,
fields=['name'],
labels={'name': 'Your name'},
linkto=URL(f='table/db/')
"""
self.ignore_rw = ignore_rw
self.formstyle = formstyle
nbsp = XML(' ') # Firefox2 does not display fields with blanks
FORM.__init__(self, *[], **attributes)
ofields = fields
keyed = hasattr(table,'_primarykey')
# if no fields are provided, build it from the provided table
# will only use writable or readable fields, unless forced to ignore
if fields is None:
fields = [f.name for f in table if (ignore_rw or f.writable or f.readable) and not f.compute]
self.fields = fields
# make sure we have an id
if self.fields[0] != table.fields[0] and \
isinstance(table,Table) and not keyed:
self.fields.insert(0, table.fields[0])
self.table = table
# try to retrieve the indicated record using its id
# otherwise ignore it
if record and isinstance(record, (int, long, str, unicode)):
if not str(record).isdigit():
raise HTTP(404, "Object not found")
record = table._db(table._id == record).select().first()
if not record:
raise HTTP(404, "Object not found")
self.record = record
self.record_id = record_id
if keyed:
self.record_id = dict([(k,record and str(record[k]) or None) \
for k in table._primarykey])
self.field_parent = {}
xfields = []
self.fields = fields
self.custom = Storage()
self.custom.dspval = Storage()
self.custom.inpval = Storage()
self.custom.label = Storage()
self.custom.comment = Storage()
self.custom.widget = Storage()
self.custom.linkto = Storage()
# default id field name
self.id_field_name = table._id.name
sep = separator or ''
for fieldname in self.fields:
if fieldname.find('.') >= 0:
continue
field = self.table[fieldname]
comment = None
if comments:
comment = col3.get(fieldname, field.comment)
if comment is None:
comment = ''
self.custom.comment[fieldname] = comment
if not labels is None and fieldname in labels:
label = labels[fieldname]
else:
label = field.label
self.custom.label[fieldname] = label
field_id = '%s_%s' % (table._tablename, fieldname)
label = LABEL(label, label and sep, _for=field_id,
_id=field_id+SQLFORM.ID_LABEL_SUFFIX)
row_id = field_id+SQLFORM.ID_ROW_SUFFIX
if field.type == 'id':
self.custom.dspval.id = nbsp
self.custom.inpval.id = ''
widget = ''
# store the id field name (for legacy databases)
self.id_field_name = field.name
if record:
if showid and field.name in record and field.readable:
v = record[field.name]
widget = SPAN(v, _id=field_id)
self.custom.dspval.id = str(v)
xfields.append((row_id,label, widget,comment))
self.record_id = str(record[field.name])
self.custom.widget.id = widget
continue
if readonly and not ignore_rw and not field.readable:
continue
if record:
default = record[fieldname]
else:
default = field.default
if isinstance(default,CALLABLETYPES):
default=default()
cond = readonly or \
(not ignore_rw and not field.writable and field.readable)
if default and not cond:
default = field.formatter(default)
dspval = default
inpval = default
if cond:
# ## if field.represent is available else
# ## ignore blob and preview uploaded images
# ## format everything else
if field.represent:
inp = represent(field,default,record)
elif field.type in ['blob']:
continue
elif field.type == 'upload':
inp = UploadWidget.represent(field, default, upload)
elif field.type == 'boolean':
inp = self.widgets.boolean.widget(field, default, _disabled=True)
else:
inp = field.formatter(default)
elif field.type == 'upload':
if hasattr(field, 'widget') and field.widget:
inp = field.widget(field, default, upload)
else:
inp = self.widgets.upload.widget(field, default, upload)
elif hasattr(field, 'widget') and field.widget:
inp = field.widget(field, default)
elif field.type == 'boolean':
inp = self.widgets.boolean.widget(field, default)
if default:
inpval = 'checked'
else:
inpval = ''
elif OptionsWidget.has_options(field):
if not field.requires.multiple:
inp = self.widgets.options.widget(field, default)
else:
inp = self.widgets.multiple.widget(field, default)
if fieldname in keepopts:
inpval = TAG[''](*inp.components)
elif field.type.startswith('list:'):
inp = self.widgets.list.widget(field,default)
elif field.type == 'text':
inp = self.widgets.text.widget(field, default)
elif field.type == 'password':
inp = self.widgets.password.widget(field, default)
if self.record:
dspval = PasswordWidget.DEFAULT_PASSWORD_DISPLAY
else:
dspval = ''
elif field.type == 'blob':
continue
else:
field_type = widget_class.match(str(field.type)).group()
field_type = field_type in self.widgets and field_type or 'string'
inp = self.widgets[field_type].widget(field, default)
xfields.append((row_id,label,inp,comment))
self.custom.dspval[fieldname] = dspval or nbsp
self.custom.inpval[fieldname] = inpval or ''
self.custom.widget[fieldname] = inp
# if a record is provided and found, as is linkto
# build a link
if record and linkto:
db = linkto.split('/')[-1]
for (rtable, rfield) in table._referenced_by:
if keyed:
rfld = table._db[rtable][rfield]
query = urllib.quote('%s.%s==%s' % (db,rfld,record[rfld.type[10:].split('.')[1]]))
else:
query = urllib.quote('%s.%s==%s' % (db,table._db[rtable][rfield],record[self.id_field_name]))
lname = olname = '%s.%s' % (rtable, rfield)
if ofields and not olname in ofields:
continue
if labels and lname in labels:
lname = labels[lname]
widget = A(lname,
_class='reference',
_href='%s/%s?query=%s' % (linkto, rtable, query))
xfields.append((olname.replace('.', '__')+SQLFORM.ID_ROW_SUFFIX,
'',widget,col3.get(olname,'')))
self.custom.linkto[olname.replace('.', '__')] = widget
# </block>
# when deletable, add delete? checkbox
self.custom.deletable = ''
if record and deletable:
widget = INPUT(_type='checkbox',
_class='delete',
_id=self.FIELDKEY_DELETE_RECORD,
_name=self.FIELDNAME_REQUEST_DELETE,
)
xfields.append((self.FIELDKEY_DELETE_RECORD+SQLFORM.ID_ROW_SUFFIX,
LABEL(
delete_label,separator,
_for=self.FIELDKEY_DELETE_RECORD,
_id=self.FIELDKEY_DELETE_RECORD+SQLFORM.ID_LABEL_SUFFIX),
widget,
col3.get(self.FIELDKEY_DELETE_RECORD, '')))
self.custom.deletable = widget
# when writable, add submit button
self.custom.submit = ''
if not readonly:
if 'submit' in buttons:
widget = self.custom.submit = INPUT(_type='submit',
_value=submit_button)
elif buttons:
widget = self.custom.submit = DIV(*buttons)
if self.custom.submit:
xfields.append(('submit_record' + SQLFORM.ID_ROW_SUFFIX,
'', widget, col3.get('submit_button', '')))
# if a record is provided and found
# make sure it's id is stored in the form
if record:
if not self['hidden']:
self['hidden'] = {}
if not keyed:
self['hidden']['id'] = record[table._id.name]
(begin, end) = self._xml()
self.custom.begin = XML("<%s %s>" % (self.tag, begin))
self.custom.end = XML("%s</%s>" % (end, self.tag))
table = self.createform(xfields)
self.components = [table]
def createform(self, xfields):
if self.formstyle == 'table3cols':
table = TABLE()
for id,a,b,c in xfields:
td_b = self.field_parent[id] = TD(b,_class='w2p_fw')
table.append(TR(TD(a,_class='w2p_fl'),
td_b,
TD(c,_class='w2p_fc'),_id=id))
elif self.formstyle == 'table2cols':
table = TABLE()
for id,a,b,c in xfields:
td_b = self.field_parent[id] = TD(b,_class='w2p_fw',_colspan="2")
table.append(TR(TD(a,_class='w2p_fl'),
TD(c,_class='w2p_fc'),_id=id
+'1',_class='even'))
table.append(TR(td_b,_id=id+'2',_class='odd'))
elif self.formstyle == 'divs':
table = TAG['']()
for id,a,b,c in xfields:
div_b = self.field_parent[id] = DIV(b,_class='w2p_fw')
table.append(DIV(DIV(a,_class='w2p_fl'),
div_b,
DIV(c,_class='w2p_fc'),_id=id))
elif self.formstyle == 'ul':
table = UL()
for id,a,b,c in xfields:
div_b = self.field_parent[id] = DIV(b,_class='w2p_fw')
table.append(LI(DIV(a,_class='w2p_fl'),
div_b,
DIV(c,_class='w2p_fc'),_id=id))
elif callable(self.formstyle):
table = TABLE()
for id,a,b,c in xfields:
raw_b = self.field_parent[id] = b
newrows = self.formstyle(id,a,raw_b,c)
if type(newrows).__name__ != "tuple":
newrows = [newrows]
for newrow in newrows:
table.append(newrow)
else: