I'm trying to control the default for a schema.Bool
, but I want it based on a condition. I'm have tried two ways and I can't figure it out.
first option:
def isCreatedInHomePage():
print "is this pic being created at the site base? if it is, then default true. if not default false"
return False
class IPics(form.Schema):
form.widget(displayOnHomepage=SingleCheckBoxFieldWidget)
displayOnHomepage = schema.Bool(
title=_(u"Display On Site Homepage"),
#default=True,
defaultFactory=isCreatedInHomePage,
required=False,
)
while the defaultFactory does get called and will correctly set true or false (based on what i tell it), i could not figure out how to check what the parent page from where the form was called. any thoughts on what i could use there?
the second option i try to control it in the AddForm itself:
class AddForm(dexterity.AddForm):
grok.name('pics')
grok.context(IPics)
def updateWidgets(self):
print "in update widgets "
super(AddForm, self).updateWidgets()
# this will give an empty list if False (or not selected) and will
# return "['selected']" if True (check box is checked)
print 'self.widgets["displayOnHomepage"].value', self.widgets["displayOnHomepage"].value
self.widgets["displayOnHomepage"].value = ['selected']
# this will return to whatever is set in the above line.
print 'self.widgets["displayOnHomepage"].value', self.widgets["displayOnHomepage"].value
def createAndAdd(self, data):
...
...
...
Any help would be appreciated :)
working with the answer from @Mathias i got other ideas and solved the problem for this problem. i feel this is a workaround and that a better solution exists. i put it into the try to avoid possible attribute error.
@form.default_value(field=IPics['displayOnHomepage'])
def isCreatedInHomePage(data):
try:
print data.context.getParentNode().portal_type
if data.context.getParentNode().portal_type == 'Plone Site':
return True
else:
return False
except:
pass