source: products/quintagroup.referencedatagridfield/trunk/quintagroup/referencedatagridfield/_field.py @ 2264

Last change on this file since 2264 was 2264, checked in by mylan, 14 years ago

Update column names

  • Property svn:eol-style set to native
File size: 4.0 KB
Line 
1#from Products.Archetypes import atapi
2import re
3import logging
4import urlparse
5from urllib import quote
6from types import ListType, TupleType
7
8from AccessControl import ClassSecurityInfo
9
10from Products.CMFCore.utils import getToolByName
11from Products.validation import validation #validators import baseValidators
12from Products.Archetypes.Field import encode
13from Products.Archetypes.Registry import registerField, registerWidget
14
15from Products.DataGridField.DataGridField import DataGridField
16from Products.DataGridField.DataGridWidget import DataGridWidget
17
18
19# Logger object
20#logger = logging.getLogger('ReferenceDataGridField')
21#logger.debug("ReferenceDataGrid loading")
22
23class ReferenceDataGridWidget(DataGridWidget):
24    _properties = DataGridWidget._properties.copy()
25    _properties.update({
26        'macro' : "referencedatagridwidget",
27        'column_names': ['Title', 'Link or UID'],
28        })
29
30isURL = validation.validatorFor('isURL')
31
32class ReferenceDataGridField(DataGridField):
33    _properties = DataGridField._properties.copy()
34    _properties.update({
35        'columns' : ('title', 'link_uid'),
36        'widget': ReferenceDataGridWidget,
37        })
38
39    security = ClassSecurityInfo()
40
41    security.declarePrivate('isRemoteURL')
42    def isRemoteURL(self, url):
43        return isURL(url) == 1 and True or False
44
45    security.declarePrivate('set')
46    def set(self, instance, value, **kwargs):
47        """
48        The passed in object should be a records object, or a sequence of dictionaries
49        About link_uid data:
50          * interpretations:
51            * if data not starts with standard protocol names (http://, ftp://) it treats
52              as UID
53          * record removed if:
54            * no data;
55            * data contains UID of not existent object
56        About title:
57          * if there is UID of existent object and record has not title data
58            - object's Title will be used.
59        """
60        catalog = getToolByName(instance, "uid_catalog")
61
62        if value is None:
63            value = ()
64
65        if not isinstance(value, (ListType, TupleType)):
66            value = value,
67
68        result = []
69        for row in value:
70            data = {"title":"", "link_uid":""}
71
72            title = str(row.get('title', "")).strip()
73            if not title == "":
74                data["title"] = title
75
76            url = str(row.get('link_uid', "")).strip()
77            if url == '':
78                continue
79            elif self.isRemoteURL(url):
80                data["link_uid"] = urlparse.urlunparse(urlparse.urlparse(url))
81            else:
82                brains = catalog(UID=url)
83                if len(brains) == 0:
84                    continue
85                else:
86                    data["link_uid"] = url
87                    if title == "":
88                        data["title"] = getattr(brains[0], "Title","")
89            result.append(data)
90
91        DataGridField.set(self, instance, result, **kwargs)
92
93    security.declarePrivate('get')
94    def get(self, instance, **kwargs):
95        """ Return DataGridField value
96
97        Value is a list object of rows.
98        Row id dictionary object with standard 'link_uid' and 'title' keys
99        plus extra informal *isLink* key
100        """
101        purl = getToolByName(instance, "portal_url")
102        resuid = purl() + "/resolveuid/"
103
104        result = []
105        rows = DataGridField.get(self, instance, **kwargs)
106        for row in rows:
107            data = {"link_uid": row["link_uid"],
108                    "title": row["title"],
109                    "link": ""}
110            url = row["link_uid"]
111            if self.isRemoteURL(url):
112                data["link"] = quote(url, safe='?$#@/:=+;$,&%')
113            else:
114                data["link"] = resuid + url
115            result.append(data)
116
117        return result
118
119registerWidget(
120    ReferenceDataGridWidget,
121    title='DataGrid Reference',
122    used_for=('quintagroup.referencedatagridfield.ReferenceDataGridField',)
123    )
124
125registerField(
126    ReferenceDataGridField,
127    title="DataGrid Reference Field",
128    description=("Reference DataGrid field.")
129    )
Note: See TracBrowser for help on using the repository browser.