def handleApply(self, action):
     data, errors = self.extractData()
     title_not_completed = self._validate_column_and_title_completed(data)
     if title_not_completed:
         self._display_message(
             _(
                 u'Please fill in the title(s) of columns(s): ${titles}',
                 mapping={'titles': ', '.join(title_not_completed)},
             ),
             'error',
         )
         return
     if not self._at_least_a_link(data):
         self._display_message(
             _(u'Please select at least one column as a link to object view.'
               ),
             'error',
         )
         return
     if errors:
         self.status = self.formErrorsMessage
         return
     if data:
         self._set_data(data)
         self.status = _(u'Changes saved!')
class DynamicVocabulariesEditForm(controlpanel.RegistryEditForm):

    schema = IDynamicVocabularies
    label = _(u'Dynamic Vocabularies')
    description = _(u'')

    def update(self):
        super(DynamicVocabulariesEditForm, self).update()
        for idx, group in enumerate(self.groups, 1):
            widgets = group.widgets
            field = 'dynamic_vocabulary_{:02d}'.format(idx)
            widgets[field].rows = 10
    def handleAdd(self, action):
        data, errors = self.extractData()
        if errors:
            return

        indexes = self.portal_catalog.indexes()
        schema = self.portal_catalog.schema()

        short_field_name = data['short_field_name'].encode('utf-8')
        index_type = data['index_type']
        idx = self._index_type(short_field_name, index_type)

        if short_field_name not in indexes and short_field_name not in schema:
            self._add_portal_catalog_index(short_field_name, idx)
            self._display_message(
                _(
                    u'Index/metadata ${name} successfully created.',
                    mapping={'name': short_field_name},
                ),
                'info',
            )
            self._redirect('@@add-index-form')
        elif short_field_name in indexes and short_field_name in schema:
            self._display_message(
                _(
                    u'There are a index and a metadata with short name: ${name}',
                    mapping={'name': short_field_name},
                ),
                'error',
            )
            return
        elif short_field_name in indexes:
            self._display_message(
                _(
                    u'There is a index with short name: ${name}',
                    mapping={'name': short_field_name},
                ),
                'error',
            )
            return
        else:
            self._display_message(
                _(
                    u'There is a metadata with short name: ${name}',
                    mapping={'name': short_field_name},
                ),
                'error',
            )
            return
class IAddIndexForm(Interface):

    short_field_name = schema.TextLine(
        title=_(u'Short field name or get function'),
        required=True,
        constraint=validate_short_field_name,
    )

    index_type = schema.Choice(
        title=_(u'Index Type'),
        vocabulary=u'brasil.gov.newfieldcomplement.index_types',
        default=None,
        missing_value=u'',
        required=True,
    )
class AddIndexForm(form.Form):

    label = _(u'Add portal_catalog Index')

    fields = field.Fields(IAddIndexForm)
    ignoreContext = True

    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.portal_catalog = portal.get_tool('portal_catalog')
        self.portal_state = getMultiAdapter(
            (self.context, self.request),
            name=u'plone_portal_state',
        )

    def updateWidgets(self):
        super(AddIndexForm, self).updateWidgets()

    def _index_type(self, short_field_name, index_type):
        if index_type == 'ZCTextIndex':
            idx = INDEX_TYPES[index_type](
                id=short_field_name,
                caller=self.portal_catalog,
                index_factory=OkapiIndex,
                field_name=short_field_name,
                lexicon_id='htmltext_lexicon'
            )
        else:
            idx = INDEX_TYPES[index_type](id=short_field_name)
        return idx

    def _add_portal_catalog_index(self, short_field_name, idx):
            self.portal_catalog.manage_addIndex(
                name=short_field_name,
                type=idx,
                extra=None,
            )
            self.portal_catalog.addColumn(
                name=short_field_name,
            )
            self.portal_catalog.reindexIndex(
                name=[short_field_name, ],
                REQUEST=self.request,
            )

    def _display_message(self, message, type):
        portal.show_message(
            message,
            self.request,
            type=type,
        )

    def _redirect(self, view):
        redirect_url = '{0}/{1}'.format(
            self.portal_state.portal_url(),
            view,
        )
        self.request.response.redirect(redirect_url)

    @button.buttonAndHandler(_(u'Add'))
    def handleAdd(self, action):
        data, errors = self.extractData()
        if errors:
            return

        indexes = self.portal_catalog.indexes()
        schema = self.portal_catalog.schema()

        short_field_name = data['short_field_name'].encode('utf-8')
        index_type = data['index_type']
        idx = self._index_type(short_field_name, index_type)

        if short_field_name not in indexes and short_field_name not in schema:
            self._add_portal_catalog_index(short_field_name, idx)
            self._display_message(
                _(
                    u'Index/metadata ${name} successfully created.',
                    mapping={'name': short_field_name},
                ),
                'info',
            )
            self._redirect('@@add-index-form')
        elif short_field_name in indexes and short_field_name in schema:
            self._display_message(
                _(
                    u'There are a index and a metadata with short name: ${name}',
                    mapping={'name': short_field_name},
                ),
                'error',
            )
            return
        elif short_field_name in indexes:
            self._display_message(
                _(
                    u'There is a index with short name: ${name}',
                    mapping={'name': short_field_name},
                ),
                'error',
            )
            return
        else:
            self._display_message(
                _(
                    u'There is a metadata with short name: ${name}',
                    mapping={'name': short_field_name},
                ),
                'error',
            )
            return

    @button.buttonAndHandler(_(u'Cancel'))
    def handleCancel(self, action):
        self._display_message(
            _('Action canceled.'),
            'info',
        )
        self._redirect('@@overview-controlpanel')
class InvalidShortFieldName(ValidationError):
    __doc__ = _(u'Invalid short field name.')
 def handleCancel(self, action):
     self._display_message(
         _('Action canceled.'),
         'info',
     )
     self._redirect('@@overview-controlpanel')
 def handleCancel(self, action):
     self._display_message(
         _(u'Changes cancelled!'),
         'info',
     )
     self.request.response.redirect(self.context.absolute_url())
class FacetedTabularConfigForm(SchemaForm):
    """ /@@faceted-tabular-config
    """
    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.utils = getMultiAdapter(
            (self.context, self.request),
            name='newfieldcomplement_utils',
        )

    schema = IFacetedTabularConfigForm
    ignoreContext = False

    label = _(u'Faceted Tabular Fields')

    def _display_message(self, message, type):
        api.portal.show_message(
            message,
            self.request,
            type=type,
        )

    def _validate_column_and_title_completed(self, data):
        errors = []
        for i in range(2, 6):
            column = 'column_{:02d}'.format(i)
            title = 'column_{:02d}_title'.format(i)
            if data[column] and not data[title]:
                errors.append('{:02d}'.format(i))
        return errors

    def _at_least_a_link(self, data):
        for i in range(1, 6):
            link = 'column_{:02d}_link'.format(i)
            if data[link]:
                return True
        return False

    def _set_data(self, data={}):
        annotations = IAnnotations(self.context)
        annotations['faceted_tabular_fields'] = PersistentDict(data)

    def getContent(self):
        return self.utils.get_faceted_tabular_fields()

    @button.buttonAndHandler(_(u'Save'))
    def handleApply(self, action):
        data, errors = self.extractData()
        title_not_completed = self._validate_column_and_title_completed(data)
        if title_not_completed:
            self._display_message(
                _(
                    u'Please fill in the title(s) of columns(s): ${titles}',
                    mapping={'titles': ', '.join(title_not_completed)},
                ),
                'error',
            )
            return
        if not self._at_least_a_link(data):
            self._display_message(
                _(u'Please select at least one column as a link to object view.'
                  ),
                'error',
            )
            return
        if errors:
            self.status = self.formErrorsMessage
            return
        if data:
            self._set_data(data)
            self.status = _(u'Changes saved!')

    @button.buttonAndHandler(_(u'Cancel'))
    def handleCancel(self, action):
        self._display_message(
            _(u'Changes cancelled!'),
            'info',
        )
        self.request.response.redirect(self.context.absolute_url())
class IFacetedTabularConfigForm(Schema):
    """ Define form fields """

    fieldset('table_fieldset', label=_(u'Table'), fields=[
        'table_caption',
    ])
    table_caption = schema.TextLine(
        title=_(u'Table Caption'),
        required=False,
    )

    fieldset('column_01_fieldset',
             label=_(u'Column 01'),
             fields=[
                 'column_01',
                 'column_01_vocab',
                 'column_01_title',
                 'column_01_link',
             ])
    column_01 = schema.Choice(
        title=_(u'Column 01'),
        required=True,
        default=u'Title',
        vocabulary='{}.available_fields'.format(VOCABULARIES_PREFIX))
    column_01_vocab = schema.Choice(
        title=_(u'Column 01 Vocabulary'),
        required=False,
        vocabulary='eea.faceted.vocabularies.PortalVocabularies',
    )
    column_01_title = schema.TextLine(
        title=_(u'Column 01 Title'),
        required=True,
        default=u'Título',
    )
    column_01_link = schema.Bool(
        title=_(u'Column 01 Link'),
        required=False,
        default=True,
    )

    fieldset('column_02_fieldset',
             label=_(u'Column 02'),
             fields=[
                 'column_02',
                 'column_02_vocab',
                 'column_02_title',
                 'column_02_link',
             ])
    column_02 = schema.Choice(
        title=_(u'Column 02'),
        required=False,
        vocabulary='{}.available_fields'.format(VOCABULARIES_PREFIX))
    column_02_vocab = schema.Choice(
        title=_(u'Column 02 Vocabulary'),
        required=False,
        vocabulary='eea.faceted.vocabularies.PortalVocabularies',
    )
    column_02_title = schema.TextLine(
        title=_(u'Column 02 Title'),
        description=_(u'title_description'),
        required=False,
    )
    column_02_link = schema.Bool(
        title=_(u'Column 02 Link'),
        required=False,
        default=False,
    )

    fieldset('column_03_fieldset',
             label=_(u'Column 03'),
             fields=[
                 'column_03',
                 'column_03_vocab',
                 'column_03_title',
                 'column_03_link',
             ])
    column_03 = schema.Choice(
        title=_(u'Column 03'),
        required=False,
        vocabulary='{}.available_fields'.format(VOCABULARIES_PREFIX))
    column_03_vocab = schema.Choice(
        title=_(u'Column 03 Vocabulary'),
        required=False,
        vocabulary='eea.faceted.vocabularies.PortalVocabularies',
    )
    column_03_title = schema.TextLine(
        title=_(u'Column 03 Title'),
        description=_(u'title_description'),
        required=False,
    )
    column_03_link = schema.Bool(
        title=_(u'Column 03 Link'),
        required=False,
        default=False,
    )

    fieldset('column_04_fieldset',
             label=_(u'Column 04'),
             fields=[
                 'column_04',
                 'column_04_vocab',
                 'column_04_title',
                 'column_04_link',
             ])
    column_04 = schema.Choice(
        title=_(u'Column 04'),
        required=False,
        vocabulary='{}.available_fields'.format(VOCABULARIES_PREFIX))
    column_04_vocab = schema.Choice(
        title=_(u'Column 04 Vocabulary'),
        required=False,
        vocabulary='eea.faceted.vocabularies.PortalVocabularies',
    )
    column_04_title = schema.TextLine(
        title=_(u'Column 04 Title'),
        description=_(u'title_description'),
        required=False,
    )
    column_04_link = schema.Bool(
        title=_(u'Column 04 Link'),
        required=False,
        default=False,
    )

    fieldset('column_05_fieldset',
             label=_(u'Column 05'),
             fields=[
                 'column_05',
                 'column_05_vocab',
                 'column_05_title',
                 'column_05_link',
             ])
    column_05 = schema.Choice(
        title=_(u'Column 05'),
        required=False,
        vocabulary='{}.available_fields'.format(VOCABULARIES_PREFIX))
    column_05_vocab = schema.Choice(
        title=_(u'Column 05 Vocabulary'),
        required=False,
        vocabulary='eea.faceted.vocabularies.PortalVocabularies',
    )
    column_05_title = schema.TextLine(
        title=_(u'Column 05 Title'),
        description=_(u'title_description'),
        required=False,
    )
    column_05_link = schema.Bool(
        title=_(u'Column 05 Link'),
        required=False,
        default=False,
    )
class IDynamicVocabularies(Interface):

    fieldset('vocabulary_01_fieldset',
             label=_(u'Vocabulary 01'),
             fields=[
                 'dynamic_vocabulary_01',
             ])
    dynamic_vocabulary_01 = schema.List(
        title=_(u'dynamic_vocabulary_01'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')),
    )
    fieldset('vocabulary_02_fieldset',
             label=_(u'Vocabulary 02'),
             fields=[
                 'dynamic_vocabulary_02',
             ])
    dynamic_vocabulary_02 = schema.List(
        title=_(u'dynamic_vocabulary_02'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_03_fieldset',
             label=_(u'Vocabulary 03'),
             fields=[
                 'dynamic_vocabulary_03',
             ])
    dynamic_vocabulary_03 = schema.List(
        title=_(u'dynamic_vocabulary_03'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_04_fieldset',
             label=_(u'Vocabulary 04'),
             fields=[
                 'dynamic_vocabulary_04',
             ])
    dynamic_vocabulary_04 = schema.List(
        title=_(u'dynamic_vocabulary_04'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_05_fieldset',
             label=_(u'Vocabulary 05'),
             fields=[
                 'dynamic_vocabulary_05',
             ])
    dynamic_vocabulary_05 = schema.List(
        title=_(u'dynamic_vocabulary_05'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_06_fieldset',
             label=_(u'Vocabulary 06'),
             fields=[
                 'dynamic_vocabulary_06',
             ])
    dynamic_vocabulary_06 = schema.List(
        title=_(u'dynamic_vocabulary_06'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_07_fieldset',
             label=_(u'Vocabulary 07'),
             fields=[
                 'dynamic_vocabulary_07',
             ])
    dynamic_vocabulary_07 = schema.List(
        title=_(u'dynamic_vocabulary_07'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_08_fieldset',
             label=_(u'Vocabulary 08'),
             fields=[
                 'dynamic_vocabulary_08',
             ])
    dynamic_vocabulary_08 = schema.List(
        title=_(u'dynamic_vocabulary_08'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_09_fieldset',
             label=_(u'Vocabulary 09'),
             fields=[
                 'dynamic_vocabulary_09',
             ])
    dynamic_vocabulary_09 = schema.List(
        title=_(u'dynamic_vocabulary_09'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_10_fieldset',
             label=_(u'Vocabulary 10'),
             fields=[
                 'dynamic_vocabulary_10',
             ])
    dynamic_vocabulary_10 = schema.List(
        title=_(u'dynamic_vocabulary_10'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_11_fieldset',
             label=_(u'Vocabulary 11'),
             fields=[
                 'dynamic_vocabulary_11',
             ])
    dynamic_vocabulary_11 = schema.List(
        title=_(u'dynamic_vocabulary_11'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_12_fieldset',
             label=_(u'Vocabulary 12'),
             fields=[
                 'dynamic_vocabulary_12',
             ])
    dynamic_vocabulary_12 = schema.List(
        title=_(u'dynamic_vocabulary_12'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_13_fieldset',
             label=_(u'Vocabulary 13'),
             fields=[
                 'dynamic_vocabulary_13',
             ])
    dynamic_vocabulary_13 = schema.List(
        title=_(u'dynamic_vocabulary_13'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_14_fieldset',
             label=_(u'Vocabulary 14'),
             fields=[
                 'dynamic_vocabulary_14',
             ])
    dynamic_vocabulary_14 = schema.List(
        title=_(u'dynamic_vocabulary_14'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))
    fieldset('vocabulary_15_fieldset',
             label=_(u'Vocabulary 15'),
             fields=[
                 'dynamic_vocabulary_15',
             ])
    dynamic_vocabulary_15 = schema.List(
        title=_(u'dynamic_vocabulary_15'),
        description=_('dynamic_vocabulary_desc'),
        required=False,
        unique=True,
        value_type=schema.TextLine(title=_(u'Value')))