                  );
              } else {
 -                $st = $this->execute('SELECT DISTINCT `eid` FROM '. self::$prefix .'entity' . $excludeSQL);
-+                if ($fieldNameSQL) {
-+                    $fieldNameSQL = 'WHERE '. $fieldNameSQL;
++                if ($fieldName) {
++                    $fieldNameSQL = ' WHERE '. $fieldNameSQL;
 +                }
 +                $st = $this->execute(
 +                    'SELECT DISTINCT '. self::$prefix .'entity.eid 

+
+        $orderBySQL = ';';
+        $fieldNameSQL = '';
+        $joinSQL = '';
+        // If the fieldName is set, also add the fieldName SQL, Join SQL and orderBy SQL
+        if ($fieldName) {
+            $fieldNameSQL = self::$prefix .'metadata.key = \''. $fieldName .'\' AND '. self::$prefix .'metadata.value not like \'\'';
+            $joinSQL = 'LEFT JOIN '. self::$prefix .'metadata ON '. self::$prefix .'entity.eid = '. self::$prefix .'metadata.eid';
+            $orderBySQL = 'ORDER BY '. self::$prefix .'metadata.value ASC;';
+        }
+
+        $excludeSQL = '';
         if (!is_null($state_exclude)) {
-            $excludeSQL = ' AND `eid` NOT IN (SELECT DISTINCT `eid` FROM janus__entity WHERE `state` IN (\'' . $state_exclude . '\'));';
+            $excludeSQL = ' AND '. self::$prefix .'entity.eid NOT IN (SELECT DISTINCT `eid` FROM janus__entity WHERE `state` IN (\'' . $state_exclude . '\'))';
         }
 
         $guard = new sspmod_janus_UIguard($this->_config->getArray('access', array()));
 
         if($guard->hasPermission('allentities', null, $this->_user->getType(), TRUE)) {
             if(!is_null($state)) {
-                $st = $this->execute('SELECT DISTINCT `eid` FROM '. self::$prefix .'entity WHERE `state` = ?' . $excludeSQL,
-                    array($state)                     

Index: modules/janus/lib/UserController.php
===================================================================
--- modules/janus/lib/UserController.php	(revision 680)
+++ modules/janus/lib/UserController.php	(working copy)
@@ -104,39 +104,70 @@
      */
     private function _loadEntities($state = null, $state_exclude = null)
     {
