function validation($data)
 {
     global $CFG, $COURSE;
     $errors = array();
     if (!($users = groups_get_potental_members($data['courseid'], $data['roleid']))) {
         $errors['roleid'] = get_string('nousersinrole', 'group');
     }
     $usercnt = count($users);
     /// Check the number entered is sane
     if ($data['groupby'] == 'groups') {
         if ($data['number'] > $usercnt || $data['number'] < 1) {
             $errors['number'] = get_string('toomanygroups', 'group', $usercnt);
         }
     }
     /// Check the naming scheme
     $matchcnt = preg_match_all('/[#@]{1,1}/', $data['namingschemegrp']['namingscheme'], $matches);
     if ($matchcnt != 1) {
         $errors['namingschemegrp'] = get_string('badnamingscheme', 'group');
     }
     if (count($errors) > 0) {
         return $errors;
     } else {
         return true;
     }
 }
    }
}
/// Create the form
$editform = new autogroup_form('autogroup.php', array('roles' => $rolenames));
$editform->set_data(array('courseid' => $courseid, 'seed' => time()));
/// Handle form submission
if ($editform->is_cancelled()) {
    redirect($returnurl);
} elseif ($data = $editform->get_data()) {
    /// Allocate members from the selected role to groups
    if ($data->allocateby == 'random') {
        $orderby = 'firstname';
    } else {
        $orderby = $data->allocateby;
    }
    $users = groups_get_potental_members($data->courseid, $data->roleid, $orderby);
    $usercnt = count($users);
    if ($data->allocateby == 'random') {
        srand($data->seed);
        shuffle($users);
    }
    $groups = array();
    $i = 0;
    $cnt = 0;
    if ($data->groupby == 'groups') {
        $numgrps = $data->number;
        $userpergrp = ceil($usercnt / $numgrps);
    } else {
        $numgrps = ceil($data->number / $usercnt);
        $userpergrp = $data->number;
    }