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
|
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
|
-
+
+
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
-
+
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
+
-
+
|
def widget(field, value, **attributes):
"""
generates a TABLE tag, including INPUT radios (only 1 option allowed)
see also: :meth:`FormWidget.widget`
"""
attr = OptionsWidget._attributes(field, {}, **attributes)
attr = RadioWidget._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),
tds.append(TD(INPUT(_type='radio', _name=field.name,
requires=attr.get('requires',None),
hideerror=True, _value=k,
value=value), v))
opts.append(TR(tds))
_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 TABLE(*opts, **attr)
return parent(*opts, **attr)
class CheckboxesWidget(OptionsWidget):
@staticmethod
def widget(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 = OptionsWidget._attributes(field, {}, **attributes)
attr = CheckboxesWidget._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(TD(INPUT(_type='checkbox', _name=field.name,
requires=attr.get('requires', None),
hideerror=True, _value=k,
value=r_value), v))
opts.append(TR(tds))
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 TABLE(*opts, **attr)
return parent(*opts, **attr)
class PasswordWidget(FormWidget):
DEFAULT_PASSWORD_DISPLAY = 8*('*')
@staticmethod
|
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
|
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
|
-
+
+
-
+
-
+
-
+
-
+
-
+
+
-
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
|
if isinstance(field.uploadfield, str):
fields[field.uploadfield] = source_file.read()
# proposed by Hamdy (accept?) do we need fields at this point?
self.vars[fieldname] = fields[fieldname]
continue
elif fieldname in self.vars:
fields[fieldname] = self.vars[fieldname]
elif field.default == None and field.type != 'blob':
elif field.default is None and field.type != 'blob':
self.errors[fieldname] = 'no data'
self.accepted = False
return False
value = fields.get(fieldname,None)
if field.type == 'list:string':
if not isinstance(value, (tuple, list)):
fields[fieldname] = value and [value] or []
elif isinstance(field.type,str) and field.type.startswith('list:'):
if not isinstance(value, list):
fields[fieldname] = [safe_int(x) for x in (value and [value] or [])]
elif field.type == 'integer':
if value != None:
if not value is None:
fields[fieldname] = safe_int(value)
elif field.type.startswith('reference'):
if value != None and isinstance(self.table, Table) and not keyed:
if not value is None and isinstance(self.table, Table) and not keyed:
fields[fieldname] = safe_int(value)
elif field.type == 'double':
if value != None:
if not value is None:
fields[fieldname] = safe_float(value)
for fieldname in self.vars:
if fieldname != 'id' and fieldname in self.table.fields\
and not fieldname in fields and not fieldname\
in request_vars:
fields[fieldname] = self.vars[fieldname]
if dbio:
if dbio:
if 'delete_this_record' in fields:
# this should never happen but seems to happen to some
del fields['delete_this_record']
for field in self.table:
if not field.name in fields and field.writable==False:
if not field.name in fields and field.writable==False \
and field.update is None:
if record_id:
fields[field.name] = self.record[field.name]
elif self.table[field.name].default!=None:
elif not self.table[field.name].default is None:
fields[field.name] = self.table[field.name].default
if keyed:
if reduce(lambda x, y: x and y, record_id.values()): # if record_id
if fields:
qry = reduce(lambda x, y: x & y,
[self.table[k] == self.record[k] for k in self.table._primarykey])
self.table._db(qry).update(**fields)
else:
pk = self.table.insert(**fields)
if pk:
self.vars.update(pk)
else:
ret = False
else:
if record_id:
self.vars.id = self.record.id
if fields:
self.table._db(self.table._id == self.record.id).update(**fields)
else:
self.vars.id = self.table.insert(**fields)
self.accepted = ret
return ret
@staticmethod
def factory(*fields, **attributes):
"""
generates a SQLFORM for the given fields.
Internally will build a non-database based data model
to hold the fields.
"""
# Define a table name, this way it can be logical to our CSS.
# And if you switch from using SQLFORM to SQLFORM.factory
# your same css definitions will still apply.
table_name = attributes.get('table_name', 'no_table')
# So it won't interfear with SQLDB.define_table
if 'table_name' in attributes:
del attributes['table_name']
return SQLFORM(DAL(None).define_table(table_name, *fields), **attributes)
return SQLFORM(DAL(None).define_table(table_name, *fields),
**attributes)
@staticmethod
def grid(query,
fields=None,
field_id=None,
left=None,
headers={},
columns=None,
orderby=None,
searchable=True,
sortable=True,
paginate=20,
deletable=True,
editable=True,
details=True,
selectable=None,
create=True,
csv=True,
links=None,
upload = '<default>',
args=[],
user_signature = True,
maxtextlengths={},
maxtextlength=20,
onvalidation=None,
oncreate=None,
onupdate=None,
ondelete=None,
sorter_icons=('[^]','[v]'),
ui = 'web2py',
showbuttontext=True,
_class="web2py_grid",
formname='web2py_grid',
):
# jQuery UI ThemeRoller classes (empty if ui is disabled)
if ui == 'jquery-ui':
ui = dict(widget='ui-widget',
header='ui-widget-header',
content='ui-widget-content',
default='ui-state-default',
cornerall='ui-corner-all',
cornertop='ui-corner-top',
cornerbottom='ui-corner-bottom',
button='ui-button-text-icon-primary',
buttontext='ui-button-text',
buttonadd='ui-icon ui-icon-plusthick',
buttonback='ui-icon ui-icon-arrowreturnthick-1-w',
buttonexport='ui-icon ui-icon-transferthick-e-w',
buttondelete='ui-icon ui-icon-trash',
buttonedit='ui-icon ui-icon-pencil',
buttontable='ui-icon ui-icon-triangle-1-e',
buttonview='ui-icon ui-icon-zoomin',
)
elif ui == 'web2py':
ui = dict(widget='',
header='',
content='',
default='',
cornerall='',
cornertop='',
cornerbottom='',
button='button',
buttontext='buttontext button',
buttonadd='icon plus',
buttonback='icon leftarrow',
buttonexport='icon downarrow',
buttondelete='icon trash',
buttonedit='icon pen',
buttontable='icon rightarrow',
buttonview='icon magnifier',
)
elif not isinstance(ui,dict):
raise RuntimeError,'SQLFORM.grid ui argument must be a dictionary'
from gluon import current, redirect
db = query._db
T = current.T
request = current.request
session = current.session
response = current.response
wenabled = (not user_signature or (session.auth and session.auth.user))
#create = wenabled and create
#editable = wenabled and editable
deletable = wenabled and deletable
def url(**b):
b['args'] = args+b.get('args',[])
b['user_signature'] = user_signature
return URL(**b)
def gridbutton(buttonclass='buttonadd',buttontext='Add',buttonurl=url(args=[]),callback=None,delete=None):
if showbuttontext:
if callback:
return A(SPAN(_class=ui.get(buttonclass,'')),
SPAN(T(buttontext),_title=buttontext,
_class=ui.get('buttontext','')),
callback=callback,delete=delete,
_class=ui.get('button',''))
else:
return A(SPAN(_class=ui.get(buttonclass,'')),
SPAN(T(buttontext),_title=buttontext,
_class=ui.get('buttontext','')),
_href=buttonurl,_class=ui.get('button',''))
else:
if callback:
return A(SPAN(_class=ui.get(buttonclass,'')),
callback=callback,delete=delete,
_title=buttontext,_class=ui.get('buttontext',''))
else:
return A(SPAN(_class=ui.get(buttonclass,'')),
_href=buttonurl,_title=buttontext,
_class=ui.get('buttontext',''))
dbset = db(query)
tables = [db[tablename] for tablename in db._adapter.tables(
dbset.query)]
if not fields:
fields = reduce(lambda a,b:a+b,
[[field for field in table] for table in tables])
if not field_id:
field_id = tables[0]._id
table = field_id.table
tablename = table._tablename
referrer = session.get('_web2py_grid_referrer_'+formname, url())
def check_authorization():
if user_signature:
if not URL.verify(request,user_signature=user_signature):
session.flash = T('not authorized')
redirect(referrer)
if upload=='<default>':
upload = lambda filename: url(args=['download',filename])
if len(request.args)>1 and request.args[-2]=='download':
check_authorization()
stream = response.download(request,db)
raise HTTP(200,stream,**response.headers)
def buttons(edit=False,view=False,record=None):
buttons = DIV(gridbutton('buttonback', 'Back', referrer),
_class='form_header row_buttons %(header)s %(cornertop)s' % ui)
if edit:
args = ['edit',table._tablename,request.args[-1]]
buttons.append(gridbutton('buttonedit', 'Edit',
url(args=args)))
if view:
args = ['view',table._tablename,request.args[-1]]
buttons.append(gridbutton('buttonview', 'View',
url(args=args)))
if record and links:
for link in links:
buttons.append(link(record))
return buttons
formfooter = DIV(
_class='form_footer row_buttons %(header)s %(cornerbottom)s' % ui)
create_form = edit_form = None
if create and len(request.args)>1 and request.args[-2]=='new':
check_authorization()
table = db[request.args[-1]]
create_form = SQLFORM(
table,
_class='web2py_form'
).process(next=referrer,
onvalidation=onvalidation,
onsuccess=oncreate,
formname=formname)
res = DIV(buttons(),create_form,formfooter,_class=_class)
res.create_form = create_form
res.edit_form = None
res.update_form = None
return res
elif details and len(request.args)>2 and request.args[-3]=='view':
check_authorization()
table = db[request.args[-2]]
record = table(request.args[-1]) or redirect(URL('error'))
form = SQLFORM(table,record,upload=upload,
readonly=True,_class='web2py_form')
res = DIV(buttons(edit=editable,record=record),form,
formfooter,_class=_class)
res.create_form = None
res.edit_form = None
res.update_form = None
return res
elif editable and len(request.args)>2 and request.args[-3]=='edit':
check_authorization()
table = db[request.args[-2]]
record = table(request.args[-1]) or redirect(URL('error'))
edit_form = SQLFORM(table,record,upload=upload,
deletable=deletable,
_class='web2py_form')
edit_form.process(formname=formname,
onvalidation=onvalidation,
onsuccess=onupdate,
next=referrer)
res = DIV(buttons(view=details,record=record),
edit_form,formfooter,_class=_class)
res.create_form = None
res.edit_form = edit_form
res.update_form = None
return res
elif deletable and len(request.args)>2 and request.args[-3]=='delete':
check_authorization()
table = db[request.args[-2]]
ret = db(table.id==request.args[-1]).delete()
if ondelete:
return ondelete(table,request.args[-2],ret)
return ret
elif csv and len(request.args)>0 and request.args[-1]=='csv':
check_authorization()
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = \
'attachment;filename=rows.csv;'
raise HTTP(200,str(dbset.select()),
**{'Content-Type':'text/csv',
'Content-Disposition':'attachment;filename=rows.csv;'})
elif request.vars.records and not isinstance(
request.vars.records,list):
request.vars.records=[request.vars.records]
elif not request.vars.records:
request.vars.records=[]
def OR(a,b): return a|b
def AND(a,b): return a&b
session['_web2py_grid_referrer_'+formname] = \
URL(args=request.args,vars=request.vars,
user_signature=user_signature)
console = DIV(_class='web2py_console %(header)s %(cornertop)s' % ui)
error = None
search_form = None
if searchable:
form = FORM(INPUT(_name='keywords',_value=request.vars.keywords,
_id='web2py_keywords'),
INPUT(_type='submit',_value=T('Search')),
INPUT(_type='submit',_value=T('Clear'),
_onclick="jQuery('#web2py_keywords').val('');"),
_method="GET",_action=url())
search_form = form
console.append(form)
key = request.vars.get('keywords','').strip()
if searchable==True:
subquery = None
if key and not ' ' in key:
SEARCHABLE_TYPES = ('string','text','list:string')
parts = [field.contains(key) for field in fields \
if field.type in SEARCHABLE_TYPES]
else:
parts = None
if parts:
subquery = reduce(OR,parts)
else:
try:
subquery = smart_query(fields,key)
except RuntimeError:
subquery = None
error = T('Invalid query')
else:
subquery = searchable(key,fields)
if subquery:
dbset = dbset(subquery)
try:
if left:
nrows = dbset.select('count(*)',left=left).first()['count(*)']
else:
nrows = dbset.count()
except:
nrows = 0
error = T('Unsupported query')
search_actions = DIV(_class='web2py_search_actions')
if create:
search_actions.append(gridbutton(
buttonclass='buttonadd',
buttontext='Add',
buttonurl=url(args=['new',tablename])))
if csv:
search_actions.append(gridbutton(
buttonclass='buttonexport',
buttontext='Export',
buttonurl=url(args=['csv'])))
console.append(search_actions)
message = error or T('%(nrows)s records found' % dict(nrows=nrows))
console.append(DIV(message,_class='web2py_counter'))
order = request.vars.order or ''
if sortable:
if order and not order=='None':
if order[:1]=='~':
sign, rorder = '~', order[1:]
else:
sign, rorder = '', order
tablename,fieldname = rorder.split('.',1)
if sign=='~':
orderby=~db[tablename][fieldname]
else:
orderby=db[tablename][fieldname]
head = TR(_class=ui.get('header',''))
if selectable:
head.append(TH(_class=ui.get('default','')))
for field in fields:
if columns and not str(field) in columns: continue
if not field.readable: continue
key = str(field)
header = headers.get(str(field),
hasattr(field,'label') and field.label or key)
if sortable:
if key == order:
key, marker = '~'+order, sorter_icons[0]
elif key == order[1:]:
marker = sorter_icons[1]
else:
marker = ''
header = A(header,marker,_href=url(vars=dict(
keywords=request.vars.keywords or '',
order=key)))
head.append(TH(header, _class=ui.get('default','')))
for link in links or []:
if isinstance(link,dict):
head.append(TH(link['header'], _class=ui.get('default','')))
head.append(TH(_class=ui.get('default','')))
paginator = UL()
if paginate and paginate<nrows:
npages,reminder = divmod(nrows,paginate)
if reminder: npages+=1
try: page = int(request.vars.page or 1)-1
except ValueError: page = 0
limitby = (paginate*page,paginate*(page+1))
def self_link(name,p):
d = dict(page=p+1)
if order: d['order']=order
if request.vars.keywords: d['keywords']=request.vars.keywords
return A(name,_href=url(vars=d))
if page>0:
paginator.append(LI(self_link('<<',0)))
if page>1:
paginator.append(LI(self_link('<',page-1)))
pages = range(max(0,page-5),min(page+5,npages-1))
for p in pages:
if p == page:
paginator.append(LI(A(p+1,_onclick='return false'),
_class='current'))
else:
paginator.append(LI(self_link(p+1,p)))
if page<npages-2:
paginator.append(LI(self_link('>',page+1)))
if page<npages-1:
paginator.append(LI(self_link('>>',npages-1)))
else:
limitby = None
rows = dbset.select(left=left,orderby=orderby,limitby=limitby,*fields)
if not searchable and not rows: return DIV(T('No records found'))
if rows:
htmltable = TABLE(THEAD(head))
tbody = TBODY()
numrec=0
for row in rows:
if numrec % 2 == 0:
classtr = 'even'
else:
classtr = 'odd'
numrec+=1
id = row[field_id]
if len(tables)>1 or row.get('_extra',None):
rrow = row[field._tablename]
else:
rrow = row
tr = TR(_class=classtr)
if selectable:
tr.append(INPUT(_type="checkbox",_name="records",_value=id,
value=request.vars.records))
for field in fields:
if columns and not str(field) in columns: continue
if not field.readable: continue
if field.type=='blob': continue
value = row[field]
if field.represent:
try:
value=field.represent(value,rrow)
except KeyError:
pass
elif field.type=='boolean':
value = INPUT(_type="checkbox",_checked = value,
_disabled=True)
elif field.type=='upload':
if value:
if callable(upload):
value = A('File', _href=upload(value))
elif upload:
value = A('File',
_href='%s/%s' % (upload, value))
else:
value = ''
elif isinstance(value,str) and len(value)>maxtextlength:
value=value[:maxtextlengths.get(str(field),maxtextlength)]+'...'
else:
value=field.formatter(value)
tr.append(TD(value))
row_buttons = TD(_class='row_buttons')
for link in links or []:
if isinstance(link, dict):
tr.append(TD(link['body'](row)))
else:
row_buttons.append(link(row))
if details and (not callable(details) or details(row)):
row_buttons.append(gridbutton(
'buttonview', 'View',
url(args=['view',tablename,id])))
if editable and (not callable(editable) or editable(row)):
row_buttons.append(gridbutton(
'buttonedit', 'Edit',
url(args=['edit',tablename,id])))
if deletable and (not callable(deletable) or deletable(row)):
row_buttons.append(gridbutton(
'buttondelete', 'Delete',
callback=url(args=['delete',tablename,id]),
delete='tr'))
tr.append(row_buttons)
tbody.append(tr)
htmltable.append(tbody)
if selectable:
htmltable = FORM(htmltable,INPUT(_type="submit"))
if htmltable.process(formname=formname).accepted:
records = [int(r) for r in htmltable.vars.records or []]
selectable(records)
redirect(referrer)
else:
htmltable = DIV(T('No records found'))
res = DIV(console,
DIV(htmltable,_class="web2py_table"),
DIV(paginator,_class=\
"web2py_paginator %(header)s %(cornerbottom)s" % ui),
_class='%s %s' % (_class, ui.get('widget','')))
res.create_form = create_form
res.edit_form = edit_form
res.search_form = search_form
return res
@staticmethod
def smartgrid(table, constraints=None, links=None,
linked_tables=None, user_signature=True,
**kwargs):
"""
@auth.requires_login()
def index():
db.define_table('person',Field('name'),format='%(name)s')
db.define_table('dog',
Field('name'),Field('owner',db.person),format='%(name)s')
db.define_table('comment',Field('body'),Field('dog',db.dog))
if db(db.person).isempty():
from gluon.contrib.populate import populate
populate(db.person,300)
populate(db.dog,300)
populate(db.comment,1000)
db.commit()
form=SQLFORM.smartgrid(db[request.args(0) or 'person']) #***
return dict(form=form)
*** builds a complete interface to navigate all tables links
to the request.args(0)
table: pagination, search, view, edit, delete,
children, parent, etc.
constraints is a dict {'table',query} that limits which
records can be accessible
links is a list of lambda row: A(....) that will add buttons
linked_tables is a optional list of tablenames of tables to be linked
"""
from gluon import current, A, URL, DIV, H3, redirect
request, T = current.request, current.T
db = table._db
if links is None: links = []
if constraints is None: constraints = {}
breadcrumbs = []
if request.args(0) != table._tablename:
request.args=[table._tablename]
try:
args = 1
previous_tablename,previous_fieldname,previous_id = \
table._tablename,None,None
while len(request.args)>args:
key = request.args(args)
if '.' in key:
id = request.args(args+1)
tablename,fieldname = key.split('.',1)
table = db[tablename]
field = table[fieldname]
field.default = id
referee = field.type[10:]
if referee!=previous_tablename:
raise HTTP(400)
cond = constraints.get(referee,None)
if cond:
record = db(db[referee].id==id)(cond).select().first()
else:
record = db[referee](id)
if previous_id:
if record[previous_fieldname] != int(previous_id):
raise HTTP(400)
previous_tablename,previous_fieldname,previous_id = \
tablename,fieldname,id
try:
name = db[referee]._format % record
except TypeError:
name = id
breadcrumbs += [A(T(referee),
_href=URL(args=request.args[:args])),' ',
A(name,
_href=URL(args=request.args[:args]+[
'view',referee,id],user_signature=True)),
' > ']
args+=2
else:
break
if args>1:
query = (field == id)
if linked_tables is None or referee in linked_tables:
field.represent = lambda id,r=None,referee=referee,rep=field.represent: A(rep(id),_href=URL(args=request.args[:args]+['view',referee,id], user_signature=user_signature))
except (KeyError,ValueError,TypeError):
redirect(URL(args=table._tablename))
if args==1:
query = table.id>0
if table._tablename in constraints:
query = query&constraints[table._tablename]
for tablename,fieldname in table._referenced_by:
if linked_tables is None or tablename in linked_tables:
args0 = tablename+'.'+fieldname
links.append(lambda row,t=T(tablename),args=args,args0=args0:\
A(SPAN(t),_href=URL(args=request.args[:args]+[args0,row.id])))
grid=SQLFORM.grid(query,args=request.args[:args],links=links,
user_signature=user_signature,**kwargs)
if isinstance(grid,DIV):
breadcrumbs.append(A(T(table._tablename),
_href=URL(args=request.args[:args])))
grid.insert(0,DIV(H3(*breadcrumbs),_class='web2py_breadcrumbs'))
return grid
class SQLTABLE(TABLE):
"""
given a Rows object, as returned by a db().select(), generates
an html table with the rows.
|