import grok from zope.component import getUtility, getMultiAdapter from zope.component.interfaces import Invalid from zope.exceptions import DuplicationError from waeup.basecontainer import BaseContainer from waeup.interfaces import IFacultyContainer from waeup.viewlets import MainArea, LeftSidebar, Index, Add, FormWrapMixin from interfaces import IFaculty from faculty import Faculty from zope.schema import ValidationError class FacultyContainer(grok.Container): grok.implements(IFacultyContainer) grok.require('waeup.manageUniversity') name = u'Faculties' def getId(self, faculty): """We need a unified id for each faculty, which acts as key. """ id = faculty.name id = id.replace(' ', '') return id.lower() def addFaculty(self, faculty): if not IFaculty.providedBy(faculty): raise TypeError('FacultyContainers contain only IFaculty instances') id = self.getId(faculty) self[id] = faculty # We register FacultyContainer as a utility. This way we can # call getUtility(IFacultyContainer) from anywhere in the code and # get an instance of FacultyContainer. grok.global_utility(FacultyContainer, provides=IFacultyContainer) class Content(grok.Viewlet): grok.viewletmanager(MainArea) grok.context(IFacultyContainer) grok.view(Index) def getFaculties(self): """Convinience method to create a sorted list of faculties. It provides a list of dicts with entries for all data needed by usual list templates. """ result = [] for key, val in self.context.items(): result.append(dict(id=key, name=val.name)) return result class AddFacultyForm(grok.AddForm): grok.context(IFacultyContainer) form_fields = grok.AutoFields(IFaculty) label = 'Add a faculty' @grok.action('Add faculty') def addFaculty(self, **data): faculty = getUtility(IFaculty) self.applyData(faculty, **data) try: self.context.addFaculty(faculty) except DuplicationError: self.status = Invalid('The name chosen already exists ' 'in the database') return self.redirect(self.url(self.context)) class AddFaculty(FormWrapMixin, grok.Viewlet): """A viewlet that wraps the `AddFacultyForm`. """ grok.viewletmanager(MainArea) grok.context(IFacultyContainer) grok.view(Add) grok.require('waeup.manageUniversity') formview_name = 'addfacultyform' # The name of the formview we # want to be rendered in this # viewlet. class AddFacultyLink(grok.Viewlet): """A link in the left sidebar displaying 'Add faculty' """ grok.viewletmanager(LeftSidebar) grok.context(IFacultyContainer) grok.view(Index) grok.order(5) # This is so cool! This link is only displayed, when the user is # allowed to use it! grok.require('waeup.manageUniversity') def render(self): return u'
'