[Product-Developers] invariant validator for add form has no context?
davidglick at groundwire.org
Thu Jan 19 06:08:08 UTC 2012
On 1/18/12 5:41 PM, zjs2k wrote:
I had the impression that one of the advantages of z3c.form.validators is the
access to context. That's true for SimpleFieldValidator, as demonstrated in
Martin Aspeli's Plone 4 book. So I assumed the same for InvariantsValidator.
But the dexterity add form sets ignoreContext to true. So when the form
trying to get the validator MultiAdapter, the context is set to None (see
z3c.form.field.FieldWidgets.validate). Is this the expected behavior?
What's the best way for full-form validation with access to context? One use
case is using First Name and Last Name fields. I would like to search
catalog to confirm no one has the same first/last name.
Should I override the "save" action handler of dexterity? Or write an event
handler for some form event like ObjectCreatedEvent? No idea about the edit
form event since ObjectModifiedEvent is after object modified.
Any suggestion will be greatly appreciated.
There is no context yet with an add form...it validates the schema before creating the item. But I suppose you just want the context in order to get to the catalog so you can do your search, right? In that case you can get it this way even though the invariant is not passed a 'context' variable:
from zope.site.hooks import getSite
from Products.CMFCore.utils import getToolByName
# later, in your validator...
catalog = getToolByName(getSite(), 'portal_catalog')
This approach depends on the fact that getSite() gives access to the portal as stored in a thread-local variable during traversal. So it will work as long as you're using it in code accessed via the web (i.e. most of the time) but not if you use it from a script run via bin/instance run...unless you take care to set up that thread-local yourself.
davidglick at groundwireconsulting.com
Groundwire Consulting is here. Learn how and why<http://groundwire.org/about/FAQ-gw-consulting> we are deepening our mission.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Product-Developers