MultiRelationField.py 20.7 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2
##############################################################################
#
3
# Copyright (c) 2002, 2004 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
5
#                    Romain Courteaud <romain@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
#
# 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
34
from Products.CMFCore.utils import getToolByName
35 36 37 38
from Products.ERP5Form import RelationField
from Products.ERP5Form.RelationField import MAX_SELECT, new_content_prefix
from Globals import get_request
from Products.PythonScripts.Utility import allow_class
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
import string
from zLOG import LOG
#MAX_SELECT = 50 # Max. number of catalog result
#new_content_prefix = '_newContent_'

def checkSameKeys(a , b):
  """
    Checks if the two lists contain
    the same values
  """
  same = 1
  for ka in a:
    if (not ka in b) and (ka != ''):
      same = 0
  for kb in b:
    if (not kb in a) and (kb != ''):
      same = 0
  return same


class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget, RelationField.RelationStringFieldWidget):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
61 62 63 64 65 66 67 68 69 70 71
    """
        RelationStringField widget

        Works like a string field but includes one buttons

        - one search button which updates the field and sets a relation

        - creates object if not there

    """
    property_names = Widget.LinesTextAreaWidget.property_names + \
72 73 74 75 76 77 78 79 80 81 82
                     RelationField.RelationStringFieldWidget.property_names

    # delete double in order to keep a usable ZMI...
    #property_names = dict([(i,0) for i in property_names]).keys() # XXX need to keep order !
    _v_dict = {}
    _v_property_name_list = []
    for property_name in property_names:
      if not _v_dict.has_key(property_name):
        _v_property_name_list.append(property_name)
        _v_dict[property_name] = 1
    property_names = _v_property_name_list
83

Romain Courteaud's avatar
Romain Courteaud committed
84

Jean-Paul Smets's avatar
Jean-Paul Smets committed
85
    def render(self, field, key, value, REQUEST):
86 87
        """
          Render text input field.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
88
        """
89
        here = REQUEST['here']
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

        relation_field_id = 'relation_%s' % key
        relation_item_id = 'item_%s' % key

        portal_url = getToolByName(here, 'portal_url')
        portal_url_string = portal_url()
        portal_object = portal_url.getPortalObject()

        if type(value) == type(''):
          # Value is a string, reformat it correctly
          value_list = string.split(value, "\r\n")
        else:
          value_list = value

        need_validation = 0
        # Check all relation
        for i in range( len(value_list) ):
107 108
          relation_field_id = 'relation_%s_%s' % ( key, i )
          relation_item_id = 'item_%s_%s' % ( key, i )
109 110 111
          if REQUEST.has_key(relation_item_id) and value_list[i] != '':
            need_validation = 1
            break
112

113 114 115 116 117
        html_string = ''
        if need_validation:
          # Check all relation
          for i in range( len(value_list) ):
            value = value_list[i]
118 119 120
            relation_field_id = 'relation_%s_%s' % ( key, i )
            relation_item_id = 'item_%s_%s' % ( key, i )

121 122 123 124 125 126

            # If we get a empty string, display nothing !
            if value == '':
              pass

            else:
127

128
              html_string += Widget.TextWidget.render(self, field, key, value, REQUEST)
129

130 131
              if REQUEST.has_key(relation_item_id):
                relation_item_list = REQUEST.get(relation_item_id)
132

133 134 135 136 137 138 139 140 141 142
                if relation_item_list != []:
                  # Define default tales on the fly
                  tales_expr = field.tales.get('items', None)
                  defined_tales = 0
                  if not tales_expr:
                    defined_tales = 1
                    from Products.Formulator.TALESField import TALESMethod
                    field.tales['items'] = TALESMethod('REQUEST/relation_item_list')


143 144 145 146
                  REQUEST['relation_item_list'] = relation_item_list
                  html_string += '&nbsp;%s&nbsp;' % Widget.ListWidget.render(self,
                                        field, relation_field_id, None, REQUEST)
                  REQUEST['relation_item_list'] = None
147 148 149 150 151

                  if defined_tales:
                    # Delete default tales on the fly
                    field.tales['items'] = None

152
                else:
153
                  html_string += '&nbsp;<input type="image" src="%s/images/exec16.png" value="update..." name="%s/portal_selections/viewSearchRelatedDocumentDialog%s_%s:method"/>' \
154 155 156 157 158 159 160
                    %  (portal_url_string, portal_object.getPath(), field.aq_parent._v_relation_field_index, i)

              html_string += '<br/>'

        else:
          # no modification made, we can display only a lines text area widget
          html_string += Widget.LinesTextAreaWidget.render(self, field, key, value_list, REQUEST)
Romain Courteaud's avatar
Romain Courteaud committed
161

162
          html_string += '&nbsp;<input type="image" src="%s/images/exec16.png" value="update..." name="%s/portal_selections/viewSearchRelatedDocumentDialog%s:method"/>' \
163
              %  (portal_url_string, portal_object.getPath(), field.aq_parent._v_relation_field_index)
Romain Courteaud's avatar
Romain Courteaud committed
164

165
          if value_list not in ((), [], None, ['']) and value_list == field.get_value('default') and field.get_value('allow_jump') == 1 :
166
            if REQUEST.get('selection_name') is not None:
167
              html_string += '&nbsp;&nbsp;<a href="%s?field_id=%s&form_id=%s&selection_name=%s&selection_index=%s"><img src="%s/images/jump.png"/></a>' \
168 169
                % (field.get_value('jump_method'), field.id, field.aq_parent.id, REQUEST.get('selection_name'), REQUEST.get('selection_index'),portal_url_string)
            else:
170
              html_string += '&nbsp;&nbsp;<a href="%s?field_id=%s&form_id=%s"><img src="%s/images/jump.png"/></a>' \
171 172
                % (field.get_value('jump_method'), field.id, field.aq_parent.id,portal_url_string)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
173
        relation_field_index = getattr(field.aq_parent, '_v_relation_field_index', 0)
174
        field.aq_parent._v_relation_field_index = relation_field_index + 1 # Increase index
175 176 177 178 179 180
        return html_string

    def render_view(self, field, value):
        """
          Render text field.
        """
181
        if field.get_value('allow_jump') == 0 :
182 183
          return Widget.LinesTextAreaWidget.render_view(self, field, value)

184 185 186 187 188 189 190 191
        REQUEST = get_request()
        here = REQUEST['here']

        portal_url = getToolByName(here, 'portal_url')
        portal_url_string = portal_url()

        # no modification made, we can display only a lines text area widget
        html_string = Widget.LinesTextAreaWidget.render_view(self, field, value)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
192 193
        if value not in ((), [], None, ''):
          if REQUEST.get('selection_name') is not None:
194
            html_string += '&nbsp;&nbsp;<a href="%s?field_id=%s&form_id=%s&selection_name=%s&selection_index=%s"><img src="%s/images/jump.png"/></a>' \
195
              % (field.get_value('jump_method'), field.id, field.aq_parent.id, REQUEST.get('selection_name'), REQUEST.get('selection_index'),portal_url_string)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
196
          else:
197
            html_string += '&nbsp;&nbsp;<a href="%s?field_id=%s&form_id=%s"><img src="%s/images/jump.png"/></a>' \
198
              % (field.get_value('jump_method'), field.id, field.aq_parent.id,portal_url_string)
199

Jean-Paul Smets's avatar
Jean-Paul Smets committed
200 201
        return html_string

202 203 204 205 206 207
class MultiRelationEditor:
    """
      A class holding all values required to update a relation
    """
    def __init__(self, field_id, base_category, portal_type, portal_type_item, key, relation_setter_id, relation_editor_list):

208

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
      self.field_id = field_id
      self.base_category = base_category
      self.portal_type = portal_type
      self.portal_type_item = portal_type_item
      self.key = key
      self.relation_setter_id = relation_setter_id
      self.relation_editor_list = relation_editor_list


    def __call__(self, REQUEST):
      if self.relation_editor_list != None:
        value_list = []


        for i, value, uid, display_text in self.relation_editor_list:
224
          value_list.append(value)
225 226 227
          if uid is not None:
            # Decorate the request so that we can display
            # the select item in a popup
228 229 230 231 232 233
            #relation_field_id = 'relation_%s_%s' % ( self.key, i )
            #relation_item_id = 'item_%s_%s' % ( self.key, i )
            relation_field_id = 'relation_field_%s_%s' % ( self.field_id, i )
            relation_item_id = 'item_field_%s_%s' % ( self.field_id, i )


234 235
            REQUEST.set(relation_item_id, ((display_text, uid),))
            REQUEST.set(relation_field_id, uid)
236

237 238 239
        REQUEST.set(self.field_id, value_list) # XXX Dirty
      else:
        # Make sure no default value appears
240
        #REQUEST.set(self.field_id[len('field_'):], None)
241
        REQUEST.set(self.field_id, None) # XXX Dirty
242

243
    def view(self):
244 245 246
      return self.__dict__

    def edit(self, o):
247
      if self.relation_editor_list != None:
248

249
        relation_uid_list = []
250
        relation_object_list = []
251

252 253 254 255 256 257 258 259 260
        for i, value, uid, display_text in self.relation_editor_list:
          if uid is not None:
            if type(uid) is type('a') and uid.startswith(new_content_prefix):
              # Create a new content
              portal_type = uid[len(new_content_prefix):]
              portal_module = None
              for p_item in self.portal_type_item:
                if p_item[0] == portal_type:
                  portal_module = o.getPortalObject().getDefaultModuleId( p_item[0] )
261
              if portal_module is not None:
262 263 264 265 266 267 268 269 270
                portal_module_object = getattr(o.getPortalObject(), portal_module)
                kw ={}
                #kw[self.key] = value
                kw[self.key] = string.join( string.split(value,'%'), '' )
                kw['portal_type'] = portal_type
                kw['immediate_reindex'] = 1
                new_object = portal_module_object.newContent(**kw)
                uid = new_object.getUid()
              else:
271
                raise
272 273
          relation_uid_list.append(int(uid))

274 275
          relation_object_list.append( o.portal_catalog.getObject(uid)  )

276 277
        #if relation_uid_list != []:

278
        # Edit relation
279 280 281
        if self.relation_setter_id:
          relation_setter = getattr(o, self.relation_setter_id)
          relation_setter((), portal_type=self.portal_type)
282
          relation_setter( relation_uid_list , portal_type=self.portal_type)
283
        else:
284 285 286
          # we could call a generic method which create the setter method name
          set_method_name = '_set'+convertToUpperCase(self.base_category)+'ValueList'
          getattr(o, set_method_name)( relation_object_list , portal_type=self.portal_type)
287 288 289 290

      else:
        # Nothing to do
        pass
291
#        # Delete relation
292 293 294 295
#        if self.relation_setter_id:
#          relation_setter = getattr(o, self.relation_setter_id)
#          relation_setter((), portal_type=self.portal_type)
#        else:
296
#          o._setValueUids(self.base_category, (), portal_type=self.portal_type)
297 298 299 300

allow_class(MultiRelationEditor)


301
class MultiRelationStringFieldValidator(Validator.LinesValidator,  RelationField.RelationStringFieldValidator):
302 303
    """
        Validation includes lookup of relared instances
304
    """
305 306 307 308 309 310 311 312 313 314 315 316
    message_names = Validator.LinesValidator.message_names + \
                     RelationField.RelationStringFieldValidator.message_names

    # delete double in order to keep a usable ZMI...
    #message_names = dict([(i,0) for i in message_names]).keys() # XXX need to keep order !
    _v_dict = {}
    _v_message_name_list = []
    for message_name in message_names:
      if not _v_dict.has_key(message_name):
        _v_message_name_list.append(message_name)
        _v_dict[message_name] = 1
    message_names = _v_message_name_list
317

318 319 320 321 322 323 324
    def validate(self, field, key, REQUEST):
      portal_type = map(lambda x:x[0],field.get_value('portal_type'))
      portal_type_item = field.get_value('portal_type')
      base_category = field.get_value( 'base_category')

      # If the value is different, build a query
      portal_selections = getToolByName(field, 'portal_selections')
325
      portal_catalog = getToolByName(field, 'portal_catalog')
326 327 328 329 330 331

      # Get the current value
      value_list = Validator.LinesValidator.validate(self, field, key, REQUEST)

#      if type(value_list) == type(''):
#        value_list = [value_list]
332

333 334 335 336 337 338 339 340
      # If the value is the same as the current field value, do nothing
      current_value_list = field.get_value('default')
      if type(current_value_list) == type(''):
        current_value_list = [current_value_list]

      catalog_index = field.get_value('catalog_index')
      relation_setter_id = field.get_value('relation_setter_id')

341
      relation_field_id = 'relation_%s' % ( key )
342 343
      # we must know if user validate the form or click on the wheel button
      relation_uid_list = REQUEST.get(relation_field_id, None)
344
      relation_field_sub_id = 'relation_%s_0' % ( key )
345
      if checkSameKeys( value_list, current_value_list ) and (relation_uid_list is None)  and (not REQUEST.has_key( relation_field_sub_id )):
346 347 348
        # XXX Will be interpreted by Base_edit as "do nothing"
        #return MultiRelationEditor(field.id, base_category, portal_type, portal_type_item, catalog_index, relation_setter_id, None)
        return None
349

350 351
      else:

352
        relation_field_id = 'relation_%s' % ( key )
Romain Courteaud's avatar
Romain Courteaud committed
353

354
        # We must be able to erase the relation
355
        if (value_list == ['']) and (not REQUEST.has_key( relation_field_id )):
356 357
          display_text = 'Delete the relation'
          return MultiRelationEditor(field.id, base_category, portal_type, portal_type_item, catalog_index, relation_setter_id, [])
358
#          return RelationEditor(key, base_category, portal_type, None,
359 360
#                                portal_type_item, catalog_index, value, relation_setter_id, display_text)
                                # Will be interpreted by Base_edit as "delete relation" (with no uid and value = '')
Romain Courteaud's avatar
Romain Courteaud committed
361 362

        if REQUEST.has_key( relation_field_id ):
Romain Courteaud's avatar
Romain Courteaud committed
363 364 365 366 367 368
          # we must know if user validate the form or click on the wheel button
          relation_uid_list = REQUEST.get(relation_field_id, None)
          if relation_uid_list != None:
            relation_editor_list = []
            for i in range( len(relation_uid_list) ):

369
              relation_item_id = 'item_%s_%s' % ( key, i )
Romain Courteaud's avatar
Romain Courteaud committed
370
              relation_uid = relation_uid_list[i]
371

Romain Courteaud's avatar
Romain Courteaud committed
372 373 374 375
              related_object = portal_catalog.getObject(relation_uid)
              if related_object is not None:
                display_text = str(related_object.getProperty(catalog_index))
              else:
376 377
                display_text = 'Object has been deleted'
              # Check
Romain Courteaud's avatar
Romain Courteaud committed
378
              REQUEST.set(relation_item_id, ( (display_text, relation_uid),  ))
379 380
              # Storing display_text as value is needded in this case
              relation_editor_list.append( (i, display_text, str(relation_uid), display_text) )
Romain Courteaud's avatar
Romain Courteaud committed
381

Romain Courteaud's avatar
Romain Courteaud committed
382
            return MultiRelationEditor(field.id, base_category, portal_type, portal_type_item, catalog_index, relation_setter_id, relation_editor_list)
383 384


385
        else:
Romain Courteaud's avatar
Romain Courteaud committed
386 387
          # User validate the form

388 389 390
          relation_editor_list = []
          raising_error_needed = 0
          raising_error_value = ''
391

392 393
          # Check all relation
          for i in range( len(value_list) ):
394 395 396
            relation_field_id = 'relation_%s_%s' % ( key, i )
            relation_item_id = 'item_%s_%s' % ( key, i )

397 398 399 400
            relation_uid = REQUEST.get(relation_field_id, None)

            value = value_list[i]

401

402 403 404 405 406 407 408 409 410 411 412 413
            # If we get a empty string, delete this line
            if value == '':
              # Clean request if necessary
              if REQUEST.has_key( relation_field_id):
                REQUEST.pop(relation_field_id)

            else:
              # Got a true value

              if relation_uid not in (None, ''):
                # A value has been defined by the user in  popup menu
                if type(relation_uid) in (type([]), type(())): relation_uid = relation_uid[0]
414 415 416 417 418
                try:
                  related_object = portal_catalog.getObject(relation_uid)
                except ValueError:
                  # Catch the exception raised when the uid is a string
                  related_object = None
419 420 421
                if related_object is not None:
                  display_text = str(related_object.getProperty(catalog_index))
                else:
422 423
                  display_text = 'Object has been deleted'
                # Check
424 425 426 427 428 429 430 431
                REQUEST.set(relation_item_id, ( (display_text, relation_uid),  ))
                relation_editor_list.append( (i, value, str(relation_uid), display_text) )

              else:

                kw ={}
                kw[catalog_index] = value
                kw['portal_type'] = portal_type
432
                kw['sort_on'] = catalog_index
433 434 435 436 437 438 439 440
                # Get the query results
                relation_list = portal_catalog(**kw)
                relation_uid_list = map(lambda x: x.uid, relation_list)

                # Prepare a menu
                menu_item_list = [('', '')]
                new_object_menu_item_list = []
                for p in portal_type:
441
                  new_object_menu_item_list += [('New %s' % p, '%s%s' % (new_content_prefix,p))]
442

443
                if len(relation_list) >= MAX_SELECT:
444 445 446 447 448 449 450 451 452 453 454 455 456
                  # If the length is long, raise an error
                  # This parameter means we need listbox help
                  REQUEST.set(relation_item_id, [])
                  raising_error_needed = 1
                  raising_error_value = 'relation_result_too_long'

                elif len(relation_list) == 1:
                  # If the length is 1, return uid
                  relation_uid = relation_uid_list[0]
                  related_object = portal_catalog.getObject(relation_uid)
                  if related_object is not None:
                    display_text = str(related_object.getProperty(catalog_index))
                  else:
457 458
                    display_text = 'Object has been deleted'

459 460
                  REQUEST.set(relation_item_id, ( (display_text, relation_uid),  ))
                  relation_editor_list.append( (0, value, relation_uid, display_text) )
461

462 463
                elif len(relation_list) == 0:
                  # If the length is 0, raise an error
464 465
                  if field.get_value('allow_creation') == 1 :
                    menu_item_list += new_object_menu_item_list
466 467 468 469 470 471 472
                  REQUEST.set(relation_item_id, menu_item_list)
                  raising_error_needed = 1
                  raising_error_value = 'relation_result_empty'

                else:
                  # If the length is short, raise an error
                  # len(relation_list) < MAX_SELECT:
473 474 475

                  #menu_item_list += [('-', '')]
                  menu_item_list += map(lambda x: (x.getObject().getProperty(catalog_index), x.uid),
476 477 478 479
                                                                                  relation_list)
                  REQUEST.set(relation_item_id, menu_item_list)
                  raising_error_needed = 1
                  raising_error_value = 'relation_result_ambiguous'
480

481 482 483 484 485 486 487 488 489 490 491
          # validate MultiRelation field
          if raising_error_needed:
            # Raise error
            self.raise_error(raising_error_value, field)
            return value_list
          else:
            # Can return editor
            return MultiRelationEditor(field.id, base_category, portal_type, portal_type_item, catalog_index, relation_setter_id, relation_editor_list)



Jean-Paul Smets's avatar
Jean-Paul Smets committed
492
MultiRelationStringFieldWidgetInstance = MultiRelationStringFieldWidget()
493
MultiRelationStringFieldValidatorInstance = MultiRelationStringFieldValidator()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
494 495 496

class MultiRelationStringField(ZMIField):
    meta_type = "MultiRelationStringField"
497
    is_relation_field = 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
498 499 500 501 502 503

    widget = MultiRelationStringFieldWidgetInstance
    validator = MultiRelationStringFieldValidatorInstance