开发者

How to modify a z3c form field in updateWidgets?

开发者 https://www.devze.com 2023-03-15 06:05 出处:网络
I am trying to dynamically update a form field based on a variable that is included in a HTTP get variable. Specifically www.site.com/form?id=name. I want to pull the \'id\' field from the url and aut

I am trying to dynamically update a form field based on a variable that is included in a HTTP get variable. Specifically www.site.com/form?id=name. I want to pull the 'id' field from the url and automatically populate the memberID field of the form.

I have access to the get variable using self.request.get('id'). However I haven't been able to figure out how to update the form field. I examined the widget documentation http://packages.python.org/z3c.form/widget.html but none of the suggestions have worked.

class IUpdateEmailFormSchema(interface.Interface):
    # -*- extra stuff goes here -*-
    """
    """
    memberID = schema.TextLine(title=(u'Member id'))

    email = schema.TextLine(title=(u'Email'), description=(u'The email'))

class updateEmailForm(form.Form):
    fields = field.Fields(IUpdateEmailFormSchema)
    label = _(u'Change Email')
    ignoreContext = True


    @button.buttonAndHandler(u'Update')
    def handleUpdate(self,action):
        data, errors = self.extractData()

        if data.has_key('email'):

            portal_membership = getToolByName(self.context, 'portal_membership')
            member = portal_membership.getMemberById(data['memberID'])

    def updateWid开发者_开发问答gets(self):
        print "This is update widget \n\n"
        import pdb; pdb.set_trace()
        print self.request.form['id']    #Does not work as specified in http://packages.python.org/z3c.form/widget.html
        #self.widgets["memberID"].value = self.request.get('id').encode('utf-8')
        form.Form.updateWidgets(self)

updateEmailFormView = wrap_form(updateEmailForm)

*Update: updateWidget wasn't correctly indented.


updateWidgets method is the right place to do it. just you shouuld first call "form.Form.updateWidgets" and then do your changes (even better user super() as shown bellow):

def updateWidgets(self):
    super(updateEmailForm, self).updateWidgets()
    id = self.request.get('id', None)
    if id:
        self.widgets["memberID"].value = id.encode('utf-8')

so basically the error was the order

and if there is no request (which is kinda weird and you are probably doing something worng there) then you can get it via:

from zope.globalrequest import getRequest
request = getRequest()


Your updateWigets() won't be called above because it's not inside the body of the form, it's a top level function.

Also, you should use super() to call the parent version of updateWidgets() - in your case, you probably want to call the parent version first and then change the value or whatever.

You may be better off using a default value adapter instead of updateWidgets() too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号