Populate activeCheckBoxList from selections table

Checkbox selections are stored in table and retrieved as follows:

Supplier Model:




$supplier_vehicles=SupplierVehicle::model()->findAll(

'supplier_id=:supplier_id', array(':supplier_id'=>$model->id));



Supplier::model()->vehicles is an activeCheckBoxList with predefined checkboxes, I need the matching checkboxes to be ticked. E.g:

<input type="checkbox" name="Supplier[vehicles][]" value="1" />Car

<input type="checkbox" name="Supplier[vehicles][]" value="2" />Boat

I tried Supplier::model()->vehicles=$supplier_vehicles but that did not work. Do I need to create this as a relation in my Supplier model?

supplier table:

id

name

supplier_vehicle table:

id

supplier_id

vehicle_id

Also what is the best way of handling updating of records, for example suppose there are 6 checkboxes and the first 3 are saved in the DB. Then upon update, the first 3 are unticked and the last 3 are ticked - obviously we need to ensure those redundant records in the DB are deleted, but does Yii offer any easy way to do this?

Anyone able to advise?

There is no easy way for this in Yii.

I cannot help you with checkbox list because I never use it, I always use many checkbox. The checkboxlist has a strange behaviour (at least it has the last time I checked it).

For update the record you can do like that:




SupplierVehicle::model()->deleteAll('supplier_id=:supplier_id', array(':supplier_id'=>$model->id));

foreach ($_POST['checkboxes'] as $checkbox)

{

    /*create and save the model*/

}



I see. That’s the quick and easy way of doing it, but not very efficient, i.e. we could be deleting a record and then re-adding it in again. We can of course do a findAll() to check if there is a supplier_id/vehicle_id combination that matches with an entry in our checkbox array, but that isn’t very efficient either.

Anyway my main stumbling block at the moment is the populating of the checkboxes, does anybody else know how to do this?

I’ve done it myself:




$supplier_vehicles=SupplierVehicle::model()->findAll(

'supplier_id=:supplier_id', array(':supplier_id'=>$model->id));

		

$vehicle_types=array();

		

foreach($supplier_vehicles as $vehicle)

{

	$vehicle_types[]=$vehicle->vehicle_id;

}


$model->vehicles=$vehicle_types;



Any improvements to this are welcome.