Commit 56f2ee23 authored by Vincent Pelletier's avatar Vincent Pelletier

MultiRelationField: Assorted code cleanups.

Drop dead code.
Update a few archaisms.
Simplify code.
Improve coding style, reduce indentation.
Escape rendering.
parent 0d9c6e7c
...@@ -34,9 +34,9 @@ from Products.ERP5Type.Utils import convertToUpperCase ...@@ -34,9 +34,9 @@ from Products.ERP5Type.Utils import convertToUpperCase
from Products.PythonScripts.Utility import allow_class from Products.PythonScripts.Utility import allow_class
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from types import StringType
from Products.Formulator.DummyField import fields from Products.Formulator.DummyField import fields
from Products.ERP5Type.Globals import get_request from Products.ERP5Type.Globals import get_request
from cgi import escape
import json import json
# Max. number of catalog result # Max. number of catalog result
...@@ -46,6 +46,7 @@ NEW_CONTENT_PREFIX = '_newContent_' ...@@ -46,6 +46,7 @@ NEW_CONTENT_PREFIX = '_newContent_'
SUB_FIELD_ID = 'relation' SUB_FIELD_ID = 'relation'
ITEM_ID = 'item' ITEM_ID = 'item'
NO_VALUE = '??? (No Value)' NO_VALUE = '??? (No Value)'
NBSP = ' '
class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget, class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget,
Widget.TextWidget, Widget.TextWidget,
...@@ -208,12 +209,7 @@ class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget, ...@@ -208,12 +209,7 @@ class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget,
return here return here
def _generateRenderValueList(self, field, key, value_list, REQUEST): def _generateRenderValueList(self, field, key, value_list, REQUEST):
result_list = [] if isinstance(value_list, basestring):
need_validation = 0
####################################
# Check value
####################################
if isinstance(value_list, StringType):
# Value is a string, reformat it correctly # Value is a string, reformat it correctly
value_list = value_list.split("\n") value_list = value_list.split("\n")
else: else:
...@@ -222,99 +218,86 @@ class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget, ...@@ -222,99 +218,86 @@ class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget,
# property is not set # property is not set
# XXX Translate ? # XXX Translate ?
value_list = [(x or NO_VALUE) for x in value_list] value_list = [(x or NO_VALUE) for x in value_list]
# Check all relation generate_subfield_key = field.generate_subfield_key
for i in range(len(value_list)): need_validation = False
################################### result_list = []
# Sub field for index, value in enumerate(value_list):
################################### relation_item_list = REQUEST.get(
relation_field_id = field.generate_subfield_key("%s_%s" % \ generate_subfield_key(
(SUB_FIELD_ID, i), "%s_%s" % (ITEM_ID, index),
key=key) key=key,
relation_item_id = field.generate_subfield_key("%s_%s" % \ ),
(ITEM_ID, i), None,
key=key) )
relation_item_list = REQUEST.get(relation_item_id, None)
value = value_list[i]
if (relation_item_list is not None) and \
(value != ''):
need_validation = 1
# If we get a empty string, display nothing ! # If we get a empty string, display nothing !
if value != '': if value:
result_list.append((Widget.TextWidgetInstance, relation_field_id, need_validation |= relation_item_list is not None
relation_item_list, value, i)) result_list.append(
if not need_validation: (
################################### Widget.TextWidgetInstance,
# Main field generate_subfield_key(
################################### "%s_%s" % (SUB_FIELD_ID, index),
result_list = [(Widget.LinesTextAreaWidgetInstance, None, [], key=key,
value_list, None)] ),
relation_item_list,
value,
index,
),
)
if need_validation:
return result_list return result_list
return [
(Widget.LinesTextAreaWidgetInstance, None, [], value_list, None)
]
def render(self, field, key, value, REQUEST, render_prefix=None): def render(self, field, key, value, REQUEST, render_prefix=None):
""" """
Render text input field. Render text input field.
""" """
html_string = '' portal = self._getContextValue(field, REQUEST).getPortalObject()
autocomplete_enabled = getattr(
portal.portal_skins,
'erp5_autocompletion_ui',
None,
) is not None
relation_field_index = REQUEST.get('_v_relation_field_index', 0) relation_field_index = REQUEST.get('_v_relation_field_index', 0)
render_parameter_list = self._generateRenderValueList(
field, key, value,
REQUEST)
####################################
# Render subfield
####################################
html_string_list = [] html_string_list = []
for widget_instance, relation_field_id, relation_item_list, \ for (
value_instance, sub_index in render_parameter_list: widget_instance,
sub_html_string = widget_instance.render(field, key, relation_field_id,
value_instance, REQUEST) relation_item_list,
value_instance,
here = self._getContextValue(field, REQUEST) sub_index
portal = here.getPortalObject() ) in self._generateRenderValueList(
autocomplete_enabled = getattr(portal.portal_skins, field, key, value, REQUEST,
'erp5_autocompletion_ui', ):
None) sub_html_string = widget_instance.render(
field, key, value_instance, REQUEST,
)
if autocomplete_enabled: if autocomplete_enabled:
sub_html_string += self.render_autocomplete(field, key) sub_html_string += self.render_autocomplete(field, key)
if relation_item_list is not None: if relation_item_list is not None:
####################################
# Render wheel
####################################
if not autocomplete_enabled: if not autocomplete_enabled:
sub_html_string += self.render_wheel( sub_html_string += self.render_wheel(
field, value_instance, REQUEST, field,
value_instance,
REQUEST,
relation_index=relation_field_index, relation_index=relation_field_index,
sub_index=sub_index) sub_index=sub_index,
)
if relation_item_list: if relation_item_list:
####################################
# Render listfield
####################################
REQUEST['relation_item_list'] = relation_item_list REQUEST['relation_item_list'] = relation_item_list
sub_html_string += ' %s ' % \ sub_html_string += NBSP + Widget.ListWidgetInstance.render(
Widget.ListWidgetInstance.render( field, relation_field_id, None, REQUEST,
field, relation_field_id, None, REQUEST) ) + NBSP
REQUEST['relation_item_list'] = None REQUEST['relation_item_list'] = None
html_string_list.append(sub_html_string) html_string_list.append(sub_html_string)
####################################
# Generate html
####################################
html_string = '<br/>'.join(html_string_list) html_string = '<br/>'.join(html_string_list)
####################################
# Render jump
####################################
if (value == field.get_value('default')): if (value == field.get_value('default')):
# XXX Default rendering with value... # XXX Default rendering with value...
relation_html_string = self.render_relation_link(field, value, relation_html_string = self.render_relation_link(field, value, REQUEST)
REQUEST) if relation_html_string:
if relation_html_string != '': html_string += NBSP + NBSP + relation_html_string
html_string += '&nbsp;&nbsp;%s' % relation_html_string
####################################
# Update relation field index
####################################
REQUEST.set('_v_relation_field_index', relation_field_index + 1) REQUEST.set('_v_relation_field_index', relation_field_index + 1)
return html_string return html_string
...@@ -322,43 +305,48 @@ class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget, ...@@ -322,43 +305,48 @@ class MultiRelationStringFieldWidget(Widget.LinesTextAreaWidget,
""" """
Render read only field. Render read only field.
""" """
html_string = '' if (value not in ((), [], None, '')) and field.get_value('allow_jump'):
here = self._getContextValue(field, REQUEST)
portal_url = here.getPortalObject().portal_url
portal_url_string = portal_url()
if (value not in ((), [], None, '')) and \
field.get_value('allow_jump'):
string_list = []
base_category = field.get_value('base_category')
portal_type = map(lambda x:x[0],field.get_value('portal_type'))
kw = {}
for k, v in field.get_value('parameter_list') :
kw[k] = v
accessor_name = 'get%sValueList' % ''.join([part.capitalize() for part in base_category.split('_')])
jump_reference_list = getattr(here, accessor_name)(portal_type=portal_type, filter=kw)
if not isinstance(value, (list, tuple)): if not isinstance(value, (list, tuple)):
value = value, value = value,
for jump_reference, display_value in zip(jump_reference_list, value): html_string = '<br />'.join(
string_list.append('<a class="relationfieldlink" href="%s">%s</a>' % \ '<a class="relationfieldlink" href="%s">%s</a>' % (
(jump_reference.absolute_url(), escape(jump_reference.absolute_url()),
display_value)) escape(display_value),
html_string = '<br />'.join(string_list) )
for jump_reference, display_value in zip(
getattr(
self._getContextValue(field, REQUEST),
'get%sValueList' % ''.join(
part.capitalize()
for part in field.get_value('base_category').split('_')
)
)(
portal_type=[x[0] for x in field.get_value('portal_type')],
filter=dict(field.get_value('parameter_list')),
),
value,
)
)
else: else:
html_string = self.default_widget_rendering_instance.render_view(field, html_string = self.default_widget_rendering_instance.render_view(
value, REQUEST=REQUEST) field,
value,
REQUEST=REQUEST,
)
if REQUEST is None: if REQUEST is None:
REQUEST = get_request() REQUEST = get_request()
relation_html_string = self.render_relation_link(field, value, REQUEST) relation_html_string = self.render_relation_link(field, value, REQUEST)
if relation_html_string != '': if relation_html_string:
html_string += '&nbsp;&nbsp;%s' % relation_html_string html_string += NBSP + NBSP + relation_html_string
extra = field.get_value('extra') extra = field.get_value('extra')
if extra not in (None, ''): if extra not in (None, ''):
html_string = "<div %s>%s</div>" % (extra, html_string) html_string = "<div %s>%s</div>" % (extra, html_string)
css_class = field.get_value('css_class') css_class = field.get_value('css_class')
if css_class not in ('', None): if css_class not in ('', None):
# All strings should be escaped before rendering in HTML html_string = '<span class="%s">%s</span>' % (
# except for editor field escape(css_class),
html_string = "<span class='%s'>%s</span>" % (css_class, html_string) html_string,
)
return html_string return html_string
def render_autocomplete(self, field, key): def render_autocomplete(self, field, key):
...@@ -373,9 +361,11 @@ $(document).ready(function() { ...@@ -373,9 +361,11 @@ $(document).ready(function() {
$("input[name='%s']").ERP5Autocomplete({search_portal_type: %s, $("input[name='%s']").ERP5Autocomplete({search_portal_type: %s,
search_catalog_key: "%s"}); search_catalog_key: "%s"});
}); });
</script>""" % (key, </script>""" % (
json.dumps(map(lambda x: x[0], field.get_value('portal_type'))), escape(key),
field.get_value('catalog_index')) escape(json.dumps([x[0] for x in field.get_value('portal_type')])),
escape(field.get_value('catalog_index')),
)
def render_wheel(self, field, value, REQUEST, relation_index=0, def render_wheel(self, field, value, REQUEST, relation_index=0,
sub_index=None, render_prefix=None): sub_index=None, render_prefix=None):
...@@ -384,8 +374,6 @@ $(document).ready(function() { ...@@ -384,8 +374,6 @@ $(document).ready(function() {
""" """
here = self._getContextValue(field, REQUEST) here = self._getContextValue(field, REQUEST)
portal_url = here.getPortalObject().portal_url portal_url = here.getPortalObject().portal_url
portal_url_string = portal_url()
portal_selections_url_string = here.portal_url.getRelativeContentURL(here.portal_selections)
if sub_index is None: if sub_index is None:
sub_index_string = '' sub_index_string = ''
else: else:
...@@ -393,45 +381,52 @@ $(document).ready(function() { ...@@ -393,45 +381,52 @@ $(document).ready(function() {
return '&nbsp;<input type="image" ' \ return '&nbsp;<input type="image" ' \
'src="%s/images/exec16.png" value="update..." ' \ 'src="%s/images/exec16.png" value="update..." ' \
'name="%s/viewSearchRelatedDocumentDialog%s%s' \ 'name="%s/viewSearchRelatedDocumentDialog%s%s' \
':method"/>' % \ ':method"/>' % (
(portal_url_string, portal_selections_url_string, escape(portal_url()),
relation_index, sub_index_string) escape(portal_url.getRelativeContentURL(here.portal_selections)),
escape(str(relation_index)),
escape(sub_index_string),
)
def render_relation_link(self, field, value, REQUEST, render_prefix=None): def render_relation_link(self, field, value, REQUEST, render_prefix=None):
""" """
Render link to the related object. Render link to the related object.
""" """
html_string = '' if value not in ((), [], None, '') and field.get_value('allow_jump'):
here = self._getContextValue(field, REQUEST)
# If we this relation field is used as a listbox/matrixbox editable # If we this relation field is used as a listbox/matrixbox editable
# field, then the context of this cell is set in REQUEST. XXX this is not # field, then the context of this cell is set in REQUEST. XXX this is not
# 100% reliable way, maybe we need something to know that the field is # 100% reliable way, maybe we need something to know that the field is
# beeing rendered as an editable field. # beeing rendered as an editable field.
cell = REQUEST.get('cell') cell = REQUEST.get('cell')
if cell is not None: here = (
here = cell cell
portal_url = here.getPortalObject().portal_url if cell is not None else
portal_url_string = portal_url() self._getContextValue(field, REQUEST)
if (value not in ((), [], None, '')) and \ )
field.get_value('allow_jump'):
# Keep the selection name in the URL # Keep the selection name in the URL
if REQUEST.get('selection_name') is not None: selection_name = REQUEST.get('selection_name')
selection_name_html = '&amp;selection_name=%s&amp;selection_index=%s' % \ if selection_name is not None:
(REQUEST.get('selection_name'), REQUEST.get('selection_index')) selection_name_html = '&amp;selection_name=%s&amp;selection_index=%s' % (
escape(selection_name),
escape(str(REQUEST.get('selection_index', 0))),
)
else: else:
selection_name_html = '' selection_name_html = ''
if REQUEST.get('ignore_layout') is not None: ignore_layout = REQUEST.get('ignore_layout')
selection_name_html += '&amp;ignore_layout:int=%s' % int(REQUEST.get('ignore_layout', 0)) if ignore_layout is not None:
selection_name_html += '&amp;ignore_layout:int=%s' % int(ignore_layout)
# Generate plan link # Generate plan link
html_string += '<a href="%s/%s?field_id=%s&amp;form_id=%s%s">' \ return '<a href="%s/%s?field_id=%s&amp;form_id=%s%s">' \
'<img src="%s/images/jump.png" alt="jump" />' \ '<img src="%s/images/jump.png" alt="jump" />' \
'</a>' % \ '</a>' % (
(here.absolute_url(), escape(here.absolute_url()),
field.get_value('jump_method'), escape(field.get_value('jump_method')),
field.id, field.aq_parent.id, escape(field.id),
selection_name_html, escape(field.aq_parent.id),
portal_url_string) escape(selection_name_html),
return html_string escape(here.getPortalObject().portal_url()),
)
return ''
class MultiRelationEditor: class MultiRelationEditor:
""" """
...@@ -474,55 +469,48 @@ class MultiRelationEditor: ...@@ -474,55 +469,48 @@ class MultiRelationEditor:
return self.__dict__ return self.__dict__
def edit(self, o): def edit(self, o):
if self.relation_editor_list is not None: if self.relation_editor_list is None:
return
if self.context_getter_id: if self.context_getter_id:
o = getattr(o, self.context_getter_id)() o = getattr(o, self.context_getter_id)()
portal = o.getPortalObject() portal = o.getPortalObject()
getDefaultModuleValue = portal.getDefaultModuleValue
getObject = portal.portal_catalog.getObject
portal_type_set = {x[0] for x in self.portal_type_item}
relation_object_list = [] relation_object_list = []
for value, uid, display_text, relation_key, item_key in \ append = relation_object_list.append
self.relation_editor_list: for (
if uid is not None: value, uid, display_text, relation_key, item_key
if isinstance(uid, StringType) and \ ) in self.relation_editor_list:
uid.startswith(NEW_CONTENT_PREFIX): if isinstance(uid, basestring) and uid.startswith(NEW_CONTENT_PREFIX):
# Create a new content
portal_type = uid[len(NEW_CONTENT_PREFIX):] portal_type = uid[len(NEW_CONTENT_PREFIX):]
portal_module = None if portal_type in portal_type_set:
for p_item in self.portal_type_item: append(
if p_item[0] == portal_type: getDefaultModuleValue(
portal_module = portal.getDefaultModuleId(p_item[0]) portal_type,
if portal_module is not None: only_visible=True,
portal_module_object = getattr(portal, portal_module) ).newContent(
kw ={} portal_type=portal_type,
kw[self.key] = value.replace('%', '') **{
kw['portal_type'] = portal_type self.key: value.replace('%', ''),
new_object = portal_module_object.newContent(**kw) }
relation_object_list.append(new_object) )
else: )
raise elif uid is not None:
else: append(getObject(uid))
relation_object_list.append(portal.portal_catalog.getObject(uid))
set_method_name = self.relation_setter_id
# Edit relation set_method_kw = {}
if self.relation_setter_id: if not set_method_name:
relation_setter = getattr(o, self.relation_setter_id) # XXX: we could call a generic method which create the setter method name
relation_setter((), portal_type=self.portal_type_list)
relation_setter(relation_object_list,
portal_type=self.portal_type_list)
else:
# we could call a generic method which create the setter method name
if len(relation_object_list) == 1:
set_method_name = 'set%sValue' % \
convertToUpperCase(self.base_category)
getattr(o, set_method_name)(relation_object_list[0],
portal_type=self.portal_type_list,
checked_permission='View')
else:
set_method_name = 'set%sValueList' % \ set_method_name = 'set%sValueList' % \
convertToUpperCase(self.base_category) convertToUpperCase(self.base_category)
getattr(o, set_method_name)(relation_object_list, set_method_kw['checked_permission'] = 'View'
getattr(o, set_method_name)(
relation_object_list,
portal_type=self.portal_type_list, portal_type=self.portal_type_list,
checked_permission='View') **set_method_kw
)
allow_class(MultiRelationEditor) allow_class(MultiRelationEditor)
...@@ -561,285 +549,189 @@ class MultiRelationStringFieldValidator(Validator.LinesValidator): ...@@ -561,285 +549,189 @@ class MultiRelationStringFieldValidator(Validator.LinesValidator):
""" """
Generate list of value, item_key Generate list of value, item_key
""" """
item_value_list = [] if isinstance(current_value_list, basestring):
if isinstance(current_value_list, StringType):
current_value_list = [current_value_list] current_value_list = [current_value_list]
# Check value list # Changes in the order or in the number of occurences
if value_list != current_value_list: # Changes in the order or in the number of occurences
# must be taken into account # must be taken into account
for i in range(len(value_list)): if value_list == current_value_list:
value = value_list[i] return []
relation_field_id = field.generate_subfield_key("%s_%s" % \ if value_list:
(SUB_FIELD_ID, i), return [
key=key) (
relation_item_id = field.generate_subfield_key("%s_%s" % \ field.generate_subfield_key(
(ITEM_ID, i), "%s_%s" % (SUB_FIELD_ID, index),
key=key) key=key,
item_value_list.append((relation_field_id, value, relation_item_id)) ),
# Make possible to delete the content of the field. value,
if item_value_list == []: field.generate_subfield_key(
relation_field_id = field.generate_subfield_key("%s" % \ "%s_%s" % (ITEM_ID, index),
SUB_FIELD_ID, key=key) key=key,
relation_item_key = field.generate_subfield_key(ITEM_ID, key=key) ),
item_value_list.append((relation_field_id, '', relation_item_key)) )
return item_value_list for index, value in enumerate(value_list)
]
return [
(
field.generate_subfield_key(SUB_FIELD_ID, key=key),
'',
field.generate_subfield_key(ITEM_ID, key=key),
)
]
def validate(self, field, key, REQUEST): def validate(self, field, key, REQUEST):
""" """
Validate the field. Validate the field.
""" """
raising_error_needed = 0 raising_error_value = None
relation_editor_list = None relation_editor_list = []
# Get some tool
catalog_index = field.get_value('catalog_index') catalog_index = field.get_value('catalog_index')
portal_type_list = [x[0] for x in field.get_value('portal_type')] portal_type_list = [x[0] for x in field.get_value('portal_type')]
portal_catalog = field.getPortalObject().portal_catalog portal = field.getPortalObject()
portal_catalog = portal.portal_catalog
#################################### relation_uid_list = REQUEST.get(
# Check list input field.generate_subfield_key(SUB_FIELD_ID, key=key),
#################################### )
relation_field_id = field.generate_subfield_key("%s" % \ if relation_uid_list in (None, ''):
SUB_FIELD_ID, key=key) value_list = self.default_validator_instance.validate(
relation_uid_list = REQUEST.get(relation_field_id, None) field, key, REQUEST,
)
#################################### field_value_list = self._generateFieldValueList(
# User clicked on the wheel field,
#################################### key,
need_to_revalidate = 1 self.default_validator_instance.validate(field, key, REQUEST),
if relation_uid_list not in (None, ''): field.get_value('default'),
need_to_revalidate = 0 )
relation_editor_list = [] if not field_value_list:
for relation_item_id, relation_uid, value in \ relation_editor_list = None
self._generateItemUidList(field, key, relation_uid_list,
REQUEST=REQUEST):
found = 0
try:
related_object = portal_catalog.getObject(relation_uid)
display_text = str(related_object.getProperty(catalog_index))
found = 1
except ValueError:
# Catch the error raised when the uid is a string
if relation_uid.startswith(NEW_CONTENT_PREFIX):
##############################
# New content was selected, but the
# form is not validated
##############################
portal_type = relation_uid[len(NEW_CONTENT_PREFIX):]
translated_portal_type = translateString(portal_type)
# XXX Replace New by Add
message = translateString('New ${portal_type}',
mapping={'portal_type':translated_portal_type})
display_text = message
else:
display_text = 'Object has been deleted'
################################
# Modify if user modified his value
################################
# XXX Does not work when user select a value in a ListField
# if (found == 1) and \
# (value != display_text):
# relation_editor_list = None
# need_to_revalidate = 1
# REQUEST.set(relation_field_id, None)
# break
if value is None:
value = display_text
# Storing display_text as value is needed in this case
relation_editor_list.append((value,
relation_uid, display_text,
None, relation_item_id))
# str(relation_uid), display_text,
####################################
# User validate the form
####################################
if need_to_revalidate == 1:
# else:
####################################
# Check the default field
####################################
value_list = self.default_validator_instance.validate(field,
key, REQUEST)
# If the value is the same as the current field value, do nothing
current_value_list = field.get_value('default')
field_value_list = self._generateFieldValueList(field, key, value_list,
current_value_list)
if len(field_value_list) != 0:
####################################
# Values were changed
####################################
relation_editor_list = []
for relation_field_id, value, relation_item_id in field_value_list: for relation_field_id, value, relation_item_id in field_value_list:
if value == '': if value == '':
####################################
# User want to delete this line
####################################
# Clean request if necessary
if REQUEST.has_key(relation_field_id):
for subdict_name in ['form', 'other']: for subdict_name in ['form', 'other']:
subdict = getattr(REQUEST, subdict_name) getattr(REQUEST, subdict_name).pop(relation_field_id, None)
if subdict.has_key(relation_field_id): relation_editor_list.append(
subdict.pop(relation_field_id) (value, None, 'Delete the relation', None, None),
display_text = 'Delete the relation' )
relation_editor_list.append((value, None, continue
display_text, None, None)) relation_uid = REQUEST.get(relation_field_id)
# XXX RelationField implementation menu_item_list = []
# # We must be able to erase the relation if relation_uid in (None, ''):
# display_text = 'Delete the relation' kw = dict(field.get_value('parameter_list'))
# # Will be interpreted by Base_edit as "delete relation"
# # (with no uid and value = '')
# relation_editor_list = [(value, None,
# display_text, None, None)]
else:
relation_uid = REQUEST.get(relation_field_id, None)
# need_to_revalidate = 1
if relation_uid not in (None, ''):
# need_to_revalidate = 0
# found = 0
####################################
# User selected in a popup menu
####################################
if isinstance(relation_uid, (list, tuple)):
relation_uid = relation_uid[0]
try:
related_object = portal_catalog.getObject(relation_uid)
except ValueError:
# Catch the exception raised when the uid is a string
related_object = None
if related_object is not None:
display_text = str(related_object.getProperty(catalog_index))
# found = 1
else:
##############################
# New content was selected, but the
# form is not validated
##############################
if relation_uid.startswith(NEW_CONTENT_PREFIX):
##############################
# New content was selected, but the
# form is not validated
##############################
portal_type = relation_uid[len(NEW_CONTENT_PREFIX):]
translated_portal_type = translateString(portal_type)
message = translateString('New ${portal_type}',
mapping={'portal_type':translated_portal_type})
display_text = message
else:
display_text = 'Object has been deleted'
# ################################
# # Modify if user modified his value
# ################################
# if (found == 1) and \
# (value != display_text):
# REQUEST.set(relation_field_id, None)
# need_to_revalidate = 1
# else:
# # Check
# REQUEST.set(relation_item_id, ((display_text, relation_uid),))
# relation_editor_list.append((value, str(relation_uid),
# display_text, relation_field_id,
# relation_item_id))
REQUEST.set(relation_item_id, ((display_text, relation_uid),))
relation_editor_list.append((value, str(relation_uid),
display_text, relation_field_id,
relation_item_id))
# if need_to_revalidate == 1:
else:
####################################
# User validate the form for this line
####################################
kw ={}
kw[catalog_index] = value kw[catalog_index] = value
kw['portal_type'] = portal_type_list relation_list = portal_catalog(
kw['sort_on'] = catalog_index portal_type=portal_type_list,
parameter_list = field.get_value('parameter_list') sort_on=catalog_index,
if len(parameter_list) > 0: **kw
for k,v in parameter_list: )
kw[k] = v
# Get the query results
relation_list = portal_catalog(**kw)
relation_uid_list = [x.uid for x in relation_list] relation_uid_list = [x.uid for x in relation_list]
menu_item_list = []
if len(relation_list) >= MAX_SELECT: if len(relation_list) >= MAX_SELECT:
# If the length is long, raise an error
# This parameter means we need listbox help
# XXX XXX XXX Do we need to delete it ?
REQUEST.set(relation_item_id, [])
raising_error_needed = 1
raising_error_value = 'relation_result_too_long' raising_error_value = 'relation_result_too_long'
elif len(relation_list) == 1: elif len(relation_list) == 1:
# If the length is 1, return uid
relation_uid = relation_uid_list[0] relation_uid = relation_uid_list[0]
related_object = relation_list[0].getObject() related_object = relation_list[0].getObject()
if related_object is not None: if related_object is None:
display_text = str(related_object.getProperty(catalog_index))
# Modify the value, in order to let the user
# modify it later...
value = display_text
else:
display_text = 'Object has been deleted' display_text = 'Object has been deleted'
# XXX XXX XXX else:
REQUEST.set(relation_item_id, ((display_text, value = display_text = str(
relation_uid),)) related_object.getProperty(catalog_index),
relation_editor_list.append((value, relation_uid, )
display_text, None, menu_item_list.append((display_text, relation_uid))
relation_item_id)) relation_editor_list.append(
# relation_editor_list.append((0, value, relation_uid, (value, relation_uid, display_text, None, relation_item_id),
# display_text, None, None)) )
elif len(relation_list) == 0: elif relation_list:
# Add blank line menu_item_list.extend(
(x.getObject().getProperty(catalog_index), x.uid)
for x in relation_list
)
menu_item_list.append(('', ''))
raising_error_value = 'relation_result_ambiguous'
else:
menu_item_list.append(('', '')) menu_item_list.append(('', ''))
# If the length is 0, raise an error if field.get_value('allow_creation'):
if field.get_value('allow_creation') == 1 : getDefaultModuleValue = portal.getDefaultModuleValue
getDefaultModule = field.getDefaultModule
# XXX
for portal_type in portal_type_list: for portal_type in portal_type_list:
try: try:
module = getDefaultModule(portal_type) getDefaultModuleValue(
portal_type, default=None, only_visible=True,
)
except ValueError: except ValueError:
pass pass
else: else:
if portal_type in module.getVisibleAllowedContentTypeList(): menu_item_list.append(
translated_portal_type = translateString(portal_type) (
message = translateString('Add ${portal_type}', translateString(
mapping={'portal_type':translated_portal_type}) 'Add ${portal_type}',
menu_item_list.append((message, mapping={
'%s%s' % (NEW_CONTENT_PREFIX, 'portal_type': translateString(portal_type),
portal_type))) },
REQUEST.set(relation_item_id, menu_item_list) ),
raising_error_needed = 1 '%s%s' % (NEW_CONTENT_PREFIX, portal_type),
)
)
raising_error_value = 'relation_result_empty' raising_error_value = 'relation_result_empty'
else: else:
# If the length is short, raise an error if isinstance(relation_uid, (list, tuple)):
# len(relation_list) < MAX_SELECT: relation_uid = relation_uid[0]
menu_item_list.extend([( display_text = 'Object has been deleted'
x.getObject().getProperty(catalog_index), if isinstance(relation_uid, basestring) and relation_uid.startswith(
x.uid) for x in relation_list]) NEW_CONTENT_PREFIX,
# Add blank line ):
menu_item_list.append(('', '')) display_text = translateString('New ${portal_type}', mapping={
'portal_type': translateString(
relation_uid[len(NEW_CONTENT_PREFIX):],
),
})
elif relation_uid is not None:
related_object = portal_catalog.getObject(relation_uid)
if related_object is not None:
display_text = str(related_object.getProperty(catalog_index))
menu_item_list.append((display_text, relation_uid))
relation_editor_list.append(
(
value,
str(relation_uid),
display_text,
relation_field_id,
relation_item_id,
),
)
REQUEST.set(relation_item_id, menu_item_list) REQUEST.set(relation_item_id, menu_item_list)
raising_error_needed = 1 else:
raising_error_value = 'relation_result_ambiguous' for relation_item_id, relation_uid, value in self._generateItemUidList(
field, key, relation_uid_list, REQUEST=REQUEST,
):
try:
related_object = portal_catalog.getObject(relation_uid)
display_text = str(related_object.getProperty(catalog_index))
except ValueError:
if relation_uid.startswith(NEW_CONTENT_PREFIX):
portal_type = relation_uid[len(NEW_CONTENT_PREFIX):]
display_text = translateString(
'New ${portal_type}',
mapping={
'portal_type': translateString(portal_type),
},
)
else:
display_text = 'Object has been deleted'
if value is None:
value = display_text
relation_editor_list.append(
(value, relation_uid, display_text, None, relation_item_id)
)
##################################### if raising_error_value:
# Validate MultiRelation field
#####################################
if raising_error_needed:
# Raise error
self.raise_error(raising_error_value, field) self.raise_error(raising_error_value, field)
return value_list return value_list
else: return self.editor(
# Can return editor field.id,
base_category = field.get_value('base_category') field.get_value('base_category'),
portal_type_item = field.get_value('portal_type')
relation_setter_id = field.get_value('relation_setter_id')
context_getter_id = field.get_value('context_getter_id')
return self.editor(field.id,
base_category,
portal_type_list, portal_type_list,
portal_type_item, catalog_index, field.get_value('portal_type'),
relation_setter_id, relation_editor_list, catalog_index,
context_getter_id) field.get_value('relation_setter_id'),
relation_editor_list,
field.get_value('context_getter_id'),
)
MultiRelationStringFieldWidgetInstance = MultiRelationStringFieldWidget() MultiRelationStringFieldWidgetInstance = MultiRelationStringFieldWidget()
MultiRelationStringFieldValidatorInstance = MultiRelationStringFieldValidator() MultiRelationStringFieldValidatorInstance = MultiRelationStringFieldValidator()
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment