TanGio
TanGio

Reputation: 766

Put arrays in session symfony2

I have the following code:

 public function addAction(Request $request){
    $aBasket[] = $request->request->all();
    $this->get('session')->set('aBasket', $aBasket);
    return $this->redirect($this->generateUrl('shop_desktop_homepage'));
    print_r($aBasket);
}

Works fine but is saved in session only the last array which was save. How to put in session. For example, the array is saved like this, only the last:

array:1 [▼
    0 => array:3 [▶]
]

But I want to save :

array:1 [▼
  0 => array:3 [▶]
  1 => array:3 [▶]
  2 => array:3 [▶]
]

not only the last.

Upvotes: 4

Views: 6580

Answers (1)

jagad89
jagad89

Reputation: 2643

I have not tested the code. But it will help.

public function addAction(Request $request){

  $aBasket = $request->request->all();
  // Get Value from session
  $sessionVal = $this->get('session')->get('aBasket');
  // Append value to retrieved array.
  $sessionVal[] = $aBasket;
  // Set value back to session
  $this->get('session')->set('aBasket', $sessionVal);
  return $this->redirect($this->generateUrl('shop_desktop_homepage'));

}

I have wrote comment. I have not checked value return by session get method. you need to check type of value return from session get.

Hope this help.

Upvotes: 8

Related Questions