Symfony2更改项目的值并将其保存在后端

时间:2015-05-08 11:08:27

标签: php arrays symfony

我需要创建一个函数来更改从后端获取的值并将新值发送回后端...

这是我到目前为止创造的。我得到了产品的当前库存(在我的例子中是50):然后我只是检查库存是否大于产品的数量,如果是,我将该数量增加1,并从库存中删除1个值。最后,我保存了购物车,我保存了新的库存(我认为)。然而,这不起作用,我的股票仍然有50个。

public function addAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $product = $em->getRepository('MpShopBundle:Product')->find($id);       
        $qtyAvailable = $product->getStock();
       // check the cart
        $session = $this->getRequest()->getSession();
        $cart = $session->get('cart', array());

          if( isset($cart[$id]) ) {  // Check if the array has this productId

                if ( $qtyAvailable > $cart[ $id ]) { 
                    $cart[ $id ] = $cart[ $id ] + 1;
                    $qtyAvailable = $qtyAvailable - 1;
                } else {

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


        } else {
            // if it doesnt make it 1
            $cart = $session->get('cart', array());
            $cart[$id] = 1;
        }
        $product->setStock('qtyAvailable', $qtyAvailable);
        $session->set('cart', $cart);
        return $this->redirect( $this->generateUrl('cart') );
    } 

2 个答案:

答案 0 :(得分:1)

通常您只需要将值赋予教条实体设置器。

$product->setStock('qtyAvailable', $qtyAvailable);

应该是

$product->setStock($qtyAvailable);

如果您在setStock()方法中没有任何自定义代码。

此外,您需要致电

$em->persist($product);
$em->flush(); // this runs the query on the database.

设置新库存后。

答案 1 :(得分:0)

你没有忘记添加:

$em->persist($product);

$em->flush();

为了保存您对产品对象所做的更改?