How to save multiple checkbox selection

hi,i’m new with yii…

i want to know the proper way on how to save multiple selection of checkbox?

any examples?

I’m no expert in yii, but after googling this over half an hour, I ended up doing it manually.

Basically it would depend on what are you planning to do with the data. It’s either that you combine the whole array into the same variable using implode




$model = new Post();


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

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


   $valid = $model->validate();    //<-- I'm just guessing this is how you validate >.<


   if($valid)

       $model->yourCheckBoxItems = implode(",",$model->yourCheckBoxItems);


       if($model->save())

           $this->redirect(blahblah);



or if you are planning to save the checkbox data to another database, it would be a little longer, but basically it would have the same logic.

I do think that there are better ways to do it, and I haven’t yet tried out this:

http://www.yiiframework.com/wiki/81/

It shows how to delete multiple records, wherein the data to be deleted came from some few check boxes. I think that this could also be used in saving items, I’m not sure though since I never had got the opportunity to try this out, correct me if I’m wrong.

Hi flakesns,

i think is just like dcsr did, in your controller implote the checkbox selection to get and array, do a for loop and call a model to pull your product info and store in all the new info to your cart list table. my emaple is like this

controller




public function actionSave(){

if(isset($_POST['Post'])){

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

   $productId = implode(",",$model->yourCheckBoxItems);


   $modelProduct = new Product;

   $modelCart = new Cart;


   for($i=0$i<count($productId);$i++){

      $productInfo = $modelProduct->getInfo($productId[$i]);

      $modelCart->storeCart($productInfo);

   }

   $this->redirect(blahblah);

}

}



modelProduct




public getInfo($productId){

    $criteria=new CDbCriteria;

    $criteria->select="product_price,product_code";

    $criteria->condition='product_id=:productId';

    $criteria->params=array(':productId'=>$productId);

    $this->model()->find($criteria);

}



$modelCart




public function storeCart($productInfo){

    $this->setIsNewRecord(true);

    unset($this->cart_id); // should be your table primary key

    $this->product_id = $productInfo['product_id'];  // assume this is your table field u want to save

    $this->product_price = $productInfo['product_price'];

    $this->product_code = $productInfo['product_code'];

}