public function addProductAction()
{
$request = $this->get('request');
$params = $request->get('add_basket');
if ($request->getMethod() != 'POST') {
throw new MethodNotAllowedException(array('POST'));
}
// retrieve the product
$product = $this->get('sonata.product.set.manager')->findOneBy(array('id' => $params['productId']));
if (!$product) {
throw new NotFoundHttpException(sprintf('Unable to find the product with id=%d', $params['productId']));
}
// retrieve the custom provider for the product type
$provider = $this->get('sonata.product.pool')->getProvider($product);
$formBuilder = $this->get('form.factory')->createNamedBuilder('add_basket', 'form', null, array('data_class' => $this->container->getParameter('sonata.basket.basket_element.class'), 'csrf_protection' => false));
$provider->defineAddBasketForm($product, $formBuilder);
// load and bind the form
$form = $formBuilder->getForm();
$form->bind($request);
// if the form is valid add the product to the basket
if ($form->isValid()) {
$basket = $this->get('sonata.basket');
$basketElement = $form->getData();
$quantity = $basketElement->getQuantity();
$currency = $this->get('sonata.basket')->getCurrency();
$price = $provider->calculatePrice($product, $currency, true, $quantity);
if ($basket->hasProduct($product)) {
$basketElement = $provider->basketMergeProduct($basket, $product, $basketElement);
} else {
$basketElement = $provider->basketAddProduct($basket, $product, $basketElement);
}
$this->get('sonata.basket.factory')->save($basket);
if ($request->isXmlHttpRequest() && $provider->getOption('product_add_modal')) {
return $this->render('SonataBasketBundle:Basket:add_product_popin.html.twig', array('basketElement' => $basketElement, 'locale' => $basket->getLocale(), 'product' => $product, 'price' => $price, 'currency' => $currency, 'quantity' => $quantity, 'provider' => $provider));
}
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
// an error occur, forward the request to the view
return $this->forward('SonataProductBundle:Product:view', array('productId' => $product, 'slug' => $product->getSlug()));
}