-
Notifications
You must be signed in to change notification settings - Fork 28
/
fields.py
288 lines (231 loc) · 9.28 KB
/
fields.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
# -*- coding: utf-8 -*-
from collective.easyform import easyformMessageFactory as _
from collective.easyform.api import get_expression
from collective.easyform.interfaces import IEasyForm
from collective.easyform.interfaces import IEasyFormForm
from collective.easyform.interfaces import IFieldExtender
from collective.easyform.interfaces import ILabel
from collective.easyform.interfaces import IHCaptcha
from collective.easyform.interfaces import INorobotCaptcha
from collective.easyform.interfaces import IReCaptcha
from collective.easyform.interfaces import ILikert
from collective.easyform.interfaces import IRichLabel
from collective.easyform.validators import IFieldValidator
from plone.schemaeditor.fields import FieldFactory
from plone.supermodel.exportimport import BaseHandler
from z3c.form.interfaces import IGroup
from z3c.form.interfaces import IValidator
from z3c.form.interfaces import IValue
from zope.component import adapter
from zope.component import queryMultiAdapter
from zope.component import queryUtility
from zope.interface import implementer
from zope.interface import Interface
from zope.interface import Invalid
from zope.interface import providedBy
from zope.schema import Field
from zope.schema import TextLine
from zope.schema._bootstrapinterfaces import IFromUnicode
from zope.schema.interfaces import IField
def superAdapter(specific_interface, adapter, objects, name=u""):
"""Find the next most specific adapter.
This is called by a FieldExtenderValidator or FieldExtenderDefault instance.
This is passed in with the 'adapter' parameter.
This adapter itself is not a real validator or default factory,
but is used to find other real validators or default factories.
This may sound strange, but it solves a problem.
Problem is that validators and default were not always found for fields in field sets.
For example, a captcha field in the main form would get validated by its proper validator,
but when in a field set, only a basic validator would be found.
We are adjusting the view object class to provide IForm rather than
IEasyFormForm or IGroup to make one of the objects less specific.
Same for the default factory.
This allows us to find another adapter other than the current one.
This allows us to find any custom adapters for any fields that we have overridden
"""
new_obj = []
found = False
for obj in objects:
interfaces = list(providedBy(obj).interfaces())
try:
index = interfaces.index(specific_interface)
found = True
except ValueError:
pass
else:
super_inferface = interfaces[index + 1]
@implementer(super_inferface)
class Wrapper(object):
def __init__(self, view):
self.__view__ = view
def __getattr__(self, item):
return getattr(self.__view__, item)
obj = Wrapper(obj) # Make one class less specific
new_obj.append(obj)
if not found:
return None
provided_by = providedBy(adapter)
# With zope.interface 5.0.2, the info we seek is in 'declared'.
# With 5.1.0+, it can also be in the 'interfaces()' iterator,
# especially for groups (field sets).
# But it looks like interfaces() works always.
# adapter_interfaces = provided_by.declared
# if not adapter_interfaces:
adapter_interfaces = list(provided_by.interfaces())
if not adapter_interfaces:
return
return queryMultiAdapter(new_obj, adapter_interfaces[0], name=name)
@implementer(IValidator)
@adapter(IEasyForm, Interface, IEasyFormForm, IField, Interface)
class FieldExtenderValidator(object):
"""z3c.form validator class for easyform fields in the default fieldset"""
def __init__(self, context, request, view, field, widget):
self.context = context
self.request = request
self.view = view
self.field = field
self.widget = widget
def validate(self, value):
"""Validate field by TValidator"""
# By default this will call SimpleFieldValidator.validator but allows for a fields
# custom validation adaptor to also be called such as recaptcha
_, _, view_interface, _, _ = self.__class__.__component_adapts__
validator = superAdapter(
view_interface,
self,
(self.context, self.request, self.view, self.field, self.widget),
)
if validator is not None:
validator.validate(value)
efield = IFieldExtender(self.field)
validators = getattr(efield, "validators", [])
if validators:
for validator in validators:
vmethod = queryUtility(IFieldValidator, name=validator)
if not vmethod:
continue
res = vmethod(value, REQUEST=self.request)
if res:
raise Invalid(res)
TValidator = getattr(efield, "TValidator", None)
if TValidator:
try:
cerr = get_expression(self.context, TValidator, value=value)
except Exception as e:
raise Invalid(e)
if cerr:
raise Invalid(cerr)
@implementer(IValidator)
@adapter(IEasyForm, Interface, IGroup, IField, Interface)
class GroupFieldExtenderValidator(FieldExtenderValidator):
"""z3c.form validator class for easyform fields in fieldset groups"""
pass
@implementer(IValue)
@adapter(IEasyForm, Interface, IEasyFormForm, IField, Interface)
class FieldExtenderDefault(object):
"""z3c.form default class for easyform fields in the default fieldset"""
def __init__(self, context, request, view, field, widget):
self.context = context
self.request = request
self.view = view
self.field = field
self.widget = widget
def get(self):
"""Get default value of field from TDefault"""
efield = IFieldExtender(self.field)
TDefault = getattr(efield, "TDefault", None)
if TDefault:
return get_expression(self.context, TDefault)
# see if there is another default adapter for this field instead
_, _, view_interface, _, _ = self.__class__.__component_adapts__
adapter = superAdapter(
view_interface,
self,
(self.context, self.request, self.view, self.field, self.widget),
name="default",
)
if adapter is not None:
return adapter.get()
else:
# TODO: this should have already been done by z3c.form.widget.update() so shouldn't be needed
return self.field.default
@implementer(IValue)
@adapter(IEasyForm, Interface, IGroup, IField, Interface)
class GroupFieldExtenderDefault(FieldExtenderDefault):
"""z3c.form default class for easyform fields in fieldset groups"""
pass
@implementer(IFromUnicode, ILabel)
class Label(Field):
"""A Label field"""
def validate(self, value):
pass
def fromUnicode(self, str):
""" """
return
@implementer(IRichLabel)
class RichLabel(Label):
"""A Rich Label field"""
rich_label = u""
def __init__(self, rich_label=u"", **kw):
self.rich_label = rich_label
super(RichLabel, self).__init__(**kw)
LabelFactory = FieldFactory(Label, _(u"label_label_field", default=u"Label"))
RichLabelFactory = FieldFactory(
RichLabel, _(u"label_richlabel_field", default=u"Rich Label")
)
LabelHandler = BaseHandler(Label)
RichLabelHandler = BaseHandler(RichLabel)
@implementer(IReCaptcha)
class ReCaptcha(TextLine):
"""A ReCaptcha field"""
ReCaptchaFactory = FieldFactory(
ReCaptcha, _(u"label_recaptcha_field", default=u"ReCaptcha")
)
ReCaptchaHandler = BaseHandler(ReCaptcha)
@implementer(IHCaptcha)
class HCaptcha(TextLine):
"""A HCaptcha field"""
HCaptchaFactory = FieldFactory(
HCaptcha, _(u"label_hcaptcha_field", default=u"HCaptcha")
)
HCaptchaHandler = BaseHandler(HCaptcha)
@implementer(INorobotCaptcha)
class NorobotCaptcha(TextLine):
"""A NorobotCaptcha field"""
NorobotFactory = FieldFactory(
NorobotCaptcha, _(u"label_norobot_field", default=u"NorobotCaptcha")
)
NorobotCaptchaHandler = BaseHandler(NorobotCaptcha)
@implementer(ILikert)
class Likert(TextLine):
"""A Likert field"""
def __init__(self, **kwargs):
self.answers = kwargs.get('answers', None)
if 'answers' in kwargs:
del kwargs['answers']
self.questions = kwargs.get('questions', None)
if 'questions' in kwargs:
del kwargs['questions']
Field.__init__(self, **kwargs)
def _validate(self, value):
super(Likert, self)._validate(value)
self.parse(value)
def parse(self, value):
result = dict()
lines = value.split(',')
for line in lines:
if not line:
continue
id, answer = line.split(':')
answer = answer.strip()
if answer not in self.answers:
raise ValueError('Invalid answer value.')
index = int(id)
if index < 1 or index > len(self.questions):
raise ValueError('Invalid question index.')
result[index] = answer
return result
LikertFactory = FieldFactory(
Likert, _(u"label_likert_field", default=u"Likert")
)
LikertHandler = BaseHandler(Likert)