显示会话数组

时间:2016-02-05 14:13:52

标签: php arrays symfony session

我通过创建一个超级简单的购物车测试来学习MVC和Symfony2(版本2.7)(我知道symfony有一个学说,但我只想学习基础知识,所以对我很轻松;))。

我希望能够做的就是他们点击的每个项目,它出现在他们点击的其他项目旁边。这真的不是一个MVC或Symfony2问题,就像我正在喋喋不休的php,twig编码问题一样。

我有一个用户可以点击购买的表单,用户可以将表单重定向到另一个显示他们购买的内容的表单。在该显示下方是具有购买按钮选项的其他项目。一旦他们单击某个项目的该按钮,新项目就会出现在上一个项目旁边。

相反,旧项目消失,新项目出现。

如何让旧的与新的一起留下来?

下面是呈现表单的控制器类。 看看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()
        ;
    }
}

///////////////// 下面是第一个表格,其中没有任何东西是&#34;买了&#34;然而。 //////////////////

{% 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 %}

///////////////////// 以下是用户在购买&#34;之后显示的表格。一个项目(&#34;购买&#34;项目显示在顶部),他们可以选择&#34;购买&#34;别的东西(这个新项目应该放在前一个&#34;买的&#34;项目旁边)。

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

{% 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 %}

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

昨天我一整天都在主演,我无法找到我的问题。所以感谢任何帮助,谢谢。

ALSO 任何想法如何使这个更好/事情,以帮助我学习MVC基础知识/ Symfony2的东西,如果你有一些也会很酷。我一直在使用Lynda dot com,谷歌,这个网站,Symfony书/ cookbook。谢谢!

1 个答案:

答案 0 :(得分:0)

问题是你在最后一个Twig文件中有这个。

{% for entities in cart %}

您在购物车的每次迭代中都会放置实体变量,因此您将失去控制器中加载的所有实体。

改变这个......

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

到此......

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

至少应该解决这部分问题:)

相关问题