【问题标题】:Remove elements from session array从会话数组中删除元素
【发布时间】:2016-02-24 14:11:27
【问题描述】:

出于学习目的,我正在尝试使用 symfony 构建一个超级简单的购物车。目前我正在使用会话来存储用户在数组中选择的“产品”。我有三个问题想问...

  1. 我想要一个从会话数组中删除“产品”的按钮(用户会在表格中显示他们选择的“产品”列表。然后用户可以选择从表格中删除“产品”并随后从会话数组中删除“产品”)。我是 jquery 的超级初学者,但是,我确信这可以使用 jquery 来完成。我怎样才能做到这一点?我研究了拼接,并删除了函数,但无法运行。有人可以使用我的 twig 文件给我一些示例,以便我更好地理解设置的正确方法吗?

cart.twig:

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

{% block body %}

<h1><u><i>Welcome to the Cart</i></u></h1>

    <div class="container">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price Per Unit</th>
                    <th>Remove From Cart</th>
                </tr>
            </thead>

            <tbody>
                {% for key, cartValue in cartArray %}
                    <tr>
                        <td>{{ cartValue[0] }}</td> <!--Product-->
                        <td>{{ cartValue[1] }}</td> <!--Quantity-->
                        <td>${{ cartValue[2] }}</td> <!--Price Per Unit-->
                        <td> <script type="text/javascript"> 
                                $(function() {(
                                    cartArray.splice(cartArray.indexOf(0),1);
                                )};
                            </script>
                            <button type="button" class="btn btn-danger">
                            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                            </button>
                        </td>
                    </tr>
                {% endfor %}    
            </tbody>
        </table> <!--top table-->

            <div class="money-container">
                <p class="text-right">Total Cost: ${{ totalCostOfAllProducts }}</p>
            </div><!--moneyContainer-->

    </div> <!--container-->

            <ul>
                <li>
                    <a href="{{ path('product_bought', {'id': entity.id }) }}">
                        Buy These Products
                    </a>
                </li>
                <li>
                    <a href="{{ path('product') }}">
                        Add More Products
                    </a>
                </li>
                <li>
                    <a href="{{ path('product_edit', { 'id': entity.id }) }}">
                        Edit
                    </a>
                </li>
                <li>{{ form(delete_form) }}</li>
            </ul>

{% endblock %}
  1. 再次通过更多研究,我发现数据操作应该保留在控制器类中。这样做会违反该规则吗?如果是这样,我应该如何在控制器中完成我的任务?

产品控制器:

namespace PaT\ShopTestBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
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 PaT\ShopTestBundle\Entity\Product;
use PaT\ShopTestBundle\Form\ProductType;

/**
 * Product controller.
 *
 * @Route("/product")
 */
class ProductController extends Controller
{

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

        //$entities = $em->getRepository('PaTShopTestBundle:Product')->findAll();

        $categories = $em->getRepository('PaTShopTestBundle:Category')->findAll();

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

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

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

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

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

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

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

        return $form;
    }

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

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

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

        $entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Product entity.');
        } else {
            //dump($entity); die;
            $descriptions = $entity->getDescriptions();
            //dump($entity); die;
        }

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

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

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

        $entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Product 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 Product entity.
    *
    * @param Product $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Product $entity)
    {
        $form = $this->createForm(new ProductType(), $entity, array(
            'action' => $this->generateUrl('product_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

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

        return $form;
    }

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

        $entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);

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

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

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

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

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

    /**
     * Deletes a Product entity.
     *
     * @Route("/{id}", name="product_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('PaTShopTestBundle:Product')->find($id);

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

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

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

    /**
     * Creates a form to delete a Product 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('product_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }

    /** 
     * Creates the option to 'add product to cart'.
     *
     * @Route("/{id}/cart", name="product_cart")
     * @Method("GET")
     * @Template()
     */
    public function cartAction(Request $request, $id) {

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

        $entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);

        $session = $request->getSession(); //session----------------

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

        $totalCostOfAllProducts = 0;

        $cartArray = array();

        if (is_null($cartArray) || !$entity) {
            throw $this->createNotFoundException('Error: Nothin in Array/Entity');
        } else {
            $cartArray = $session->get('cartArray', []);

            $cartArray[$entity->getId()] = [$entity->getName(), $entity->getQuantity(), $entity->getPrice()];

            foreach ($cartArray as $key => $product) {
                    // dump($cartArray); die;
                    // dump($key); die;
                    $productEntity = $em->getRepository('PaTShopTestBundle:Product')->find($key);
                    $quantity = $productEntity->getQuantity();
                    $price = $productEntity->getPrice();
                    $totalCostOfAllProducts += $price * $quantity;
            }
        }

        //$remove = unset($cartArray);

        // if (isset($_POST['Button'])) {
        //     unset($cartArray[1]); //remove index
        // }

        //above did nothing

        $session->set('cartArray', $cartArray); //session---------------

        //var_dump($cartArray); die;

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

    /**
     * Displays the products bought from products 'added to cart'
     *
     * @Route("/{id}/bought", name="product_bought")
     * @Method("GET")
     * @Template()
     */
    public function boughtAction(Request $request, $id) {

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

        $entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);

        $session = $request->getSession(); //session----------------

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

        $totalCostOfAllProducts = 0;

        $cartArray = array();

        if (is_null($cartArray) || !$entity) {
            throw $this->createNotFoundException('Error: Nothing Found In Entity/Array');
        } else {
            $cartArray = $session->get('cartArray', []);

            $cartArray[$entity->getId()] = [$entity->getName()];

            foreach ($cartArray as $key => $value) {
                $prodEnt = $em->getRepository('PaTShopTestBundle:Product')->find($key);
                $quantity = $prodEnt->getQuantity();
                $price = $prodEnt->getPrice();
                $totalCostOfAllProducts += $price * $quantity;
            }
        }

        $session->set('cartArray', $cartArray); //session---------------
        $request->getSession()->invalidate(1);

        return array(
            'price'     => $price,
            'quantity'  => $quantity,
            'totalCostOfAllProducts' => $totalCostOfAllProducts,
            'cartArray' => $cartArray,
        );
    }
}
  1. 最后,如何在不使用会话数组逻辑的情况下完成所有这些操作,就像我现在正在做的那样。与我交谈过的人告诉我,依靠会话来创建数组是不好的做法。做我正在做的事情的更好方法是什么。 (如果最后一个问题过于宽泛或基于观点,那么要么忽略它,要么留下一些链接/快速答案来帮助回答,但请不要基于这个问题关闭整个事情)

非常感谢任何帮助,谢谢!

编辑:转储数组:

array:3 [▼
  1 => array:3 [▼
    0 => "Water"
    1 => 5
    2 => 2.75
  ]
  5 => array:3 [▼
    0 => "Rooster"
    1 => 1
    2 => 105.0
  ]
  6 => array:3 [▼
    0 => "Apple Sauce"
    1 => 1
    2 => 9.25
  ]
]

这也是我最新的尝试:(仍然什么都不做/不工作)

<script type="text/javascript"> 
    $('#removeButton').click(function() {
        cartArray.splice(indexOf(($this), 1);
    });
</script> 

(由于 'products' 的数量可以超过 1,splice 中的第二个参数可能不起作用。所以 splice 可能不是我需要的答案......或者不是,我完全在这里猜测

【问题讨论】:

  • 产品能否在数组中出现多次?
  • 不,它不能出现多次
  • 你说 .splice 不起作用,splice 中的第一个参数是要删除元素的起始索引,第二个参数是要删除多少项。您应该使用array.splice(indexOf("someValueInArray"), 1) indexOf("value") 将返回该值在数组中的索引。第二个将从该起始索引中仅删除 1 个条目..
  • 我理解正确,''someValueInArray" 将是我要从中删除的索引?正确吗?
  • 不,它是数组中的值而不是索引。例如“food”产品["food", "soap", ect...],indexOf("food") 将返回食物在数组中的索引,因此它将返回0

标签: php jquery symfony session


【解决方案1】:

首先,您需要函数的查询目标,如果我理解正确,这将是按钮。给你的按钮一个 id 并在标签中引用它,例如 $( '#buttonid' ).click( function(){ #your code here }) 也 jquery 有一个 $(this) 选择器,它允许你引用一个与触发动作的当前上下文相关的元素。因此,在您的情况下,$(this).parent().parent() 将引用包含被单击按钮的&lt;tr&gt;。另外,为了它的价值,您应该将脚本放在页面的顶部或底部

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2011-10-31
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多