简体   繁体   中英

How to stop array from being overwritten?

I'm using Symfony2, version 2.7. But anyone should be able to answer this because it's not entirely relevant to symfony.

I have a function. I want that function to add a new item (once clicked on from a form) to an array. Instead, my array keeps getting overwritten with the new item that was clicked.

I tried a few foreach loops but couldn't get it right. Please, any help is appreciated.

Below is 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 it is being used in twig:

{% extends '::base.html.twig' %}

{% block body -%}
    <h1>Items Bought...</h1>

    <table class="record_properties">
        <h3>You Bought...</h3>
        {# {% if entity is defined %} #}
            {% for key, cartValue in cart %}
                <tr>
                    <td>{{ key }}: {{ cartValue }}</td>
                    {{ dump(entity.name) }}
                    {{ dump(cart) }}
                </tr>
            {% endfor %}
        {# {% endif %} #}


        <tbody>
        {% for 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') }}">
            Back to the list
        </a>
    </li>
{% endblock %}

Maybe I am wrong, but I guess that this line is problem:

$cart[] = $id;

You initialize here new array, every time. If I am wright You shuld get this array from session .

Try

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

For better formats of code I am answering to Your last comment here.

Above You're writting about adding new elements and I helped You solve this problem. Now (if I understand correclty) You have problem with added elements to array which You saved in session. I'm surprised your surprise. If You want delete something now from array which You saved in session YOU HAVE TO IMPLEMENT IT. It's not difficult - to clear a cart You should write something like this:

public function clearCartAction(Request $request)
{
   $session->set('cart', array()); //set empty array

   //return something here.. 
}

To delete single object from cart something like this (very simple implementation):

public function removeAction(Request $request, $id)
{
    $session = $request->getSession();

    $em = $this->getDoctrine()->getManager();

    $cart = $session->get('cart', array());

    if (isset($cart[$id]) {
        unset($cart[$id]);
    }

    $session->set('cart', $cart);

    //return something here
}

I can see that You have many very basic problems - definatelly You need a lot of learn and study programming.

Btw. I guess that I helped You solve problem describing in topic - so You should mark my comment as helpfull and topic as resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM