如何将jQuery与表中的字段相关联?

时间:2016-04-08 12:50:32

标签: php jquery symfony

我不确定我是以最好的方式问我的问题还是完全清楚,但我会尽我所能。

我的$quantity实体中有Quantity字段。然后在我的一个控制器中,我创建了一个类实体Quantity的实例,如下所示:$quantity = new Quantity();。最后我设置了这样的数量:$quantity->setQuantity(1);只是让事情变得有意义并且我的应用程序可以运行。

然后在我的twig文件中,我实现了jQuery数字微调器(https://jqueryui.com/spinner/)。我将quantity field(1)作为值放入。

然后在我的微调器脚本中,我试着这样做,所以当我点击或向下点击时,数据会在数据库中更新。我失败了。这是我需要帮助的。

最终,我想根据购物车中产品的数量更新用户购物车的总费用。

ProductController relevant functions

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

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

    $product = $em->getRepository('ShopBundle:Product')->find($id);
        $product->getId();
        $product->getName();
        $product->getPrice();
    $cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'submitted' => false]);
    // $quantity = $em->getRepository('ShopBundle:Quantity')->findOneBy(['id' => $this->getUser()]);

    if ($this->checkUserLogin()) {
        $this->addFlash('notice', 'Login to Create a Cart');
        return $this->redirectToRoute('product');
    }

    // --------------------- assign added products to userCart id ------------------------ //

    $quantity = new Quantity();

    if (is_null($cart) || $cart->getSubmitted(true)) {
        $cart = new UserCart();
    }

    $cart->setTimestamp(new \DateTime()); // Set Time Product was Added 
    $quantity->setQuantity(1);   // Set Quantity Purchased.......Make jQuery # Spinner the input of setQuantity()
    $cart->setSubmitted(false); // Set Submitted
    $cart->setUser($this->getUser());  // Sets the User ONCE
    $cart->addQuantity($quantity);    //  Add Quantity ONCE
    $quantity->setUserCart($cart);   //   Create a UserCart ONCE
    $quantity->setProduct($product); // Sets the Product to Quantity Association ONCE
    $em->persist($product);
    $em->persist($cart);
    $em->persist($quantity); 
    $em->flush();
    $this->addFlash('notice', 'The product: '.$product->getName().' has been added to the cart!');


return $this->redirectToRoute('product');

}

/**
 * Shows Empty Cart
 * 
 * @Route("/showCart", name="product_showCart")
 * @METHOD("GET")
 * @Template()
 */
public function showCartAction(Request $request) {

// --------------------------- show only what the user added to their cart --------------------------- //

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

    if ($this->checkUserLogin()) {
        $this->addFlash('notice', 'Login to Create a Cart');
        return $this->redirectToRoute('product');
    }

    // $product = $em->getRepository('ShopBundle:Product')->f

    $cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'submitted' => false]);

    // $productsInUsersCart = $em->getRepository('ShopBundle:Quantity')->findOneBy(['product' => $cart->getId()]);
    // dump($productsInUsersCart); die;
    // dump($cart); die;

    if (!$cart) {
        $this->addFlash('notice', 'There is NO CART');
        return $this->redirectToRoute('product');
    }

    $sub = $cart->getSubmitted();

    /**
     * Function in UserCart that Maps to Quantity where product values lives.
     *       $quantity is an object (ArrayCollection / PersistentCollection)
     */
    if ($sub == false) {
        $quantity = $cart->getQuantities();
    } else {
        $this->addFlash('notice', 'Cart should be EMPTY');
    }

    if (!$cart) {
        throw $this->createNotFoundException(
            'ERROR: You got past Gondor with an EMPTY CART'
        );
    }

    $totalCostOfAllProducts = 0;

    $totalCostOfAllProducts = $this->getTotalCost($cart, $totalCostOfAllProducts);

    if (empty($price) && empty($quantity) && empty($totalCostOfAllProducts)) {
        $price = 0; $quantity = 0; $totalCostOfAllProducts = 0;
    }

    return array(
        'user' => $cart->getUser(),         // for :UserCart
        'cart' => $cart,
        'quantity' => $cart->getQuantities(),         // for :UserCart
        // 'quantity' => $quantity,         // for :UserCart
        'totalCostOfAllProducts'    => $totalCostOfAllProducts,
    );
}

twig file where jQuery spinner script is(唯一有效的是jQuery微调器增加或减少数字......没有别的):

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

{% block body %}

<h1 class="text-center"><u><i>Your Cart</i></u></h1>

    <div class="container">

        <div class="who_is_logged_in">
            {% if user is null %}
                <a href="{{ path ('fos_user_security_login') }}">Login</a>
            {% else %}
                <u>Hello<strong> {{ user }}</strong></u>
            {% endif %}
        </div>

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

            <tbody>
            {% for key, product in quantity %}  
                    <tr>
                        <td>{{ product.product }}</td> <!--Product-->
                        <td>
                            <input class="spinner" value="{{ product.quantity }}" style="width:30px">
                        </td> <!--Quantity-->
                        <td>${{ product.product.price|default('') }}</td> <!--Price-->   
                        <td>
                            <a href="{{ path('product_remove', {'id': product.product.id }) }}">
                                <button name="REMOVE" type="button" class="btn btn-danger" id="removeButton">
                                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                                </button>
                            </a>
                        </td><!--Remove--> 
                    </tr>
                {% endfor %}      
            </tbody>
        </table> <!--top table-->

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

        {% for flash_message in app.session.flashbag.get('notice') %}
            <div class="flash-notice">
                <strong>{{ flash_message }}</strong>
            </div> <!--flashNotice-->
        {% endfor %}

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


    <ul>
        <li>
            <a href="{{ path('product') }}">
                Add More Products
            </a>
        </li>

    {#    {% if cartArray is empty %}   #}
    {#    {% else %}                    #}
            <li>
                <a href="{{ path('product_bought') }}">
                    Buy These Products
                </a>
            </li>
    {#  {% endif %}                     #}

    </ul>

<script type="text/javascript">
 $(".spinner").spinner();
    $('input.spinner').on('change', function(){
        var $this = $(this);
        $.ajax({
            url: '{{ path('product_showCart') }}',
            method: 'POST',
            data : {
                quantity: $this.val()
            }
        }).done(function(resp){
            console.log('success', resp);
        }).error(function(err){
            console.log('error', resp);
        });
    });
</script>


{% endblock %}

showCart screenshot

quantity table screenshot

如果你不能说我是jQuery / web开发的新手,但我每天都在学习。我真的可以使用一些帮助/指导!

编辑:

我将我的脚本更改为此,现在我在控制台中看到了我的消息,但数据库中仍未更新/更改任何内容,当我刷新页面时,数量会返回显示&#39; 1&#39;。

<script type="text/javascript">
 $(".spinner").spinner();
    $('input.spinner').on('spinstop', function(){
        console.log('spinner changed');
        var $this = $(this);
        $.ajax({
            url: "{{ path('product_showCart') }}",
            method: 'GET',
            data : {
                quantity: $this.val()
            }
        }).done(function(resp){
            console.log('success', resp);
        }).error(function(err){
            console.log('error', resp);
        });
    });
</script>

0 个答案:

没有答案