[eluser]Michael Wales[/eluser]
I kind of rushed over this, but you get the general idea.
A few things here - first we're going to change our checkbox's return value to TRUE; since, if a checkbox isn't clicked, it won't be part of the POST array and the Input class will return FALSE.
Secondly, your labels aren't doing anything for your right now as they aren't referencing an ID. We're going to fix that.
I would pull all of the possible permissions down into a variable in my controller and pass it to this view, so I could loop through the various admin privileges:
Code:
<h1>Administrative Priviliges</h1>
<?php foreach ($admin_privs as $a): ?>
<input type="checkbox" name="<?php echo $a->priv_id; ?>" id="priv-<?php echo $a->priv_id; ?>" value="TRUE" /><label for="priv-<?php echo $a->priv_id; >"><?php echo $a->priv_title; ?></label>
<?php endforeach; ?>
Now that our form is all fixed up - let's do the form processor:
Code:
$errors = array();
if ($this->validation->run()) {
// Setup our user object
$user = array('username' => $this->input->post('username'),
'screen_name' => $this->input->post('screen_name'),
'email' => $this->input->post('email'),
'passwrd' => $this->input->post('password'));
// Send it to the model to be created
if ($this->user->create('user')) {
$user_id = $this->db->insert_id();
// Get all of our possible privileges
$admin_privs = $this->privileges->get_privileges();
// Loop through them all to see if we're giving them that privilege
if ($admin_privs !== FALSE) {
foreach ($admin_privs as $a) {
if ($this->input->post($a->priv_id)) {
// We are, make a call to the model to insert the data
if (!$this->user->add_privilege($user_id, $a->priv_id)) {
// We couldn't add the priv for some reason, save this error
$errors[] = 'Could not add ' . $a->priv_title . ' privilege.';
}
}
}
// Check for errors
if (count($errors) !== 0) {
show_error('There were errors:<br /><br />' . implode('<br />', $errors));
}
}
// We're done creating this user - go somewhere else
redirect('user');
return;
}
show_error('Could not create user.');
}
Now, we'll create our user model - not really focusing on create() much since it's not the topic here. Make sure you hash out the password and protect it with a salt or something:
Code:
function create($user) {
$this->db->insert('users', $user);
if ($this->db->affected_rows() > 0) {
return TRUE;
}
return FALSE;
}
function add_privilege($user, $priv) {
$this->db->insert('admin_priv_link', array(
'admin_id' => $user,
'priv_id' => $priv));
if ($this->db->affected_rows() > 0) {
return TRUE;
}
return FALSE;
}
Now, the privileges model:
Code:
function get_privileges() {
$query = $this->db->get('admin_privs');
if ($query->num_rows() > 0) {
return $query->result();
}
return FALSE;
}