Woocommerce Mini Cart Widget product price override - javascript

is it possible to change product price in Woocommerce Mini Cart Widget? I've overrided price in cart using tips from WooCommerce: Add product to cart with price override? but it only works for cart page. Prices in widget are not changed.

Instead of using "woocommerce_before_calculate_totals" you can use "woocommerce_cart_item_price" filter, some thing like
add_filter('woocommerce_cart_item_price','modify_cart_product_price',10,3);
function modify_cart_product_price( $price, $cart_item, $cart_item_key){
$price = wc_price($custom_price, 4);
return $price;
}

This is how I set price to 0 for free products:
function set_free_items_price( $price, $cart_item, $cart_item_key ) {
$returned_item_price = $cart_item['data']->get_price();
if (isset($cart_item['free_item']['value'])
&& $cart_item['free_item']['value'] == true) {
$returned_item_price = 0;
}
return get_woocommerce_currency_symbol() . $returned_item_price;
}
I hooked inside class, so it hook looks like this:
add_filter( 'set_free_items_price', array(__CLASS__, 'woocommerce_cart_item_price_filter'), 10, 3 );
But if you are using it as procedural function, your hook should look like this:
add_filter( 'set_free_items_price', 'woocommerce_cart_item_price_filter', 10, 3 );
Keep in mind this is also affecting price row in regular cart.
And, if you are not seeing changes in mini cart, try to update cart on regular cart page, and the go back and check again if mini-cart values has been changed.

To change the price on the WooCommerce Mini Cart Widget you have to use this filter hook: woocommerce_widget_cart_item_quantity
You can check the line 63 of the file: woocommerce/templates/cart/mini-cart.php to see how the filter hook is created.
apply_filters( 'woocommerce_widget_cart_item_quantity', '<span class="quantity">' . sprintf( '%s × %s', $cart_item['quantity'], $product_price ) . '</span>', $cart_item, $cart_item_key );
As the name of the filter hook indicates it can be used not only for the price but also to show the quantity.
For example you can use it to apply a discount to certain products based on a condition. In this case I used a value stored in the meta data of the product.
add_filter('woocommerce_widget_cart_item_quantity', 'custom_wc_widget_cart_item_quantity', 10, 3 );
function custom_wc_widget_cart_item_quantity( $output, $cart_item, $cart_item_key ) {
$product_id = $cart_item['product_id'];
// Use your own way to decide which product's price should be changed
// In this case I used a custom meta field to apply a discount
$special_discount = get_post_meta( $product_id, 'special_discount', true );
if ($special_discount) {
$price = $cart_item['data']->get_price();
$final_price = $price - ( $price * $special_discount );
// The final string with the quantity and price with the discount applied
return sprintf( '<span class="quantity">%s × <span class="woocommerce-Price-amount amount">%s <span class="woocommerce-Price-currencySymbol">%s</span></span></span>', $cart_item['quantity'], $final_price, get_woocommerce_currency_symbol() );
} else {
// For the products without discount nothing is done and the initial string remains unchanged
return $output;
}
}
Note that this will only change how price is displayed, if you have to change it internally use also this action hook: woocommerce_before_calculate_totals

Related

Price inside Add to Cart shows only when there is a Sale Price

I'm using script to add the price to the Add to Cart in WooCommerce but for some reason the script seems to break when there aren't any variations set with a 'sale price'.
Would anyone have an idea why this is breaking? I have tried it in and outside of the button but experiencing the same issue. There are no errors in the console to reference.
Example of what is happening: https://i.stack.imgur.com/f6beM.jpg
<?php
add_action( 'woocommerce_after_add_to_cart_form', 'bbloomer_echo_variation_info' );
function bbloomer_echo_variation_info() {
global $product;
if ( ! $product->is_type( 'variable' ) ) return;
$attributes = $product->get_variation_attributes();
wc_enqueue_js( "
$(document).on('found_variation', function( event, variation ) {
$('.pricePoint').html(variation.price_html);
});
" );
}
?>
<button type="submit" class="pricePoint single_add_to_cart_button button alt" title="Add to Cart"></button>
Thank you!
I was able to work out the fix:
I just needed to add this to the function as the "price_html" was not being displayed by default.
add_filter( 'woocommerce_show_variation_price', '__return_true' );

Handle WooCommerce selected variation custom field conditional display

I have this code where I need to insert a value based on a condition in: **///////// HERE THE MY CODE /////////**
Here I have overridden single-product/add-to-cart/variation.php Woocommerce template file via my active theme:
<script type="text/template" id="tmpl-variation-template">
<div class="woocommerce-variation-description">
{{{ data.variation.variation_description }}}
</div>
<div class="woocommerce-variation-price">
{{{ data.variation.price_html }}}
</div>
<div class="woocommerce-variation-custom_field">
{{{ data.variation.custom_field}}}
///////// HERE MY CODE /////////
</div>
<div class="woocommerce-variation-availability">
{{{ data.variation.availability_html }}}
</div>
</script>
The condition should check the value of the variable `{{{ data.variation.custom_field}}}` and if this data is greater than 10 then the code should print "Yes".
**Something like**:
if( $data.variation.custom_field > 10 ){
echo "yes";
}
But it's not working. I guess, this should be done using Javascript instead of php but I don't know how grab the variable value.
There is no need to use additional javascript (or jQuery) code for that.
The following will handle a product variation custom field displaying "YES" if the custom field value is bigger than 10 (otherwise nothing).
You will need to replace your exiting hooked function that use woocommerce_available_variation hook, with one of the following ways.
There are mainly 2 ways:
1). The simplest way, without overriding variation.php template:
// Frontend: Handle Conditional display and include custom field value on product variation
add_filter( 'woocommerce_available_variation', 'variation_data_custom_field_conditional_display', 10, 3 );
function variation_data_custom_field_conditional_display( $data, $product, $variation ) {
// Get custom field value and set it in the variation data array (not for display)
$data['custom_field'] = $variation->get_meta('custom_field');
// Defined custom field conditional display
$displayed_value = $data['custom_field'] > 10 ? 'YES' : '';
// Frontend variation: Display value below formatted price
$data['price_html'] .= '</div>' . $displayed_value . '
<div class="woocommerce-variation-custom_field_html">';
return $data;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
2). Another simple way (overriding variation.php template):
// Frontend: Handle Conditional display and include custom field value on product variation
add_filter( 'woocommerce_available_variation', 'variation_data_custom_field_conditional_display', 10, 3 );
function variation_data_custom_field_conditional_display( $data, $product, $variation ) {
// Get custom field value and set it in the variation data array (not for display)
$data['custom_field'] = $variation->get_meta('custom_field');
// Frontend display: Define custom field conditional display
$data['custom_field_html'] = $data['custom_field'] > 10 ? "YES" : "";
return $data;
}
Code goes in functions.php file of the active child theme (or active theme).
Then in your custom template single-product/add-to-cart/variation.php you will replace:
{{{ data.variation.custom_field}}}
with:
{{{ data.variation.custom_field_html }}}
It will work nicely without any additional requirements.
Here is a complete code example for the community, based on the 2nd Way:
1). Admin variations: Display a custom field and save it's value
// Admin: Add a custom field in product variations options pricing
add_action( 'woocommerce_variation_options_pricing', 'add_admin_variation_custom_field', 10, 3 );
function add_admin_variation_custom_field( $loop, $variation_data, $variation ){
woocommerce_wp_text_input( array(
'id' => 'custom_field['.$loop.']',
'label' => __('Custom Field', 'woocommerce' ),
'placeholder' => __('Enter Custom Field value here', 'woocommerce' ),
'desc_tip' => true,
'description' => __('This field is for … (explanation / description).', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'custom_field', true )
) );
}
// Admin: Save custom field value from product variations options pricing
add_action( 'woocommerce_save_product_variation', 'save_admin_variation_custom_field', 10, 2 );
function save_admin_variation_custom_field( $variation_id, $i ){
if( isset($_POST['custom_field'][$i]) ){
update_post_meta( $variation_id, 'custom_field', sanitize_text_field($_POST['custom_field'][$i]) );
}
}
Code goes in functions.php file of the active child theme (or active theme).
2). Frontend variations: Conditional display based on selected variation and custom field value
// Frontend: Handle Conditional display and include custom field value on product variation
add_filter( 'woocommerce_available_variation', 'variation_data_custom_field_conditional_display', 10, 3 );
function variation_data_custom_field_conditional_display( $data, $product, $variation ) {
// Get custom field value and set it in the variation data array (not for display)
$data['custom_field'] = $variation->get_meta('custom_field');
// Frontend display: Define custom field conditional display
$data['custom_field_html'] = $data['custom_field'] > 10 ? __("YES", "woocommerce") : "";
return $data;
}
Code goes in functions.php file of the active child theme (or active theme).
3). Template override: single-product/add-to-cart/variation.php file to your active theme's:
<?php
/**
* Single variation display
*
* This is a javascript-based template for single variations (see https://codex.wordpress.org/Javascript_Reference/wp.template).
* The values will be dynamically replaced after selecting attributes.
*
* #see https://docs.woocommerce.com/document/template-structure/
* #package WooCommerce/Templates
* #version 2.5.0
*/
defined( 'ABSPATH' ) || exit;
?>
<script type="text/template" id="tmpl-variation-template">
<div class="woocommerce-variation-description">{{{ data.variation.variation_description }}}</div>
<div class="woocommerce-variation-price">{{{ data.variation.price_html }}}</div>
<div class="woocommerce-variation-custom_field">{{{ data.variation.custom_field_html}}}</div>
<div class="woocommerce-variation-availability">{{{ data.variation.availability_html }}}</div>
</script>
<script type="text/template" id="tmpl-unavailable-variation-template">
<p><?php esc_html_e( 'Sorry, this product is unavailable. Please choose a different combination.', 'woocommerce' ); ?></p>
</script>
Tested and works.
Related: WooCommerce: Add/display Product or Variation custom field everywhere
Based on https://codex.wordpress.org/Javascript_Reference/wp.template and similar template engine like https://github.com/blueimp/JavaScript-Templates#evaluation, you need to build a template with evaluation.
In your case, it should be something like:
<div class="woocommerce-variation-custom_field">
<# if (data.variation.custom_field > 10) { #>
yes
<# } #>
</div>
Also, here https://lkwdwrd.com/wp-template-js-templates-wp you can find an example with if statement itself.

Woocommerce: Detect where Add to Cart button was clicked and run different code

In the ecommerce store:
There are items displayed on Homepage and each of the items have an "Add to Cart" button underneath them. When this button is clicked, the item is added to cart. If this button is clicked again, the Quantity of the item that is already existing in cart, is incremented by 1. I believe this is the loop. So far, so good.
On the Single Product page, there is an "Add to Cart" button. When this button is clicked, the item gets added to cart. There is a Quantity input textbox as well that can be used to change the quantity. This is fine too.
THE ISSUE:
I need to differentiate between the "Add to Cart" button that was clicked within the loop (currently on Homepage, but can also be used on other pages such as Archive page, etc.) vs the "Add to Cart" button that was clicked on the Single Product page. Based on this differentiation, here is what I need to do:
If the "Add to Cart" button appearing within the loop was clicked, grab the Quantity of this item that is already existing in cart using the $cart_item_key, increment it by 1 and send this to a custom function that will do additional processing and save the details to cart again.
If the "Add to Cart" button appearing in the Single Product page was clicked, grab the Quantity of this item that is already existing in cart using the $cart_item_key, multiply it by 3 and send this to a custom function that will do additional processing and save the details to cart again.
In both the above cases, the Quantity is being changed, based on different logics and this Quantity needs to be sent to a custom function call.
WHAT I TRIED:
I tried the following code:
add_action('woocommerce_add_to_cart', 'custom_action_add_to_cart', 20, 6);
function custom_action_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data)
{
$cart = WC()->cart->get_cart();
$product = wc_get_product($product_id);
// NEED TO RUN CUSTOM CODE HERE BASED ON THE CHECKS
if (add to cart within loop is clicked) {
// Get existing $quantity_from_cart from cart using $cart_item_key, but how????
$new_quantity = $quantity_from_cart + 1;
}
else if (add to cart on single product page is clicked) {
// Get existing $quantity_from_cart from cart using $cart_item_key, but how????
$new_quantity = $quantity_from_cart * 3;
}
// Need to send the $new_quantity along with the $cart_item_key to the custom function so that the data can be saved using $cart_item_key
my_custom_function($new_quantity, $cart_item_key);
}
function my_custom_function($new_quantity, $cart_item_key)
{
echo $new_quantity;
WC()->cart->cart_contents[$cart_item_key]['custom_quantity'] = $new_quantity;
WC()->cart->set_session();
}
The issue with the above code is that it if I don't have the if... else if... logic, then the code is executed regardless of where the "Add to Cart" button is located. In other words, whether I click the "Add to Cart" button that is located in the loop (Homepage, Archive page or any page that uses the loop) or I click the "Add to Cart" button located in the Single Product page, the above code gets executed in the absence of the if... else if... logic.
So, I want to run separate code when the "Add to Cart" button that is located in the loop is clicked (regardless of its location, whether Homepage, Archives, etc.) and run different code when the "Add to Cart" button that is located on the Single Product page is clicked. How can I achieve this?
Expecting something like this:
If button appearing inside the loop is clicked -> Do this.
If button appearing in Single Product page is clicked -> Do that.
you can use wp_get_referer or check_ajax_referer() for example:
function custom_action_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data)
{
$cart = WC()->cart->get_cart();
$product = wc_get_product($product_id);
$referer = wp_get_referer();
// HOMEPAGE
if (strpos($referer ,'http://yourwebsite.com/') !== false) {
$new_quantity = $quantity_from_cart + 1;
}
//from some product page like http://yourwebsite.com/product/my-product-page
else if (strpos($referer ,'http://yourwebsite.com/product/') !== false) {
$new_quantity = $quantity_from_cart * 3;
}
// Need to send the $new_quantity along with the $cart_item_key to the custom function so that the data can be saved using $cart_item_key
my_custom_function($new_quantity, $cart_item_key);
}
Please refer: Wordpress Nonces related functions
You can try this way:
add_action('woocommerce_add_to_cart', 'custom_action_add_to_cart', 20, 6);
function custom_action_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
$cart = WC()->cart->get_cart();
$product = wc_get_product($product_id);
$referer = $_SERVER['HTTP_REFERER'];
$route = parse_url( $referer );
$path = $route['path'] ?? 'home' ;
$args = array_filter( ( explode('/', $path) ) );
if (in_array( 'product', $args) ) {
// Product Page
} elseif (in_array('product-category', $args)) {
// Product Category
} else {
// Default
}
}
But you need check your settings. Settings > Permalinks.
you can use is_product(),is_product_category() function
function custom_action_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data)
{
$cart = WC()->cart->get_cart();
$product = wc_get_product($product_id);
if ( is_product() ) {
global $product;
$id = $product->get_id();
foreach ( WC()->cart->get_cart() as $cart_item ) {
if($cart_item['product_id'] == $id ){
$quantity_from_cart = $cart_item['quantity'];
break; // stop the loop if product is found
}
}
$new_quantity = $quantity_from_cart * 3;
}
else if (is_product_category()) {
$new_quantity = $quantity_from_cart + 1;
}
my_custom_function($new_quantity, $cart_item_key);
}
There are couple solutions I could think of. But here's one:
add_action( 'woocommerce_after_add_to_cart_button', 'rmg_woocommerce_after_add_to_cart_button' );
function rmg_woocommerce_after_add_to_cart_button() {
$button_location = 0;
// if (is_home() || is_front_page()) {
// // we're at the home page
// $button_location = 1;
// }
if (is_product()) {
// where at product page
$button_location = 2;
} else {
// pages other than product page
$button_location = 1;
}
echo '<input type="hidden" name="button-location" value="'. $button_location .'" />';
}
We could add an hidden input inside the form, that above code does it.
Then could check it's value like:
$button_location = $_REQUEST['button-location'];
if ($button_location && $button_location === 2) {
// add to cart button clicked at or came from product page..
$new_quantity = $quantity_from_cart + 1;
}
Please note that this is just an idea and not a complete solution... You need to take care of the ajax button.

How to auto-populate sub-field selects from within a parent field

I'm using the ACF tutorial here to build from.
What I'd like to do is use the values in a text sub-field to populate other select sub-fields within the same repeater field. I know it sounds recursive and maybe that's prohibitive. The field admin will not be to ajax-y or update on the fly, it's more of an admin field for other site functionality.
Anyway, here's what I have so far.
ACF Repeater field = core_values
Page the field is on = valuesadmin
Source text sub-field within core_values = value_name
Target sub-fields (
each needing dynamically propagated selects from value_name) =
constructor1_name
constructor2_name
constructor3_name
destructor1_name
destructor2_name
I've tried to modify the code at the tutorial linked above and put it in the theme's functions.php and in the main file of a plugin I'm building other custom functions.
/**
* ACF population functions
*/
function acf_load_core_values_field_choices( $field ) {
// reset choices
$field['choices'] = array();
// if has rows
if( have_rows('core_values', 'valuesadmin') ) {
// while has rows
while( have_rows('core_values', 'valuesadmin') ) {
// instantiate row
the_row();
// vars
$value = get_sub_field('value_name');
$label = get_sub_field('value_name');
// append to choices
$field['constructor1_name'][ $value ] = $label;
$field['constructor2_name'][ $value ] = $label;
$field['constructor3_name'][ $value ] = $label;
$field['destructor1_name'][ $value ] = $label;
$field['destructor2_name'][ $value ] = $label;
}
}
// return the field
return $field;
}
add_filter('acf/load_field/name=constructor1_name', 'acf_load_core_values_field_choices');
add_filter('acf/load_field/name=constructor2_name', 'acf_load_core_values_field_choices');
add_filter('acf/load_field/name=constructor3_name', 'acf_load_core_values_field_choices');
add_filter('acf/load_field/name=destructor1_name', 'acf_load_core_values_field_choices');
add_filter('acf/load_field/name=destructor2_name', 'acf_load_core_values_field_choices');
Obviously this isn't propagating the select sub-fields as I'd like.
Questions:
- Is this even possible ( the value_name fields are all filled with values already )
- Where should the function code go?
- Maybe I've mangled the code somehow
Thanks in advance!
Well, I achieved the functionality I was looking for by first moving this all to an ACF options page and then creating another ACF field ( values_master) with which I could populate the values dynamically in a second field on the options page. So I'm not sure if this was not working because of some recursively but it IS working.
function acf_load_value_field_choices( $field ) {
// reset choices
$field['choices'] = array();
// if has rows
if( have_rows('values_master', 'option') ) {
// while has rows
while( have_rows('values_master', 'option') ) {
// instantiate row
the_row();
// vars
$value = get_sub_field('value_name');
$label = get_sub_field('value_name');
// append to choices
$field['choices'][ $value ] = $label;
}
}
// return the field
return $field;
}
add_filter('acf/load_field/name=constructor1_name', 'acf_load_value_field_choices');
add_filter('acf/load_field/name=constructor2_name', 'acf_load_value_field_choices');
add_filter('acf/load_field/name=constructor3_name', 'acf_load_value_field_choices');
add_filter('acf/load_field/name=destructor1_name', 'acf_load_value_field_choices');
add_filter('acf/load_field/name=destructor2_name', 'acf_load_value_field_choices');
add_filter('acf/load_field/name=value_mstr_name', 'acf_load_value_field_choices');

Symfony2 need some clearness and guidance with a shopping cart (regarding the quantities)

So I have a shopping cart. I can add, delete and view the products in the cart. The problem now comes with increasing and decreasing the quantities. If for example the user wants to buy more than one of the same product.
BACKGROUND:
There are two ways on how you can increase your quantity:
You can increase it every time you add a product from its details page. This part works and im doing this like here:
if( isset($cart[$id]) ) {
$qtyAvailable = $product->getStock();
if ( $qtyAvailable > $cart[ $id ]) {
$cart[ $id ] = $cart[ $id ] + 1;
} else {
return $this->redirect($this->generateUrl('cart'));
}
} else {
// if it doesnt make it 1
$cart = $session->get('cart', array());
$cart[$id] = 1;
}
What is the $cart here?
AS you can see I am checking if the id of the product already exists in the cart. If it does then increase its value. My array Cart only has one key which is and id of the product and I increase the ids value everytime I add the same product.
The other way is to increase the quantity in the cart itself with the buttons +,-. I am stuck at this part.
I am guessing there are two ways I can increase the quantity here, either by using javascript or writing the similar function like on the top(i prefer this one). Since I am not used to javascript the only way I think i can do this is by writing this:
<div class="input-append"><input class="span1" style="max-width:34px" placeholder="{{ key }}" id="appendedInputButtons" size="16" type="text">
<button class="btn" type="button" name="add" onclick='javascript: document.getElementById("appendedInputButtons").value++;'><i class="icon-minus"></i></button>
<button class="btn" type="button" name='subtract' onclick='javascript: document.getElementById("appendedInputButtons").value--;'><i class="icon-plus"></i></button>
However this only changes the number on the screen, it doesnt increase or decrease in the array itself. Maybe there is a way you can change the array values with javascript?
UPDATE
Ok so I am trying to understand the code one of the StackOverflow users have provided, however I am getting some problems.
So in my twig I have made this:
<div class="input-append"><input class="span1" style="max-width:34px" name="quantity" placeholder="{{ key }}" id="appendedInputButtons" size="16" type="text" data-id="12">
<button class="btn" type="submit" value="increase"><a href="javascript:void(0)" class="plus"><i class="icon-minus"></i></button>
<button class="btn" type="button"><i class="icon-plus"></i></button>
Then in my controller i done like in the example:
/**
* #Route("/cart/update", name="cart_update")
*/
public function cartUpdateAction( Request $request )
{
$response = new JsonResponse();
$requestData = $request->request->all();
$productid = $requestData['product'];/** first put all validations not empty/ is numeric and exists in your db etc*/
$quantity = $requestData['quantity'];/** first put all validations not empty/ is numeric etc */
/** if all is good then put your logic*/
$product = $em->getRepository('MpShopBundle:Product')->find($productid);
$qtyAvailable = $product->getStock();
$session = $this->getRequest()->getSession();
$cart = $session->get('cart', array());
if ( $qtyAvailable > $cart[ $productid ] ) {
$cart[ $productid ] = $cart[ $productid ] + 1;
$response->setData(array('success'=>true,'message'=>'Qunatity increased'));
} else {
$response->setData(array('success'=>false,'message'=>'Out of stock'));
}
return $response;
}
Now I am having problems on where do I have to write the javascript code? I read that you have to create a new .js file and add it with assetic, so I did it like this:
I have added the jquery library and my ajax script file to assets in my base.twig.html file like this:
{% block javascripts %}
{# Le Javascript #}
{% javascripts
'bundles/mpFrontend/assets/js/jquery-1.11.2.min.js'
'Mp/ShopBundle/Resources/js/scripts.js'
%}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
And then I extend the base.html.twig in the twig that I want to use the ajax.
However nothing happens when I press the button. SO the ajax code is added wrong probably?
You can use jQuery and Ajax to pick and post values to server you have to include the library first in order to use .
sample markup will be each item has its own container one input either text or hidden if you are using any js effect to increment quantity make sure this input gets updated each time increment or decrement action performed by user
<div class="item">
<input type="text" data-id="product id here" />
+
-
</div>
<div class="item">...</div>
<div class="item">...</div>
initialize click handler for anchor with class plus so that you can post values to server to update your cart array
$('.plus').on('click', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'server side action url here',// /cart/update
async: false,
dataType: 'JSON',
data: {product: $this.parent('.item').find('input').data('id'),quantity: $this.parent('.item').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}
}
});
});
On your server side action just a sample code for increment quantity if you get the idea you can implement same for decrement scenario
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request; /** At the top of your controller*/
/**
* #Route("/cart/update", name="cart_update")
*/
public function cartUpdateAction( Request $request ) {
$response = new JsonResponse();
$requestData = $request->request->all();
$productid = $requestData['product'];/** first put all validations not empty/ is numeric and exists in your db etc*/
$quantity = $requestData['quantity'];/** first put all validations not empty/ is numeric etc */
/** if all is good then put your logic*/
$product = $em->getRepository('MpShopBundle:Product')->find($productid);
$qtyAvailable = $product->getStock();
$session = $this->getRequest()->getSession();
$cart = $session->get('cart', array());
if ( $qtyAvailable > $cart[ $productid ] ) {
$cart[ $productid ] = $cart[ $productid ] + 1;
$response->setData(array('success'=>true,'message'=>'Qunatity increased'));
} else {
$response->setData(array('success'=>false,'message'=>'Out of stock'));
}
return $response;
}

Categories