FormBox.py 7.63 KB
Newer Older
1
# -*- coding: utf-8 -*-
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
##############################################################################
#
# Copyright (c) 2002-2006 Nexedi SARL and Contributors. All Rights Reserved.
#                    Jean-Paul Smets <jp@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

from Products.Formulator import Widget, Validator
from Products.Formulator.Field import ZMIField
from Products.Formulator.DummyField import fields
from Products.ERP5Type.Utils import convertToUpperCase
from Products.CMFCore.utils import getToolByName

from Products.PageTemplates.PageTemplateFile import PageTemplateFile

38
from Products.ERP5Type.Globals import get_request
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39 40 41
from Products.PythonScripts.Utility import allow_class

from Products.PythonScripts.standard import url_quote_plus
42
from Products.Formulator.Errors import FormValidationError, ValidationError
Jean-Paul Smets's avatar
Jean-Paul Smets committed
43 44 45 46 47 48 49

import string

class FormBoxWidget(Widget.Widget):
  """
      A widget that display a form within a form.

50
      A first purpose of this widget is to display addresses in
Jean-Paul Smets's avatar
Jean-Paul Smets committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64
      a different order for every localisation.

      A second purpose of this widget is to represent a single value
      (ex. a number, a date) into multiple forms. We need for that
      purpose a script to assemble a value out of

      A third purpose is to display values on subobjects and,
      if necessary, create such objects ?

      WARNING: this is still pre-alpha code for experimentation. Do not
      use in production.
  """

  property_names = Widget.Widget.property_names + [
65
    'formbox_target_id', \
66
    'context_method_id', \
Jean-Paul Smets's avatar
Jean-Paul Smets committed
67 68
  ]

69 70 71
  # This name was changed to prevent naming collision with ProxyField
  formbox_target_id = fields.StringField(
                                'formbox_target_id',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
72 73 74 75
                                title='Form ID',
                                description=(
    "ID of the form which must be rendered in this box."),
                                default="",
76
                                required=0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
77

78 79 80 81 82 83 84 85
  context_method_id = fields.StringField(
                                'context_method_id',
                                title='Context method ID',
                                description=(
    "ID of the method that returns a context for this box."),
                                default="",
                                required=0)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
86 87 88 89 90 91 92 93
  default = fields.StringField(
                                'default',
                                title='Default',
                                description=(
    "A default value (not used)."),
                                default="",
                                required=0)

94 95 96 97
  def render_view(self, field, value, REQUEST, render_prefix=None):
    """
        Render a view form in a field
    """
98
    return self.render(field, None, value, REQUEST, render_prefix)
99

100 101 102 103
  def render(self, field, key, value, REQUEST, render_prefix=None):
    """
        Render a form in a field
    """
104
    target_id = field.get_value('formbox_target_id')
105 106 107
    if target_id:
      other = REQUEST.other
      here = other['here']
108
      context_method_id = field.get_value('context_method_id')
109
      try:
110 111
        cell = other.pop('cell', None)
        context = cell or here
112
        if context_method_id:
113 114 115 116 117 118 119 120
          context = getattr(context, context_method_id)(
            field=field, REQUEST=REQUEST)
        return getattr(context, target_id)(REQUEST=REQUEST, key_prefix=key)
      finally:
        other['here'] = here
        if cell:
          other['cell'] = cell
    return ''
121 122

class FormBoxEditor:
123
  """An editor returned from FormBox validation able to `edit` document."""
124

125 126 127 128 129 130 131
  def __init__(self, result, context_method_id=None):
    """Initialize with all necessary information for editing a document.

    :result: tuple of attributes, editors intended as parameters for edit function
    :context_method_id: editor needs to operate on the correct context (Document)
                        but it cannot hold reference because then weird failures
                        appear; thus we keep name of the context-obtaining method
132 133
    """
    self.attr_dict, self.editor_list = result
134
    self.context_method_id = context_method_id
135 136 137 138 139 140

  def view(self):
    return self.__dict__

  def __call__(self, REQUEST):
    pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
141

142
  def edit(self, context):
143 144
    if self.context_method_id:
      context = getattr(context, self.context_method_id)
145 146
    context.edit(**self.attr_dict)
    for encapsulated_editor in self.editor_list:
147
      encapsulated_editor.edit(context)
148 149 150 151 152 153

  def as_dict(self):
    """
    This method is used to return parameter dict.
    XXX This API is probably not stable and may change, as some editors are used to
    edit multiple objects.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
154
    """
155
    result_dict = self.attr_dict.copy()  # avoid modifying own attribute
156
    for encapsulated_editor in self.editor_list:
157 158 159 160 161 162
      if hasattr(encapsulated_editor, 'as_dict'):
        result_dict.update(
            encapsulated_editor.as_dict())
    return result_dict

allow_class(FormBoxEditor)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
163 164 165 166 167 168 169

class FormBoxValidator(Validator.Validator):
  """
    Validate all fields of the form and return
    the result as a single variable.
  """
  property_names = Validator.Validator.property_names
170
  message_names = Validator.Validator.message_names + \
171
                  ['form_invalidated', 'required_not_found']
172 173

  form_invalidated = "Form invalidated."
174
  required_not_found = 'Input is required but no input given.'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
175 176

  def validate(self, field, key, REQUEST):
177
    # XXX hardcoded acquisition
178 179
    # TODO: Handle 'cell' for validation inside listboxes,
    #       like it is done for rendering.
180
    here = field.aq_parent.aq_parent
181 182
    context_method_id = field.get_value('context_method_id')
    if context_method_id:
183
      here = getattr(here, context_method_id)(field=field, REQUEST=REQUEST)
184 185 186 187 188 189
    formbox_target_id = field.get_value('formbox_target_id')

    # Get current error fields
    current_field_errors = REQUEST.get('field_errors', [])

    # XXX Hardcode script name
190
    result, result_type = here.Base_edit(formbox_target_id, silent_mode=1, key_prefix=key)
191
    if result_type == 'edit':
192
      return FormBoxEditor(result, context_method_id)
193 194 195 196
    elif result_type == 'form':
      formbox_field_errors = REQUEST.get('field_errors', [])
      current_field_errors.extend(formbox_field_errors)
      REQUEST.set('field_errors', current_field_errors)
197
      getattr(here, formbox_target_id).validate_all_to_request(REQUEST, key_prefix=key)
198 199
    else:
      raise NotImplementedError, result_type
Jean-Paul Smets's avatar
Jean-Paul Smets committed
200 201 202 203 204 205 206 207 208

FormBoxWidgetInstance = FormBoxWidget()
FormBoxValidatorInstance = FormBoxValidator()

class FormBox(ZMIField):
  meta_type = "FormBox"

  widget = FormBoxWidgetInstance
  validator = FormBoxValidatorInstance