'Get a SELECT of person entities for realm assignment'

def _entity_select(self):

    T = current.T
    s3db = current.s3db
    auth = current.auth
    system_roles = auth.get_system_roles()
    has_role = auth.s3_has_role
    is_admin = has_role(system_roles.ADMIN)
    if is_admin:
        all_entities = OPTION(T('All    Entities'), _value=0)
    else:
        all_entities = ''
    select = SELECT(OPTGROUP(OPTION(T('Default    Realm'), _value='__NONE__', _selected='selected'), all_entities, _label=T('Multiple')), _name='pe_id')
    table = s3db.table('pr_pentity')
    if (table is None):
        return select
    instance_type_nice = table.instance_type.represent
    types = current.deployment_settings.get_auth_realm_entity_types()
    pe_ids = []
    if (not is_admin):
        if has_role(system_roles.ORG_GROUP_ADMIN):
            realms = auth.user.realms[system_roles.ORG_GROUP_ADMIN]
            if realms:
                pe_ids.extend(realms)
        if has_role(system_roles.ORG_ADMIN):
            realms = auth.user.realms[system_roles.ORG_ADMIN]
            if realms:
                pe_ids.extend(realms)
    entities = s3db.pr_get_entities(pe_ids=pe_ids, types=types, group=True)
    for instance_type in types:
        if (instance_type in entities):
            optgroup = OPTGROUP(_label=instance_type_nice(instance_type))
            items = [(n, i) for (i, n) in entities[instance_type].items()]
            if (not items):
                continue
            items.sort()
            for (name, pe_id) in items:
                optgroup.append(OPTION(name, _value=pe_id))
            select.append(optgroup)
    return select
