Subclassing IS_IN_SET - one piece missing.

29 views
Skip to first unread message

Andrew Buchan

unread,
Dec 1, 2014, 10:04:32 AM12/1/14
to web...@googlegroups.com
Hi,

I wanted to create a validator which creates a dropdown of users in a certain auth group. 
I figured I could shortcut this by inheriting from IS_IN_SET, see class below.
This works fine for SQLFORMS in create mode (drop dow with just what I want to see) and for read-only mode (I see the user name, not the id) , but for a SQLFORM in edit mode which is pointing at an existing record, it doesn't pre-select the entry in the options drop-down. 

Any ideas on how I go about getting this to work, or is there a simpler solution?

If you use this validator in the DAL, you can see the result the admin pages, so you have an easy way to test if you want to play around with it.

Thanks,

class IS_USER_IN_GROUP(IS_IN_SET):
    """A validator that can be used like "requires = IS_USER_IN_GROUP()"
    Provides a drop down of users in that group.
    """
    def __init__(self, group_name):
        keys = []
        labels = []
        staff_groups = db((db.auth_user.id==db.auth_membership.user_id) & (db.auth_group.id==db.auth_membership.group_id))
        rows = staff_groups(db.auth_group.role == group_name).select(db.auth_user.ALL, orderby=db.auth_user.first_name|db.auth_user.last_name)
        for user in rows:
            keys.append(user.id)
            labels.append('%s %s' % (user.first_name, user.last_name))
        IS_IN_SET.__init__(self, keys, labels)
        
    def formatter(self, user_id):
        hits = db(db.auth_user.id == user_id).select()
        if len(hits) == 1:
            user = hits.first()
            return '%s %s' % (user.first_name, user.last_name)
        return ''

Niphlod

unread,
Dec 1, 2014, 3:54:45 PM12/1/14
to web...@googlegroups.com
why reinventing the wheel ? IS_IN_DB takes a Set...

gr = db.auth_group
me = db.auth_membership
us = db.auth_user

theset = db(
   (us.id == me.user_id) &
   (gr.id == me.group_id) &
   (gr.role == 'roletest')
)

....
Field('a_field', requires=IS_IN_DB(theset, 'auth_user.id', '%(first_name)s - %(last_name)s'))

Andrew Buchan

unread,
Dec 2, 2014, 6:26:32 AM12/2/14
to web...@googlegroups.com
That works perfectly, thanks Niphlod!

--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to a topic in the Google Groups "web2py-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/web2py/oTzLZILrg9E/unsubscribe.
To unsubscribe from this group and all its topics, send an email to web2py+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages