Symfony 3在结账时获得价格和名称的问题

时间:2017-06-28 17:28:25

标签: php symfony twig

我的购物车出了问题。我是编码的新手,我无法正确使用这些东西。 所以。我的问题是:

我做了一个"网上商店" a:产品清单/购物车/结账。

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

这是我的代码:

CartController(带结账功能)

<?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') );
    }
}

结帐/ 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 %}

车/ 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 %}

可能会有很多意大利面条代码(不良代码),但那是因为我是一个真正的新手。对不起啊!!!

希望有人能帮助我:)。

干杯

1 个答案:

答案 0 :(得分:2)

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

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

因此,在您的结帐操作中,您将拥有以下内容:

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

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

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

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

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

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

希望这有帮助!