1
votes

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

<div class="users form">
<?php echo $this->Form->create('User');?>
    <fieldset>
        <legend><?php __('Add User'); ?></legend>
    <?php
        echo $this->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'
   )
  ));
    ?>

    </fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>

In the model file I have used a beforeSave callback method:

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 values in the database.

The main problem comes when I'm editing a user. If a user has selected multiple types during user creation, none of the checkboxes is checked for the type.

2
You have the data modeled wrong to begin with. Before you invest time on code for this model, get that part right. User->Type is a one-to-many relation. That type of relation is represented with a second table where the user may have between 1 and 3 rows. If you ever have multiple values in a single column (i.e. column values are not atomic) you've not normalized your design.Dan Grossman
@Dan: You want to say that I have to create new table type and user_type tables to relate the types with users.samir chauhan
You don't necessarily need a types table, but a user_type table, yes.Dan Grossman
@Dan In user_type table there would be 3 fields id, typeName and user_id. or u have the other way. Could u explain a bit more abt the table structure.samir chauhan

2 Answers

0
votes

you have $this->data['User']['type'] = join(',', $this->data['User']['type']); in the beforeSave() so you would need to do the same in afterFind() $this->data['User']['type'] = explode(',', $user['User']['type']); which would make it an array again.

This is however a horrible design, you should consider doing it properly.

0
votes

@dogmatic69 after following this $this->data['User']['type'] = explode(',', $user['User']['type']); and the array is properly arranged the checked box is still unchecked