[7342] | 1 | """A phone number widget. |
---|
| 2 | |
---|
| 3 | This widget is an input widget (not made for display forms but for |
---|
| 4 | edit and add forms). |
---|
| 5 | |
---|
| 6 | It can be used for :class:`zope.schema.TextLine` fields but has to be |
---|
| 7 | requested by the form manually (otherwise the regular TextLine widget |
---|
| 8 | will be used for rendering). |
---|
| 9 | |
---|
[7352] | 10 | If you use the PhoneWidget for rendering regular TextLine attributes |
---|
| 11 | (preferably in edit forms or add forms), the phone number is displayed |
---|
| 12 | by three input fields representing the international code, the area |
---|
[7856] | 13 | code and the extension line. |
---|
[7352] | 14 | |
---|
| 15 | When the entered input is stored with a context object, it is stored |
---|
| 16 | as a single unicode string with the numbers divided by single hyphen. |
---|
| 17 | |
---|
[7856] | 18 | So, input <+12>, <111>, <444> becomes the string ``'+12-111-444'`` for |
---|
[7352] | 19 | the context object. |
---|
[7342] | 20 | """ |
---|
[7840] | 21 | import grok |
---|
[7342] | 22 | import re |
---|
[7874] | 23 | from zope.component import queryUtility |
---|
[7856] | 24 | from zope.formlib.interfaces import MissingInputError, InputErrors |
---|
| 25 | from zope.interface import Interface |
---|
[7846] | 26 | from zope.formlib.textwidgets import ( |
---|
| 27 | TextWidget, renderElement, ConversionError) |
---|
[7874] | 28 | from waeup.kofa.interfaces import IKofaUtils |
---|
[7846] | 29 | from waeup.kofa.interfaces import MessageFactory as _ |
---|
[7874] | 30 | from waeup.kofa.utils.utils import KofaUtils |
---|
[7840] | 31 | |
---|
[7848] | 32 | RE_INT_PREFIX = re.compile('^\+\d+') |
---|
[7846] | 33 | RE_NUMBERS = re.compile('^\d+$') |
---|
| 34 | RE_NUMBERS_AND_HYPHENS = re.compile('^[\d\-]+$') |
---|
| 35 | |
---|
[7852] | 36 | class PhoneWidget(TextWidget): |
---|
[7840] | 37 | |
---|
| 38 | subwidget_names = ('country', 'area', 'ext') |
---|
[11254] | 39 | cssClass = 'phone-input' |
---|
[7840] | 40 | |
---|
| 41 | def _renderPrefixWidget(self, value): |
---|
[7874] | 42 | prefix_func = getattr( |
---|
| 43 | queryUtility(IKofaUtils), 'sorted_phone_prefixes', |
---|
| 44 | KofaUtils.sorted_phone_prefixes) |
---|
[7840] | 45 | options = [] |
---|
[7874] | 46 | for ptitle, pval in prefix_func(request=self.request): |
---|
[7840] | 47 | selected = '' |
---|
| 48 | if value == pval: |
---|
| 49 | selected = ' selected="selected" ' |
---|
| 50 | options.append( |
---|
| 51 | '<option value="%s"%s>%s</option>' % (pval, selected, ptitle)) |
---|
| 52 | options = '\n'.join(options) |
---|
[11254] | 53 | return '<select id="%s" name="%s" size="1" class="%s">\n%s\n</select>' % ( |
---|
[7840] | 54 | '%s.%s' % (self.name, 'country'), |
---|
| 55 | '%s.%s' % (self.name, 'country'), |
---|
[11254] | 56 | self.cssClass, |
---|
[7840] | 57 | options) |
---|
| 58 | |
---|
| 59 | def __call__(self): |
---|
| 60 | value = self._getFormValue() |
---|
| 61 | if value is None or value == self.context.missing_value: |
---|
| 62 | value = '' |
---|
| 63 | if len(value.split('-')) < 2: |
---|
| 64 | value = '--' + value |
---|
| 65 | subvalues = value.split('-', 2) |
---|
| 66 | |
---|
| 67 | kwargs = {'type': self.type, |
---|
| 68 | 'name': self.name, |
---|
| 69 | 'id': self.name, |
---|
| 70 | 'value': value, |
---|
| 71 | 'cssClass': self.cssClass, |
---|
| 72 | 'style': self.style, |
---|
| 73 | 'size': self.displayWidth, |
---|
| 74 | 'extra': self.extra} |
---|
| 75 | if self.displayMaxWidth: |
---|
| 76 | kwargs['maxlength'] = self.displayMaxWidth # TODO This is untested. |
---|
| 77 | fields = [] |
---|
| 78 | for num, subname in enumerate(self.subwidget_names): |
---|
| 79 | if num == 0: |
---|
| 80 | select = self._renderPrefixWidget(subvalues[num]) |
---|
| 81 | fields.append(select) |
---|
| 82 | continue |
---|
| 83 | print select |
---|
| 84 | kwargs.update(name = '%s.%s' % (self.name, subname)) |
---|
| 85 | kwargs.update(id=kwargs['name']) |
---|
[11254] | 86 | kwargs.update(cssClass = '%s %s' % ('', self.cssClass)) |
---|
[7840] | 87 | kwargs.update(value = subvalues[num]) |
---|
| 88 | fields.append(renderElement(self.tag, **kwargs)) |
---|
| 89 | return '-'.join(fields) |
---|
| 90 | |
---|
| 91 | def _getFormInput(self): |
---|
| 92 | """Returns current form input. |
---|
| 93 | |
---|
| 94 | The value returned must be in a format that can be used as the 'input' |
---|
| 95 | argument to `_toFieldValue`. |
---|
| 96 | |
---|
| 97 | The default implementation returns the form value that corresponds to |
---|
| 98 | the widget's name. Subclasses may override this method if their form |
---|
| 99 | input consists of more than one form element or use an alternative |
---|
| 100 | naming convention. |
---|
| 101 | """ |
---|
| 102 | result = '-'.join( |
---|
[7846] | 103 | [self.request.get('%s.%s' % (self.name, name), '') |
---|
[7840] | 104 | for name in self.subwidget_names]) |
---|
| 105 | return result |
---|
| 106 | |
---|
[7846] | 107 | def _toFieldValue(self, input): |
---|
| 108 | """Check value entered in form further. |
---|
| 109 | |
---|
| 110 | Raises ConversionError if values entered contain non-numbers. |
---|
| 111 | |
---|
| 112 | For the extension line we silently allow slashes as well. |
---|
| 113 | """ |
---|
[8937] | 114 | # In import files we can use the hash symbol at the end of a |
---|
| 115 | # date string to avoid annoying automatic number transformation |
---|
| 116 | # by Excel or Calc |
---|
| 117 | input = input.strip('#') |
---|
[7852] | 118 | result = super(PhoneWidget, self)._toFieldValue(input) |
---|
[7846] | 119 | parts = input.split('-', 2) |
---|
| 120 | if '' in parts and self.context.required: |
---|
| 121 | raise ConversionError( |
---|
| 122 | _("Empty phone field(s)."), MissingInputError( |
---|
[8169] | 123 | self.name, self.label, None)) |
---|
[7848] | 124 | if parts[0] != '' and not RE_INT_PREFIX.match(parts[0]): |
---|
[7846] | 125 | raise ConversionError( |
---|
[7848] | 126 | _("Int. prefix requires format '+NNN'"), |
---|
| 127 | ValueError('invalid international prefix')) |
---|
[8169] | 128 | # Make sure there are only numbers in parts 1..N. We do not allow |
---|
| 129 | # dashes in last field any more. |
---|
| 130 | errors = [(x != '' and not RE_NUMBERS.match(x)) for x in parts[1:]] |
---|
| 131 | error = True in errors |
---|
| 132 | if error: |
---|
[7848] | 133 | raise ConversionError( |
---|
[7846] | 134 | _("Phone numbers may contain numbers only."), |
---|
| 135 | ValueError('non numbers in phone number')) |
---|
[8169] | 136 | # We consider also values ending with empty ending as missing |
---|
| 137 | # values. An 'empty ending' is a form where the fields |
---|
| 138 | # following the prefix are all empty. This means that any |
---|
| 139 | # prefix setting in the form will switch back to default upon |
---|
| 140 | # submit if no further phone fields are filled. As advantage |
---|
| 141 | # we get only valid phone numbers or missing value. |
---|
| 142 | empty_ending = '-'*(len(parts) - 1) |
---|
| 143 | if result in ('', None) or result.endswith(empty_ending): |
---|
[7848] | 144 | result = self.context.missing_value |
---|
[7846] | 145 | return result |
---|
| 146 | |
---|
| 147 | def _getFormValue(self): |
---|
| 148 | """Returns a value suitable for use in an HTML form. |
---|
| 149 | |
---|
| 150 | Detects the status of the widget and selects either the input value |
---|
| 151 | that came from the request, the value from the _data attribute or the |
---|
| 152 | default value. |
---|
| 153 | """ |
---|
| 154 | try: |
---|
| 155 | input_value = self._getCurrentValueHelper() |
---|
| 156 | except InputErrors: |
---|
| 157 | form_value = '-'.join( |
---|
| 158 | [self.request.form.get('%s.%s' % (self.name, name), '') |
---|
| 159 | for name in self.subwidget_names] |
---|
| 160 | ) |
---|
| 161 | else: |
---|
| 162 | form_value = self._toFormValue(input_value) |
---|
| 163 | return form_value |
---|
| 164 | |
---|
[7840] | 165 | def hasInput(self): |
---|
[7846] | 166 | """A phone widget has input if all three subfields have input. |
---|
| 167 | """ |
---|
[7840] | 168 | for name in self.subwidget_names: |
---|
| 169 | if '%s.%s' % (self.name, name) not in self.request.form: |
---|
| 170 | return False |
---|
| 171 | return True |
---|