def createAndAdd(self, data): # Filter away data values that does not come from the 'core' schema. # Additional values can come from AutoExtensibleForm/FormExtender # schemas,and the portlet Assignment creation will fail if the # portlet AddForm create() method is using "Assignment(**data)" # instead of explicit parameters. # Extender values are set by form.applyChanges below, via the usual # z3cform adapter lookups. schema_keys = field.Fields(self.schema).keys() unextended_data = { key: data[key] for key in schema_keys if key in data } obj = self.create(unextended_data) # Acquisition wrap temporarily to satisfy things like vocabularies # depending on tools container = aq_inner(self.context) if IAcquirer.providedBy(obj): obj = obj.__of__(container) form.applyChanges(self, obj, data) obj = aq_base(obj) zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj)) self.add(obj) return obj
def handleSave(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return typeName = self.tileType.__name__ # Traverse to a new tile in the context, with no data tile = self.context.restrictedTraverse('@@%s/%s' % (typeName, self.tileId,)) dataManager = ITileDataManager(tile) content = dataManager.get() applyChanges(self, content, data) dataManager.set(content) # Look up the URL - we need to do this after we've set the data to # correctly account for transient tiles contextURL = absoluteURL(tile.context, self.request) notify(ObjectModifiedEvent(tile)) # Get the tile URL, possibly with encoded data IStatusMessage(self.request).addStatusMessage(_(u"Tile saved",), type=u'info') self.request.response.redirect(contextURL)
def populateContextFromDraft(self): """Will populate the temporary content object from values contained within the draft """ data, errors = self.extractData() if errors: return None fti = zope.component.getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) content = zope.component.createObject(fti.factory) if hasattr(content, '_setPortalTypeName'): content._setPortalTypeName(fti.getId()) # Acquisition wrap temporarily to satisfy things like vocabularies # depending on tools if IAcquirer.providedBy(content): content = content.__of__(container) applyChanges(self, content, data) for group in self.groups: applyChanges(group, content, data) return aq_base(content)
def create(self, data): fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) content = createObject(fti.factory) # Note: The factory may have done this already, but we want to be sure # that the created type has the right portal type. It is possible # to re-define a type through the web that uses the factory from an # existing type, but wants a unique portal_type! if hasattr(content, '_setPortalTypeName'): content._setPortalTypeName(fti.getId()) # Acquisition wrap temporarily to satisfy things like vocabularies # depending on tools if IAcquirer.providedBy(content): content = content.__of__(container) form.applyChanges(self, content, data) for group in self.groups: form.applyChanges(group, content, data) return aq_base(content)
def create(self, data): fd = IntFieldDescription(data['title'], str(data['name']), data['required']) form.applyChanges(self, fd, data) self._fd = fd return fd
def create(self, data): fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) # give data to factory, so it can make checks content = createObject(fti.factory, **data) # Note: The factory may have done this already, but we want to be sure # that the created type has the right portal type. It is possible # to re-define a type through the web that uses the factory from an # existing type, but wants a unique portal_type! if getattr(content, '_setPortalTypeName'): content._setPortalTypeName(fti.getId()) # Acquisition wrap temporarily to satisfy things like vocabularies # depending on tools if IAcquirer.providedBy(content): content = content.__of__(container) form.applyChanges(self, content, data) for group in self.groups: form.applyChanges(group, content, data) return aq_base(content)
def createAndAdd(self, data): # Filter away data values that does not come from the 'core' schema. # Additional values can come from AutoExtensibleForm/FormExtender # schemas,and the portlet Assignment creation will fail if the # portlet AddForm create() method is using "Assignment(**data)" # instead of explicit parameters. # Extender values are set by form.applyChanges below, via the usual # z3cform adapter lookups. schema_keys = field.Fields(self.schema).keys() unextended_data = {key: data[key] for key in schema_keys if data.has_key(key)} obj = self.create(unextended_data) # Acquisition wrap temporarily to satisfy things like vocabularies # depending on tools container = aq_inner(self.context) if IAcquirer.providedBy(obj): obj = obj.__of__(container) form.applyChanges(self, obj, data) obj = aq_base(obj) zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj)) self.add(obj) return obj
def handleAdd(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return typeName = self.tileType.__name__ # Traverse to a new tile in the context, with no data tile = self.context.restrictedTraverse( '@@%s/%s' % (typeName, self.tileId,)) dataManager = ITileDataManager(tile) content = {} applyChanges(self, content, data) dataManager.set(content) # Look up the URL - we need to do this after we've set the data to # correctly account for transient tiles tileURL = absoluteURL(tile, self.request) contextURL = absoluteURL(tile.context, self.request) notify(ObjectCreatedEvent(tile)) notify(ObjectAddedEvent(tile, self.context, self.tileId)) IStatusMessage(self.request).addStatusMessage( _(u"Tile created at ${url}", mapping={'url': tileURL}), type=u'info', ) self.request.response.redirect(contextURL)
def create(self, data): LOG.info('create: '+str(self.portal_type)) fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) options = {} options['portal_type'] = self.portal_type options['sql_id'] = data.get('ISQLContent.sql_id') content = createObject(fti.factory, **options) # Note: The factory may have done this already, but we want to be sure # that the created type has the right portal type. It is possible # to re-define a type through the web that uses the factory from an # existing type, but wants a unique portal_type! if hasattr(content, '_setPortalTypeName'): content._setPortalTypeName(fti.getId()) # Acquisition wrap temporarily to satisfy things like vocabularies # depending on tools if IAcquirer.providedBy(content): content = content.__of__(container) # Don't set empty data in SQL DB: for k,v in data.items(): if not v: del data[k] form.applyChanges(self, content, data) for group in self.groups: form.applyChanges(group, content, data) return aq_base(content)
def handleAdd(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return typeName = self.tileType.__name__ generator = getUtility(IUUIDGenerator) tileId = generator() # Traverse to a new tile in the context, with no data tile = self.context.restrictedTraverse( '@@%s/%s' % (typeName, tileId,)) dataManager = ITileDataManager(tile) new_data = {} form.applyChanges(self, new_data, data) dataManager.set(new_data) # Look up the URL - we need to do this after we've set the data to # correctly account for transient tiles tileURL = absoluteURL(tile, self.request) notify(ObjectCreatedEvent(tile)) notify(ObjectAddedEvent(tile, self.context, tileId)) logger.debug(u"Tile created at {0}".format(tileURL)) try: url = self.nextURL(tile) except NotImplementedError: url = tileURL self.request.response.redirect(url)
def handle_assign(self, action): data, errors = self.extractData() if not errors: issue = self.getContent() info = getAdapter(issue, IWorkflowInfo, name="project.issue") form.applyChanges(self, issue, data) info.fireTransition("responsibility_assigned") self.request.response.redirect(".")
def create(self, data): """ Create """ name = INameChooser( self.context).chooseName(data.get('title', ''), None) ob = PortalType(id=name) form.applyChanges(self, ob, data) return ob
def create(self, data): """ Create """ name = INameChooser(self.context).chooseName(data.get('title', ''), None) ob = PortalType(id=name) form.applyChanges(self, ob, data) return ob
def save(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return content = self.getContent() form.applyChanges(self, content, data)
def create(self, data): """ Create """ valid_input = input_is_valid(self, data) if not valid_input: return ob = PortalType(id=data.get('title', 'ADDTitle')) form.applyChanges(self, ob, data) return ob
def create(self, data): obj = self.Type() container = aq_inner(self.context) if IAcquirer.providedBy(obj): obj = obj.__of__(container) applyChanges(self, obj, data) obj = aq_base(obj) return obj
def autosave(event): context = getattr(event, 'object', None) request = getattr(context, 'REQUEST', getRequest()) if not request.URL.endswith('/@@z3cform_validate_field'): return draft = getCurrentDraft(request) if draft is None: return view = getattr(request, 'PUBLISHED', None) form = getattr(view, 'context', None) if hasattr(aq_base(form), 'form_instance'): form = form.form_instance if IAddForm.providedBy(form): target = getattr(draft, '_draftAddFormTarget', None) if not target: return target = target.__of__(context) else: target = context fti = queryUtility(IDexterityFTI, name=target.portal_type) if IDraftable.__identifier__ not in fti.behaviors: return if not hasattr(form, "extractData"): return data, errors = form.extractData() if not errors: content = DraftProxy(draft, target) # Drop known non-draftable values map(data.pop, [key for key in AUTOSAVE_BLACKLIST if key in data]) # Values are applied within savepoint to allow revert of any # unexpected side-effects from setting field values sp = transaction.savepoint(optimistic=True) try: applyChanges(form, content, data) for group in getattr(form, 'groups', []): applyChanges(group, content, data) except Exception: # If shortname was not blacklisted, it could fail because the # behavior trying to rename object on add form. pass values = dict(draft.__dict__) sp.rollback() for key, value in values.items(): setattr(draft, key, value) # Disable Plone 5 implicit CSRF to update draft if HAS_PLONE_PROTECT: alsoProvides(request, IDisableCSRFProtection)
def create(self, data): # create object content = Graph() # apply form.rdftype content.add((content.identifier, RDF['type'], self.rdftype)) # apply form data form.applyChanges(self, content, data) for group in self.groups: form.applyChanges(group, content, data) return content
def applyChanges(self, data): '''See interfaces.IEditForm''' changed = False content = self.getContent() form.applyChanges(self, content, data) for group in self.groups: groupChanged = form.applyChanges(group, content, data) changed = changed or groupChanged if changed: zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent(content)) return changed
def create(self, data): """Overrides to set IClassificationFolder fields""" content = super(ReplyForm, self).create(data) # we have to apply changes again because the base method wraps acquisition around the content # the classification fields are then considered as unchanged # we do it again without this wrap and only on classification data filtered_data = { key: value for key, value in data.items() if key.startswith('IClassificationFolder') } applyChanges(self, content, filtered_data) return content
def create(self, data): # Dexterity base AddForm bypasses self.applyData and uses form.applyData directly, # we'll have to override it to find a place to apply our algo_group data' newob = super(SpeciesTraitsAdd, self).create(data) # apply values to algo dict manually to make sure we don't write data on read new_params = {} for group in self.param_groups: if group.toolkit == data['algorithm']: content = group.getContent() applyChanges(group, content, data) new_params[group.toolkit] = content newob.parameters = new_params return newob
def create(self, data): """ Since content rules expects paths, we're transforming UUID, which is what the z3c form widget uses, to paths. """ a = self.Type() if data.get('target_folder', None): site = getSite() site_path = '/'.join(site.getPhysicalPath()) path = uuidToPhysicalPath(data['target_folder']) if path: data['target_folder'] = path[len(site_path):] form.applyChanges(self, a, data) return a
def createAndAdd(self, data): obj = self.create(data) # Acquisition wrap temporarily to satisfy things like vocabularies # depending on tools container = aq_inner(self.context) if IAcquirer.providedBy(obj): obj = obj.__of__(container) form.applyChanges(self, obj, data) obj = aq_base(obj) zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj)) self.add(obj) return obj
def create(self, data): # This is mostly a direct copy of # :py:meth:`plone.dexterity.browser.add.DefaultAddForm.create`, # extended to apply the right interface. fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) content = createObject(fti.factory) alsoProvides(content, self.schema) if hasattr(content, '_setPortalTypeName'): content._setPortalTypeName(fti.getId()) if IAcquirer.providedBy(content): content = content.__of__(container) applyChanges(self, content, data) for group in self.groups: applyChanges(group, content, data) return aq_base(content)
def handleApply(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return if data['selected_group']: self.group_obj = self.hlite[data['selected_group']] content = self.getContent() del data['selected_group'] changes = form.applyChanges(self, content, data) if self.group_obj.id not in self.highlights: self.highlights[self.group_obj.id] = content interface.alsoProvides(self.context, IHighlighted) if changes: content.author = getActiveUser() self.context.reindexObject(idxs=['object_provides', 'hlite_groups']) self.status = self.successMessage self.refreshActions = True self.updateWidgets() else: self.status = self.noChangesMessage else: self.status = _(u'Please select a group.')
def applyChangesToSchedule(self, schedule, data): changes = form.applyChanges(self, schedule, data) # ``changes`` is a dictionary; if empty, there were no changes if changes: # Construct change-descriptions for the object-modified event descriptions = [] for interface, names in changes.items(): descriptions.append( zope.lifecycleevent.Attributes(interface, *names)) # Send out a detailed object-modified event zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent(schedule, *descriptions)) schedule_changed = bool(changes) timetable = schedule.timetable for day in timetable.periods.templates.values(): for period in day.values(): key = self.getPeriodKey(day, period) selected = bool(self.request.get(key)) scheduled = schedule.hasPeriod(period) if selected and not scheduled: schedule.addPeriod(period) schedule_changed = True elif not selected and scheduled: schedule.removePeriod(period) schedule_changed = True return schedule_changed
def applyChanges(self, data): '''See interfaces.IEditForm''' content = self.getContent() changed = form.applyChanges(self, content, data) for group in self.groups: groupChanged = group.applyChanges(data) for interface, names in groupChanged.items(): changed[interface] = changed.get(interface, []) + names return changed
def applyChanges(self): data, errors = self.extractData() content = self.getContent() if errors: self.status = self.formErrorsMessage return changes = form.applyChanges(self, content, data) # ``changes`` is a dictionary; if empty, there were no changes if changes: self.setConfiguration(content) return changes
def create(self, data): fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) content = createObject(fti.factory) if hasattr(content, '_setPortalTypeName'): content._setPortalTypeName(fti.getId()) if IAcquirer.providedBy(content): content = content.__of__(container) for behavior in get_default_variant_aspects(self.context): name = dotted_name(behavior) enable_behaviors(content, (name, ), (behavior, ), reindex=False) form.applyChanges(self, content, data) for group in self.groups: form.applyChanges(group, content, data) return aq_base(content)
def applyChanges(self, data): content = self.getContent() changes = form.applyChanges(self, content, data) if changes: product = self.context.product for changed_field in changes[IProduct]: new_value = data[changed_field] setattr(product, changed_field, new_value) session = getSession() session.add(product) session.commit() return bool(changes)
def handleApply(self, action): data, errors = self.widgets.extract() if errors: self.status = self.formErrorsMessage return content = self.getContent() changed = form.applyChanges(self, content, data) if changed: zope.event.notify(zope.lifecycleevent.ObjectModifiedEvent(content)) self.status = self.successMessage else: self.status = self.noChangesMessage
def applyChanges(self, data): changed = super(ParamGroupMixin, self).applyChanges(data) # apply algo params: new_params = {} for group in self.param_groups: if self.is_toolkit_selected(group.toolkit, data[self.func_select_field]): content = group.getContent() param_changed = applyChanges(group, content, data) new_params[group.toolkit] = content self.context.parameters = new_params return changed
def create(self, data): fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) content = createObject(fti.factory) if hasattr(content, '_setPortalTypeName'): content._setPortalTypeName(fti.getId()) if IAcquirer.providedBy(content): content = content.__of__(container) for behavior in get_default_variant_aspects(self.context): name = dotted_name(behavior) enable_behaviors(content, (name,), (behavior,), reindex=False) form.applyChanges(self, content, data) for group in self.groups: form.applyChanges(group, content, data) return aq_base(content)
def handleApply(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return uid = data.get('uid') if uid: # this is an existing registration attendee = self.getattendee(uid) if attendee is None: # we should not get here... tampering alert raise ValueError, "Tampering with the form!" for group in self.groups: applyChanges(group, attendee, data) else: # Create the attendee object in the attendees folder attendees = self.context.attendees del data['uid'] # need to remove uid before adding attendee = createContentInContainer( attendees, 'netsight.conferenceregistration.attendee', checkConstraints=False, **data) # Add attendee to shopping cart self.addToCart(attendee) # IStatusMessage(self.request).addStatusMessage( # _(u"Thank you for your registration."), # "info" # ) portal_url = getToolByName( self.context, 'portal_url').getPortalObject().absolute_url() return self.request.response.redirect( '%s/registrations/@@getpaid-cart' % portal_url)
def handleApply(self, action): data, errors = self.widgets.extract() if errors: self.status = self.formErrorsMessage return content = self.getContent() changed = form.applyChanges(self, content, data) if changed: zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent(content)) self.status = self.successMessage else: self.status = self.noChangesMessage
def handleApply(self, action): data, errors = self.widgets.extract() if errors: # XXX: we don't handle errors for now return content = self.getContent() changed = form.applyChanges(self, content, data) self.changed = bool(changed) if self.changed and self.relationship is not None: self.relationship.state.set( self.request.util.today, meaning=self.data['relationship'].active, code=self.data['relationship'].code)
def handleApply(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return uid = data.get('uid') if uid: # this is an existing registration attendee = self.getattendee(uid) if attendee is None: # we should not get here... tampering alert raise ValueError, "Tampering with the form!" for group in self.groups: applyChanges(group, attendee, data) else: # Create the attendee object in the attendees folder attendees = self.context.attendees del data['uid'] # need to remove uid before adding attendee = createContentInContainer(attendees, 'netsight.conferenceregistration.attendee', checkConstraints=False, **data) # Add attendee to shopping cart self.addToCart(attendee) # IStatusMessage(self.request).addStatusMessage( # _(u"Thank you for your registration."), # "info" # ) portal_url = getToolByName( self.context, 'portal_url').getPortalObject().absolute_url() return self.request.response.redirect('%s/registrations/@@getpaid-cart' % portal_url)
def applyChanges(self, data): '''See interfaces.IEditForm''' descriptions = [] content = self.getContent() changed = form.applyChanges(self, content, data) for group in self.groups: groupChanged = group.applyChanges(data) for interface, names in groupChanged.items(): changed[interface] = changed.get(interface, []) + names if changed: for interface, names in changed.items(): descriptions.append( zope.lifecycleevent.Attributes(interface, *names)) # Send out a detailed object-modified event zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent( content, *descriptions)) return changed
def applyChanges(self, data): '''See interfaces.IEditForm''' descriptions = [] content = self.getContent() changed = form.applyChanges(self, content, data) for group in self.groups: groupChanged = group.applyChanges(data) for interface, names in groupChanged.items(): changed[interface] = changed.get(interface, []) + names if changed: for interface, names in changed.items(): descriptions.append( zope.lifecycleevent.Attributes(interface, *names)) # Send out a detailed object-modified event zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent(content, *descriptions)) return changed
def handleApply(self, action): data, errors = self.extractData() if not data.get(self.channel_selector): self.unsubscribe() return if errors: self.status = self.formErrorsMessage return content = self.getContent() del data[self.channel_selector] changes = form.applyChanges(self, content, data) if changes: zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent(content)) self.status = self.successMessage else: self.status = self.noChangesMessage
class AsyncEditForm(edit.DefaultEditForm): success_message = _(u"Changes will be saved") @button.buttonAndHandler(_(u"Save"), name="save") def handleApply(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return try: notify(events.AsyncBeforeEdit(self.context)) except Unauthorized: IStatusMessage(self.request).add( _(u"You are not authorized to edit this element.")) return except interfaces.AsyncValidationFailed, e: IStatusMessage(self.request).add(unicode(e)) return content = self.getContent() changes = form.applyChanges(self, content, data) new_changes = list() for interface, names in changes.items(): new_changes.append((interface.__identifier__, names)) uuid = IUUID(content, 0) task_id = utils.register_task(action=constants.EDIT, changes=new_changes, context=uuid) tasks.finish_edit.apply_async([content, task_id], dict()) IStatusMessage(self.request).addStatusMessage(self.success_message, "info") url = content.absolute_url() portal_type = getattr(aq_base(content), "portal_type", None) registry = zope.component.getUtility(IRegistry) use_view_action = registry.get( "plone.types_use_view_action_in_listings", []) if portal_type in use_view_action: url = url + '/view' return self.request.response.redirect(url)
def createAndAdd(self, data): context = self.getContent() applyChanges(self, context, data) self.status = self.successMessage return context
def applyChanges(self, data): content = self.getContent() applyChanges(self, content, data)
def create(self, data): c = RoleCondition() form.applyChanges(self, c, data) return c
def create(self, data): rule = Rule() applyChanges(self, rule, data) return rule
def create(self, data): schoolyear = SchoolYear(data['title'], data['first'], data['last']) form.applyChanges(self, schoolyear, data) self._schoolyear = schoolyear return schoolyear
def create(self, data): c = PortalTypeCondition() form.applyChanges(self, c, data) return c
def create(self, data): c = WorkflowStateCondition() form.applyChanges(self, c, data) return c