xylar
xylar

Reputation: 7673

Mark checkbox as checked if in postdata or in existing user data in Kohana

I want to mark checkboxes if they have been selected via existing data from db or in the postdata. I have an array of all roles, $roles, and $user_roles contains the current roles.

foreach ($roles as $r) {

    $checked = false;

    if(isset($postdata['roles'][$r->id])){
        $checked = true;
    }
    else{
        foreach($user_roles as $ur){
            if($ur->id == $r->id){
                $checked = true;
            }
        }
    }

<input type="checkbox" name="roles[<?php echo $r->id; ?>]" <?php if($checked){ ?>checked="checked"<?php } ?> value="<?php echo $r->id; ?>" />

The code is working but I wondered if I could tidy it up. I am using Kohana 3.2

Upvotes: 0

Views: 722

Answers (2)

badsyntax
badsyntax

Reputation: 9650

Assuming you are trying to update an existing user in the db...

foreach($roles as $role){
  echo 
    Form::checkbox('roles[]', $role->id, in_array($role, $user_roles), array('id' => 'role-'.$role->id)),
    Form::label('role-'.$role->id, $role->name);
}

The $user_roles variable is either an array of user roles from the db, using $user->roles->find_all(), or user roles that have been updated via POST data. If POST data exists, then I update the user roles:

$roles = $this->request->post('roles');

foreach(ORM::factory('role')->find_all() as $role)
{
  if (in_array($role->id, $roles))
  {
    // Add roles relationship
    $user->add('roles', new Model_Role(array('id' => $role->id)));
  }
  else
  {
    // Remove roles relationship
    $user->remove('roles', new Model_Role(array('id' => $role->id)));
  }
}

And then I still use $user->roles->find_all() for the user roles displayed in the view.

Doing it this way means I don't have to decide what to display in the view, (POST or DB data), as that conditional exists in the model or controller, and the user roles are always up to date.

Upvotes: 1

Kemo
Kemo

Reputation: 7042

$role_ids = $user_roles->as_array(NULL, 'id');

$checked = in_array($r->id, $role_ids) or Arr::path($postdata,"roles.$r->id");

echo Form::checkbox('roles['.$r->id.']', $r->id, $checked);

Upvotes: 1

Related Questions