Updating Checkbox Selections

Suppose I have a activeCheckBoxList called $model->selections

When the user wants to UPDATE their selections, they can view the form which already has their CURRENT selections ticked.

The user then changes their selections and submits the form. In my controller I need to update these selections in the database.

In my Listing model, I have the following relation, which fetches the current selections:


'categories'=>array(self::HAS_MANY, 'ListingCategory', 'listing_id'),

And here is the ListingController code:


$model = $this->loadModel($id);


$selections = array();


// reference the 'categories' relation

foreach($model->categories as $category)

{

	$selections[] = $category->category_id;

}


// $model->selections is a virtual attribute in Listing model

$model->selections = $selections;


if(isset($_POST['Listing']))

{

	$model->attributes = $_POST['Listing'];

	

	if($model->validate())

	{

		foreach($model->selections as $selection)

		{

			$listing_category = new ListingCategory();

			$listing_category->listing_id = $model->id;

			$listing_category->category_id = $selection;

			$listing_category->save();

		}

		

		$this->redirect(array('view', 'id'=>$model->id));

	}

}

So this basically ADDS the new selections to the database, but does not delete the existing ones. What is the most efficient way of doing this?

Hi

You have to detect the difference old and news categories

So get the current stored categories($this->oldCategories) and compares with news ($this->newCategories)

Like that


   $toRemove = array_diff($this->oldCategories, $this->newCategories); 


        foreach ($toRemove as $item) {

                $item->delete();

            }

        }

The other thing you can do is delete all the user’s associated records and resave them if the history isn’t important.

I had the same issue before one months for e-shop that I develop,

so I have to solve the assign of products to their categories :D

Thanks for voting ;)

Hi,change your code like this in your controller:


                foreach($model->selections as $selection)

                {

                        $listing_category =ListingCategory::model();

                        $listing_category->listing_id = $model->id;

                        $listing_category->category_id = $selection;

                        $listing_category->save();

                }

yes,if you want update your record,you should declare the class like this "$listing_category =ListingCategory::model();" if you want insert a new record,declare the class:"$listing_category =new ListingCategory();",Then call the save method.