从会话数组中删除元素

时间:2016-02-24 14:11:27

标签: php jquery symfony session

为了我的学习目的,我试图使用symfony构建一个超级简单的购物车。目前,我正在使用会话来存储'产品'用户在数组中选择的内容。我有三个问题要问......

  1. 我想要一个能够移除产品的按钮。来自会话数组(用户会在表格中显示一个'产品列表。然后,用户可以选择从表格中删除产品,然后删除'产品'来自会话数组)。我是jquery的超级初学者,但是,我确信这可以使用jquery来完成。我怎样才能做到这一点?我研究了splice,并删除了函数但却无法运行。有人可以使用我的twig文件给我示例,这样我就可以更好地理解设置的正确方法了吗?
  2. 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. 从更多研究中我再次看到数据操作应该保留在控制器类中。上述做法会破坏这条规则吗?如果是这样,我应该如何在控制器中完成任务?
    2. ProductController的:

      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. 最后,我如何在不使用像我现在这样做的会话数组逻辑的情况下完成所有这些操作。我与之交谈过的人告诉我依靠会话来创建阵列是不好的做法。做我正在做的事情的更好方法是什么。 (如果这个最后一个问题过于宽泛或基于意见,那么要么忽略它,要么留下一些链接/快速答案以帮助回答,但请不要根据这个问题关闭整个问题)
      2. 非常感谢任何帮助,谢谢!!

        编辑:转储数组:

        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> 
        

        (由于&#39;产品的数量可能超过1,拼接中的第二个参数可能不起作用。因此拼接可能不是我需要的答案......或者不是,我&#39;我完全猜到这里

1 个答案:

答案 0 :(得分:0)

首先,你需要你的功能的查询目标,如果我理解你的话,这将是按钮。给你的按钮一个id并在标签中引用它$( '#buttonid' ).click( function(){ #your code here }) jquery也有一个$(this)选择器,它允许你引用一个相对于触发动作的当前上下文的元素。因此,在您的情况下,$(this).parent().parent()会引用包含已点击按钮的<tr>。另外,对于它的价值,您应该将脚本放在页面的顶部或底部