NotJustClarkKent
NotJustClarkKent

Reputation: 1095

Getting an array of values based on a set of checkboxes

I'm very new to Ember and I've built this sort of thing before a few times before using JS/jQuery but after 2 hours I just can't seem to make any headway the "Ember" way.

I have a set of permissions that I've pulled from my Permission Model:

[
  {
    id : 1,
    permission : "Can Eat Cake",
    description : "User is allowed to eat cake."
  },
  {
    id : 2,
    permission : "Can Fly",
    description : "User is allowed to fly."
  },
  ...
]

And I want to allow the user to check all that apply to a particular role:

// RoleCreate.hbs
{{#each model.permissions}}
  {{input type="checkbox" name="rolePerm" checked=permChecked}} {{permission}}<br />
{{/each}}

Up to this point, everything looks/operates as expected, however, this is where I'm stuck... how do I get an array of ids/values for the checked checkboxes so I can create an object like the below to send back to the server to actually create the role?

{
  roleName : "My new user role",
  permissions : [ 1, 2 ] 
}

I just have no idea how to get the values of each checkbox to a parent array that can be sent to the server to create the new role... I've managed to figure out how to get an observer to fire on check/uncheck but can't seem to get the value of the checkbox no matter what I try.

// RoleCreateController
rolePermissionMgr : function() {

  console.log( "Permission Checkbox Changed!" );

}.observes( '[email protected]' )

Again, very new to Ember so I'm sure I've done one or more things incorrectly.

Upvotes: 0

Views: 70

Answers (1)

blessanm86
blessanm86

Reputation: 31779

You were almost there. I assign the checkbox value to the model. I just check every checkbox value when the observer is fired and extract the permissions using ember's array methods. Here is the working demo.

{{#each item in content.permissions}}
  <li>{{input type="checkbox" checked=item.value}} {{item.permission}}</li>
{{/each}}

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return {
      roleName: 'Blessan',
      permissions: [{
        id : 1,
        permission : "Can Eat Cake",
        description : "User is allowed to eat cake."
      },{
        id : 2,
        permission : "Can Fly",
        description : "User is allowed to fly."
      }]
    };
  }
});

App.IndexController = Em.ObjectController.extend({
  permissionChanged: function() {
    var obj = {
      roleName: this.get('content.roleName'),
      permissions: this.get('content.permissions')
              .filterBy('value', true).mapBy('id');
    };
    console.info(obj);
  }.observes('[email protected]')
});

Upvotes: 1

Related Questions