简体   繁体   English

在会话数组中显示单击的项目

[英]Displaying clicked items in session array

I'm learning MVC and Symfony2 (version 2.7) by creating a super simple shopping cart test (I know symfony has a doctrine for this but I just want to learn basics, so go easy on me ;) ). 我正在通过创建一个超级简单的购物车测试来学习MVC和Symfony2(版本2.7)(我知道symfony为此有一个原则,但是我只想学习基础知识,所以对我轻松一点;))。

All I want to be able to do is for each item they click, it appears next to the other items they clicked. 我要做的就是为他们单击的每个项目显示,它们出现在他们单击的其他项目旁边。 This really isn't a MVC or Symfony2 problem as much as it is a php, twig coding problem that I'm flubbing on. 这确实不是MVC或Symfony2问题,而是我正在摸索的PHP,细枝编码问题。

I have a form that users can click buy, on which users are redirected to another form that displays what they bought. 我有一个用户可以单击购买的表单,在该表单上,用户被重定向到另一个显示他们购买的表单。 Below that display are other items with the buy button option again. 在该显示下方的其他项再次带有“购买”按钮选项。 Once they click that button for an item, the new item should appear next to the previous one. 一旦他们单击该按钮的某个项目,新项目应出现在上一个项目的旁边。

Instead the old item goes away and the new item appears. 相反,旧项目消失了,新项目出现了。

How can I make the old ones stay along with the new ones? 我该如何使旧的与新的并存?

Below is the controller class that renders the forms. 下面是呈现表单的控制器类。 Take a look at buyAction It stores the items in cart, but only one at a time...How can I fix that? 看看buyAction它将物品存储在购物车中,但一次只能存储一个...我该如何解决?

////////////////// //////////////////

<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\Item;
use AppBundle\Form\ItemType;

/**
 * Item controller.
 *
 * @Route("/item")
 */
class ItemController extends Controller
{

    /**
     * Lists all Item entities.
     *
     * @Route("/", name="item")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AppBundle:Item')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Creates a new Item entity.
     *
     * @Route("/", name="item_create")
     * @Method("POST")
     * @Template("AppBundle:Item:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Item();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('item_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Item entity.
     *
     * @param Item $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Item $entity)
    {
        $form = $this->createForm(new ItemType(), $entity, array(
            'action' => $this->generateUrl('item_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Item entity.
     *
     * @Route("/new", name="item_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Item();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }


    /**
     * Displays Bought Items
     *
     * @Route("/buy/{id}", name="item_buy")
     * @Method("GET")
     * @Template()
     */
    public function buyAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Item')->find($id);

        $entities = $em->getRepository('AppBundle:Item')->findAll();

        $cart = [];

        $session = $request->getSession();

        $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,
        );
    }


    /**
     * Finds and displays an Item entity.
     *
     * @Route("/show/{id}", name="item_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Item')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Item entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Item entity.
     *
     * @Route("/{id}/edit", name="item_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Item')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Item entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Item entity.
    *
    * @param Item $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Item $entity)
    {
        $form = $this->createForm(new ItemType(), $entity, array(
            'action' => $this->generateUrl('item_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }

    /**
     * Edits an existing Item entity.
     *
     * @Route("/{id}", name="item_update")
     * @Method("PUT")
     * @Template("AppBundle:Item:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:Item')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Item entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('item_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes an Item entity.
     *
     * @Route("/{id}", name="item_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AppBundle:Item')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Item entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('item'));
    }

    /**
     * Creates a form to delete an Item entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('item_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}

///////////////// Below is the first form, where nothing is "bought" yet. ///////////////以下是第一种形式,其中“未购买”任何东西。 ////////////////// //////////////////

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

{% block body -%}
    <h1>Item list</h1>

    <table class="records_list">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Actions</th>
            </tr>
        </thead>
        <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>
                    <li>
                        <a href="{{ path('item_show', { 'id': entity.id }) }}">show</a>
                    </li>
                    <li>
                        <a href="{{ path('item_edit', { 'id': entity.id }) }}">edit</a>
                    </li>
                </ul>
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
        <ul>
            <li>
                <a href="{{ path('item_new') }}">Create a new entry</a>
            </li>
             {#<li>
               <a href="{{ path('item') }}">Buy Item</a>
            </li>#}
        </ul>
{% endblock %}

///////////////////// Below is the form users are shown after they "bought" an item (where the "bought" item is displayed up top) and where they can choose to "buy" something else (where this new item should go next to the previous "bought" item). ////////////////////下面是用户“购买”某项后显示的表单(其中“所购买”的项显示在顶部)以及可以选择“购买”其他商品(此新商品应位于前一个“购买”商品的旁边)。

//////////////////// ////////////////////

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

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

    <table class="record_properties">
        <h3>You Bought...</h3>
        {# {% if entity is defined %} #}
            {% for entities in cart %}
                <tr>
                    <td>{{ entity.name }}</td>
                </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 %}

////////////////////// //////////////////////

I've been starring at this all day yesterday and I can't find my issue. 我昨天整天一直在主演,但找不到我的问题。 So any help is appreciated, thanks. 因此,感谢您的任何帮助。

ALSO Any ideas how to make this better/things to help me learn MVC basics/Symfony2 stuff would be cool if you got some too. 另外,如果有什么想法,如何使它变得更好/可以帮助我学习MVC基础知识/ Symfony2的知识也很不错。 I've been using Lynda dot com, google, this site, the Symfony book/cookbook. 我一直在使用Lynda dot com,google,此网站,Symfony图书/烹饪书。 Thanks! 谢谢!

The problem is that you have this in your last Twig file. 问题是您在上一个Twig文件中有此文件。

{% for entities in cart %}

You're placing in entities variable each iteration of cart, so you're losing all entities loaded in the controller. 您要在购物车的每次迭代中都将实体变量放入,因此您将丢失控制器中加载的所有实体。

Change this... 改变这个...

{% for entities in cart %}
    <tr>
        <td>{{ entity.name }}</td>
    </tr>
{% endfor %}

to this... 为此...

{% for cartItem in cart %}
    <tr>
        <td>{{ cartItem.name }}</td>
    </tr>
{% endfor %}

At least this part should be solved :) 至少这部分应该解决:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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