php - How to stop array from being overwritten? -


i'm using symfony2, version 2.7. should able answer because it's not entirely relevant symfony.

i have function. want function add new item (once clicked on form) array. instead, array keeps getting overwritten new item clicked.

i tried few foreach loops couldn't right. please, appreciated.

below relevant function.

  /**      * displays bought items      *      * @route("/buy/{id}", name="item_buy")      * @method("get")      * @template()      */     public function buyaction(request $request, $id)     {         $session = $request->getsession();          $cart[] = $id;          $em = $this->getdoctrine()->getmanager();          $entity = $em->getrepository('appbundle:item')->find($id);          $entities = $em->getrepository('appbundle:item')->findall();              $session->set('cart', $cart);              if (!$entity) {                 throw $this->createnotfoundexception('no item ');             } else {                 $cart[$entity->getid()] = $entity->getname();             }        $session->set('cart', $cart);      return array(         'cart'     => $cart,         'entity'   => $entity,         'entities' => $entities,     ); } 

how being used in twig:

{% extends '::base.html.twig' %}  {% block body -%}     <h1>items bought...</h1>      <table class="record_properties">         <h3>you bought...</h3>         {# {% if entity defined %} #}             {% key, cartvalue in cart %}                 <tr>                     <td>{{ key }}: {{ cartvalue }}</td>                     {{ dump(entity.name) }}                     {{ dump(cart) }}                 </tr>             {% endfor %}         {# {% endif %} #}           <tbody>         {% entity in entities %}             <tr>                 <td><a href="{{ path('item_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td>                 <td>{{ entity.name }}</td>                 <td>                 <ul>                     <li>                         <a href="{{ path('item_buy', { 'id': entity.id }) }}">buy</a>                     </li>                 </ul>                 </td>             </tr>         {% endfor %}         </tbody>     </table>        <ul class="record_actions">     <li>         <a href="{{ path('item') }}">             list         </a>     </li> {% endblock %} 

maybe wrong, guess line problem:

$cart[] = $id; 

you initialize here new array, every time. if wright shuld array session.

try

$cart = $this->get('session')->get('cart', []);


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -