TanGio
TanGio

Reputation: 766

Update session in symfony2 for shoppingg cart

I have the following code :

public function addAction(Request $request){
    //Get submited data
    // Get Value from session
    $sessionVal = $this->get('session')->get('aBasket');
    // Append value to retrieved array.
    $aBasket = $request->request->all();
    if(count($sessionVal) > 0) {
        foreach ($sessionVal as $key=>$value) {
            if($aBasket['product_id'] == $sessionVal[$key]['product_id'])
            {
                $sessionVal[$key]['product_quantity'] = $sessionVal[$key]['product_quantity'] + $aBasket['product_quantity'];
                $this->get('session')->set('aBasket', $sessionVal);
            }
            else
            {
                $sessionVal[] = $aBasket;
                $this->get('session')->set('aBasket', $sessionVal);
            }
        }
    }
    else
    {
        $sessionVal[] = $aBasket;
        $this->get('session')->set('aBasket', $sessionVal);
    }
    // Set value back to session
    return $this->redirect($this->generateUrl('shop_desktop_homepage'));
}

The idea is to increment the quantity of an existing product, if id not corespond then add them. Now the quantity is correct added, but and the product is also added.Exist a solution?? Help me please...

Upvotes: 3

Views: 732

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

You can simplify your code to, i guess your session array would look something like

array(
    '11' =>array('id'=>'11','title'=>'some product','product_quantity'=>2),
    '12' =>array('id'=>'12','title'=>'some product','product_quantity'=>1),
    '13' =>array('id'=>'13','title'=>'some product','product_quantity'=>3),
);

key in your cart array will be product id so there will be no chance of duplicate product in array now in below code i have removed foreach loop instead i have used just an if check if(isset($sessionVal[$aBasket['product_id']])) whether product already exist in cart array by putting product id in place of key e.g if(isset($sessionVal['11']))if exist then increment quantity by one, if not exist then insert product in cart array

public function addAction( Request $request ) {
    $sessionVal = $this->get( 'session' )->get( 'aBasket' );
    $aBasket = $request->request->all();
    if(isset($sessionVal[$aBasket['product_id']])){
        $sessionVal[$aBasket['product_id']]['product_quantity'] += 1;
    }else{
        $sessionVal[$aBasket['product_id']]= array(
            'id'=>$aBasket['product_id'],
            'product_quantity' => 1,
            'other_info' => '...'
        );
    }
    $this->get( 'session' )->set( 'aBasket', $sessionVal );
    return $this->redirect( $this->generateUrl( 'shop_desktop_homepage' ) );
}

Upvotes: 1

Related Questions