Symfony 3 在我的结帐时正确获取价格和名称的问题 [英] Symfony 3 problems with getting the price and name right on my checkout

查看:28
本文介绍了Symfony 3 在我的结帐时正确获取价格和名称的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的购物车有问题.我是编码新手,我无法正确处理这些东西.所以.我的问题是:

我创建了一个网上商店",其中包含:产品列表/购物车/结帐.

有 2 个产品:当我将它们添加到我的卡片时,我得到了:然后是结帐出错的地方:您可以看到它添加了 ID 为 3 的产品的名称和价格,而不是正确添加了这两个项目.

这是我的代码:

CartController(带结账功能)

set('cart', '');$session = $this->get('request_stack')->getCurrentRequest()->getSession();$cart = $session->get('cart', array());//$cart = $session->get('cart', array());//$cart = array_keys($cart);//print_r($cart);死;//使用购物车中的查询和 ID 获取信息if( $cart != '' ) {$em = $this->getDoctrine()->getEntityManager();foreach( $cart as $id => $quantity ) {$product[] = $em->getRepository('TuinadviesBundle:Product')->findById($id);}if(!isset($product)){return $this->render('TuinadviesBundle:cart:index.html.twig', array('空' =>真的,));}return $this->render('TuinadviesBundle:Cart:index.html.twig', array('产品' =>$产品,));} 别的 {return $this->render('TuinadviesBundle:Cart:index.html.twig', array('空' =>真的,));}}/*** @Route("/checkout", name="cart_checkout")*/公共功能结帐(){$session = $this->get('request_stack')->getCurrentRequest()->getSession();$cart = $session->get('cart', array());foreach( $cart as $id => $qunatity) {$em = $this->getDoctrine()->getEntityManager();$product = $em->getRepository('TuinadviesBundle:Product')->find(key($cart));}$em = $this->getDoctrine()->getEntityManager();$product = $em->getRepository('TuinadviesBundle:Product')->find(key($cart));return $this->render('@Tuinadvies/checkout/index.html.twig', array('产品' =>$产品,'价格' =>$product->getPrice(),'名称' =>$product->getName(),转储($产品),));//return $this->render('@Tuinadvies/checkout/index.html.twig', array(//'产品' =>$产品();//));//return $this->render('@Tuinadvies/checkout/index.html.twig', array(//'id' =>$product->getId(),//'价格' =>$product->getPrice(),//));}/*** @Route("/add/{id}", name="cart_add")*/公共函数 addAction($id){//获取购物车$em = $this->getDoctrine()->getEntityManager();$product = $em->getRepository('TuinadviesBundle:Product')->find($id);//print_r($product->getId());死;$session = $this->get('request_stack')->getCurrentRequest()->getSession();$cart = $session->get('cart', array());//$cart = $session->get('cart', array());//检查 $id 是否已经存在于其中.如果 ( $product == NULL ) {$this->get('session')->setFlash('notice', '该产品在商店不可用');返回 $this->redirect($this->generateUrl('cart'));} 别的 {if( isset($cart[$id]) ) {//$qtyAvailable = $product->getQuantity();$qtyAvailable = 999;if( $qtyAvailable >= $cart[$id] + 1 ) {$cart[$id] = $cart[$id] + 1;} 别的 {$this->get('session')->setFlash('notice', '数量超过可用库存');返回 $this->redirect($this->generateUrl('cart'));}} 别的 {//如果它没有使它成为 1$cart = $session->get('cart', array());$cart[$id] = $id;$cart[$id] = 1;}$session->set('cart', $cart);返回 $this->redirect($this->generateUrl('cart'));}}/*** @Route("/remove/{id}", name="cart_remove")*/公共函数 removeAction($id){//检查购物车$session = $this->get('request_stack')->getCurrentRequest()->getSession();$cart = $session->get('cart', array());//$cart = $session->get('cart', array());//如果它不存在,则重定向到购物车索引页面.结尾if(!$cart) { $this->redirect( $this->generateUrl('cart') );}//检查 $id 是否已经存在于其中.if( isset($cart[$id]) ) {//如果是 ++ 数量$cart[$id] = '0';未设置($cart[$id]);//echo $cart[$id] ;死();} 别的 {返回 $this->redirect( $this->generateUrl('cart') );}$session->set('cart', $cart);//重定向(索引页)返回 $this->redirect( $this->generateUrl('cart') );}}

结帐/index.html.twig

{% 扩展 '@Tuinadvies/base.html.twig' %}{% 块体 %}<h1>结帐</h1>{% 如果定义为空 %}<h5>您的购物车是空的.</h5>{% 万一 %}{% 设置购物车 = app.session.get('cart') %}{% 如果定义了产品 %}<ul class="缩略图">{% if app.session.flashbag.has('notice') %}<div class="flash-notice">{{app.session.flashbag.has('notice') }}

{% 万一 %}<table class="table"><头><th>产品</th><th>ID</th><th>数量</th><th>价格 (€)</th></thead>{% for key, item, price in car %}<td><b>{{名称}}<b></td><td>{{key }}</td><td>{{ item }}</td><td>{{价格}}</td></tr>{% 结束为 %}{% 万一 %}<a href="{{ path('product_index') }}">产品</a>{% 结束块 %}

购物车/index.html.twig

{% 扩展 '@Tuinadvies/base.html.twig' %}{% 块体 %}<h1>Winkelwagentje</h1><ul class="缩略图">{% 如果定义为空 %}<h5>您的购物车是空的.</h5>{% 万一 %}{% 设置购物车 = app.session.get('cart') %}{% 如果定义了产品 %}<ul class="缩略图">{% if app.session.flashbag.has('notice') %}<div class="flash-notice">{{app.session.flashbag.has('notice') }}

{% 万一 %}{% for key, item in car %}<p>ID:{{key }}</p><p>数量:{{ item }}</p><a href="{{ path('cart_remove', {'id': key}) }}">Remove</a><a href="{{ path('cart_checkout', {'id': key}) }}">checkout</a>{% 结束为 %}{% 万一 %}<a href="{{ path('product_index') }}">产品</a>{% 结束块 %}

可能有很多意大利面条式代码(错误代码),但那是因为我是一个真正的新手.非常抱歉!!!

希望任何人都可以帮助我:)

干杯

解决方案

看起来您正在从数据库中获取每个已检出的产品,然后在 $product 变量上覆盖它而不是保存所有这些.

您应该使用数组来存储不同的产品,然后使用这些产品来填充树枝模板中的值

因此,在您的结帐操作中,您会看到如下内容:

$em = $this->getDoctrine()->getEntityManager();$repo = $em->getRepository('TuinadviesBundle:Product');$产品 = [];foreach ($cart as $id => $quantity) {$products[] = $repo->find($id);}

然后,在渲染模板时,只需传递 $products 数组,而不是名称和价格.

return $this->render('@Tuinadvies/checkout/index.html.twig', array('产品' =>$产品,));

最后,在您的树枝模板中,您将遍历 products 数组并使用它的 id 来获取正确的数量,而不是遍历购物车

{% for product in products %}<td><b>{{product.name }}</b></td><td>{{product.id }}</td><td>{{cart[product.id]}}</td><td>{{product.price }}</td></tr>{% 结束为 %}

希望这会有所帮助!

I am having trouble with my shopping cart. I'm a newbie at coding and i can not get this stuff right. So. my problem is:

I made a "webshop" with a: product list / shopping cart / checkout.

There are 2 products: When i add them to my card i get this: And then there is the checkout where it goes wrong: You can see that it added the name and the price of the product with the ID 3 instead of adding both items correctly.

Here is my code:

CartController (with the checkout function)

<?php

namespace TuinadviesBundle\Controller;

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 Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;

use TuinadviesBundle\Entity\Product;

/**
 * @Route("/cart")
 */
class CartController extends Controller
{
    /**
     * @Route("/", name="cart")
     */
    public function indexAction(Request $request)
    {
        // get the cart from  the session
//        $session = new Session();
        // $cart = $session->set('cart', '');
        $session = $this->get('request_stack')->getCurrentRequest()->getSession();
        $cart = $session->get('cart', array());
       // $cart = $session->get('cart', array());

        // $cart = array_keys($cart);
        // print_r($cart); die;

        // fetch the information using query and ids in the cart
        if( $cart != '' ) {

            $em = $this->getDoctrine()->getEntityManager();
            foreach( $cart as $id => $quantity ) {
                $product[] = $em->getRepository('TuinadviesBundle:Product')->findById($id);
            }

            if( !isset( $product ) )
            {
                return $this->render('TuinadviesBundle:cart:index.html.twig', array(
                    'empty' => true,
                ));
            }


            return $this->render('TuinadviesBundle:Cart:index.html.twig',     array(
                'product' => $product,
            ));
        } else {
            return $this->render('TuinadviesBundle:Cart:index.html.twig',     array(
                'empty' => true,
            ));
        }
    }


    /**
     * @Route("/checkout", name="cart_checkout")
     */
    public function checkout() {
        $session = $this->get('request_stack')->getCurrentRequest()->getSession();
        $cart = $session->get('cart', array());

        foreach( $cart as $id => $qunatity) {

            $em = $this->getDoctrine()->getEntityManager();
            $product = $em->getRepository('TuinadviesBundle:Product')->find(key($cart));

        }



        $em = $this->getDoctrine()->getEntityManager();
        $product = $em->getRepository('TuinadviesBundle:Product')->find(key($cart));
        return $this->render('@Tuinadvies/checkout/index.html.twig',     array(
           'product' => $product,
           'price' => $product->getPrice(),
            'name' => $product->getName(),
            dump($product),
        ));






        //return $this->render('@Tuinadvies/checkout/index.html.twig',     array(
         //  'product' => $product();
       // ));


        //return $this->render('@Tuinadvies/checkout/index.html.twig',     array(
        //   'id' => $product->getId(),
        //    'price' => $product->getPrice(),
        //));



}

    /**
     * @Route("/add/{id}", name="cart_add")
     */
    public function addAction($id)
    {
        // fetch the cart
        $em = $this->getDoctrine()->getEntityManager();
        $product = $em->getRepository('TuinadviesBundle:Product')->find($id);
        //print_r($product->getId()); die;
        $session = $this->get('request_stack')->getCurrentRequest()->getSession();
        $cart = $session->get('cart', array());
        //$cart = $session->get('cart', array());


        // check if the $id already exists in it.
        if ( $product == NULL ) {
            $this->get('session')->setFlash('notice', 'This product is not     available in Stores');
            return $this->redirect($this->generateUrl('cart'));
        } else {
            if( isset($cart[$id]) ) {

                //$qtyAvailable = $product->getQuantity();
                $qtyAvailable = 999;
                if( $qtyAvailable >= $cart[$id]  + 1 ) {
                    $cart[$id]  = $cart[$id]  + 1;
                } else {
                    $this->get('session')->setFlash('notice', 'Quantity     exceeds the available stock');
                    return $this->redirect($this->generateUrl('cart'));
                }
            } else {
                // if it doesnt make it 1
                $cart = $session->get('cart', array());
                $cart[$id] = $id;
                $cart[$id]  = 1;
            }

            $session->set('cart', $cart);
            return $this->redirect($this->generateUrl('cart'));

        }
    }


    /**
     * @Route("/remove/{id}", name="cart_remove")
     */
    public function removeAction($id)
    {
        // check the cart
        $session = $this->get('request_stack')->getCurrentRequest()->getSession();
        $cart = $session->get('cart', array());
        //$cart = $session->get('cart', array());

        // if it doesn't exist redirect to cart index page. end
        if(!$cart) { $this->redirect( $this->generateUrl('cart') ); }

        // check if the $id already exists in it.
        if( isset($cart[$id]) ) {
            // if it does ++ the quantity
            $cart[$id]  = '0';
            unset($cart[$id]);
            //echo $cart[$id] ; die();
        } else {
            return $this->redirect( $this->generateUrl('cart') );
        }

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

        // redirect(index page)
        return $this->redirect( $this->generateUrl('cart') );
    }
}

Checkout/index.html.twig

{% extends '@Tuinadvies/base.html.twig' %}

{% block body %}
    <h1>Checkout</h1>
    {% if empty is defined %}
        <h5>Your shopping cart is empty.</h5>
    {% endif %}

    {% set cart = app.session.get('cart') %}


    {% if product is defined %}


        <ul class="thumbnails">
        {% if app.session.flashbag.has('notice') %}

            <div class="flash-notice">

                {{app.session.flashbag.has('notice') }}

            </div>

        {% endif %}
    <table class="table">
        <thead>
            <th>Product</th>
            <th>ID</th>
            <th>Amount</th>
            <th>Price (€)</th>
        </thead>
    {% for key, item, price in cart %}
        <tr class="col-span-6">
            <td><b>{{ name }}<b></td>
            <td>{{ key }}</td>
            <td>{{ item }}</td>
            <td>{{ price }}</td>
        </tr>
    {% endfor %}
    </table>

        {% endif %}

    <a href="{{ path('product_index') }}">Products</a>

{% endblock %}

cart/index.html.twig

{% extends '@Tuinadvies/base.html.twig' %}

{% block body %}
    <h1>Winkelwagentje</h1>
    <ul class="thumbnails">

        {% if empty is defined %}
            <h5>Your shopping cart is empty.</h5>
        {% endif %}
        {% set cart = app.session.get('cart') %}


        {% if product is defined %}


            <ul class="thumbnails">
                {% if app.session.flashbag.has('notice') %}

                    <div class="flash-notice">

                        {{app.session.flashbag.has('notice') }}

                    </div>

                {% endif %}
                {% for key, item in cart %}
                    <p>ID:{{ key }}</p>
                    <p>Quantity:{{ item }}</p>
                    <a href="{{ path('cart_remove', {'id': key}) }}">Remove</a>
                    <a href="{{ path('cart_checkout', {'id': key}) }}">checkout</a>


                {% endfor %}
            </ul>

        {% endif %}
    </ul>

    <a href="{{ path('product_index') }}">Products</a>

{% endblock %}

There might be a lot of spaghetti code (bad code) but that's because i'm a real newbie. so sorry about that!!!

Hope anyone can help me :)

Cheers

解决方案

It looks like you're fetching every checked out product from the database but overwriting it then on the $product variable instead of saving all of them.

You should use an array to store the different products and then use those products to fill the values in your twig template

So, in your checkout action you would have something like this:

$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('TuinadviesBundle:Product');

$products = [];
foreach ($cart as $id => $quantity) {
    $products[] = $repo->find($id);
}

Then, when rendering the template, just pass the $products array instead of the name and price.

return $this->render('@Tuinadvies/checkout/index.html.twig', array(
    'products' => $products,
));

And finally, in your twig template, instead of iterating over the cart, you would iterate over the products array and use it's id to get the right quantity

{% for product in products %}
    <tr class="col-span-6">
        <td><b>{{ product.name }}</b></td>
        <td>{{ product.id }}</td>
        <td>{{ cart[product.id] }}</td>
        <td>{{ product.price }}</td>
    </tr>
{% endfor %}

Hope this helps!

这篇关于Symfony 3 在我的结帐时正确获取价格和名称的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆