0
votes

I have table user which have fields username,password, and type. The type can be any or combination of these employee,vendor and client i.e a user can be vendor or client both or some another combination. For type field I have used the multiple checkbox, see the code below. This is the views/users/add.ctp file

Form->create('User');?> Form->input('username'); echo $this->Form->input('password'); echo $this->Form->input('type', array('type' => 'select', 'multiple' => 'checkbox','options' => array( 'client' => 'Client', 'vendor' => 'Vendor', 'employee' => 'Employee' ) )); ?> Form->end(__('Submit', true));?>

This is the code I have used in the model file. A callback method beforeSave app/models/user.php

function beforeSave() { if(!empty($this->data['User']['type'])) { $this->data['User']['type'] = join(',', $this->data['User']['type']); } return true; } This code saves the multiple values as comma separated value in db.

The main problem comes when Im editing a user. If a user has selected multiple types during user creation I can't find the checkbox checked for that user types.

3
I'm unfamiliar with cakephp, if you are loading $this->data['User'] somewhere, straight after you do that, you should run $this->data['User']['type'] = explode(',',$this->data['User']['type']); and then it should workJason
ya I know that I should code it that way. But Iam confused about in which callback method should I write this code.samir chauhan

3 Answers

3
votes

you should never be saving serialized data, json or csv in a field. This makes your life real hard later on down the line.

While habtm is one way to do things, if your binary maths is reasonable you might want to checkout bitmasks for this. here is a great post http://mark-story.com/posts/view/using-bitmasks-to-indicate-status

basics would be 1 = employee 2 = vendor 4 = client // 8 = next_type

then, if the user was type employee & vendor the type would be 3 (1 + 2) and if it was a vendor & client the type would be 6 (2 + 4)

as you can see there is no way to mix it up, and bitwise works pretty good in mysql aswell so finds are pretty easy. See the post for much more detailed information

0
votes

You should have a table types and a join table users_types.
What you're looking at is a HABTM relationship, so you should handle it like one.
In the joining UsersType model you should add a custom validation rule that checks if the current combination of types is allowed.

0
votes

If you want to modify data after it's been found in the database, you can use the afterFind() callback in your model.

So in your case, put something like this is your user model:

function afterFind($results) {
    $results['User']['type'] = explode(',', $results['User']['type']);
    return $results;
}

There's more info on afterFind in the CakePHP manual.

That being said, it might be worth considering another approach, like a HABTM relationship as deceze first suggested above.