Laravel post data - php

I am adding a order on my database with diferent taxes and I was suprise with this function that work prefectly on local envoirement is not working wen I deploy the website $tva6, $tva10 and $tva20 still 0.
$tva6 = 0;
$tva10 = 0;
$tva20 = 0;
$cart = session('orderList.orderList');
foreach ($cart as $item){
if ($item['tva'] === 6){
$tva6 += ($item['price'] * $item['qty']);
}
if ($item['tva'] === 10){
$tva10 += ($item['price'] * $item['qty']);
}
if ($item['tva'] === 20){
$tva20 += ($item['price'] * $item['qty']);
}
}
$tva6 = $tva6 - ($tva6 / 1.055);
$tva10 = $tva10 - ($tva10 / 1.1);
$tva20 = $tva20 - ($tva20 / 1.2);
$total = session('orderList.deliSup') + session('DBcart.totalPrice');
$order = Order::create([
"user_id"=>Auth::id(),
"orderId"=>session('orderList.orderIdNaga'),
"orderList"=>session('orderList.orderList'),
"payMethod"=>session('orderList.payMethod'),
"utensils"=>session('orderList.utensils'),
"infoOrder"=>session('orderList.infoOrder'),
"totalPrice"=>$total,
"tva6"=>$tva6,
"tva10"=>$tva10,
"tva20"=>$tva20,
"deliSup"=>session('orderList.deliSup'),
"deliTime"=>session('orderList.deliTime'),
"deliDate"=>session('orderList.deliDate')
]);
Any idea ? thx
edit: $cart is a array with product infos

Maybe $item['tva'] is not integer, use intval for example
foreach ($cart as $item) {
if (intval($item['tva']) === 6) {
$tva6 += ($item['price'] * $item['qty']);
}
}

Try debugging $cart to see if the session is actually returning the array you expect.
Otherwise, check the script where the session is generated, as the problem may be there.
If I'm right in my thinking above. send us the script where the session is generated.

Related

How to save multiple products details in one row in the database?(laravel)

I'm new to the laravel community but have to make a quick fix for my eCommerce website,
Currently, I have an OrderController that saves information to the database after Checking out,
The problem is, The Current Controller saves multiple products purchase at one time in multiple
new Order Columns in the Database I have been trying to fix on my own for a couple of days now without fully learning laravel as my website is live and I can't spend time learning Laravel.
This is The Code Block That fetches & saves Order details in the Controller:
public function store(Request $request)
{
$carts = Cart::where('user_id', Auth::user()->id)
->get();
if ($carts->isEmpty()) {
flash(translate('Your cart is empty'))->warning();
return redirect()->route('home');
}
$shipping_info = Address::where('id', $carts[0]['address_id'])->first();
$shipping_info->name = Auth::user()->name;
$shipping_info->email = Auth::user()->email;
if ($shipping_info->latitude || $shipping_info->longitude) {
$shipping_info->lat_lang = $shipping_info->latitude . ',' . $shipping_info->longitude;
}
$seller_products = array();
foreach ($carts as $cartItem){
$product_ids = array();
$product = Product::find($cartItem['product_id']);
if(isset($seller_products[$product->user_id])){
$product_ids = $seller_products[$product->user_id];
}
array_push($product_ids, $cartItem);
$seller_products[$product->user_id] = $product_ids;
}
//Order Details Storing
foreach ($seller_products as $cartItem) {
$product = Product::find($cartItem['product_id']);
$subtotal += $cartItem['price'] * $cartItem['quantity'];
$tax += $cartItem['tax'] * $cartItem['quantity'];
$coupon_discount += $cartItem['discount'];
$product_variation = $cartItem['variation'];
$product_stock = $product->stocks->where('variant', $product_variation)->first();
if ($product->digital != 1 && $cartItem['quantity'] > $product_stock->qty) {
flash(translate('The requested quantity is not available for ') . $product->getTranslation('name'))->warning();
$order->delete();
return redirect()->route('cart')->send();
} elseif ($product->digital != 1) {
$product_stock->qty -= $cartItem['quantity'];
$product_stock->save();
}
}
$order_detail = new OrderDetail;
$order_detail->order_id = $order->id;
$order_detail->seller_id = "$seller_products";
$order_detail->product_id = $product->id;
$order_detail->variation = $product_variation;
$order_detail->price = $cartItem['price'] * $cartItem['quantity'];
$order_detail->tax = $cartItem['tax'] * $cartItem['quantity'];
$order_detail->shipping_type = $cartItem['shipping_type'];
$order_detail->product_referral_code = $cartItem['product_referral_code'];
$order_detail->shipping_cost = $cartItem['shipping_cost'];
$shipping += $order_detail->shipping_cost;
if ($cartItem['shipping_type'] == 'pickup_point') {
$order_detail->pickup_point_id = $cartItem['pickup_point'];
}
//End of storing shipping cost
$order_detail->quantity = $cartItem['quantity'];
$order_detail->save();

A non well formed numeric value encountered in laravel 5.5

I have this code
private function calculateDefferedRevenue($price, $sub)
{
$defferedrevenue = '0.00';
if ($sub->has('fulfillment') && is_object($sub->fulfillment)) {
$fulfillments = $sub->fulfillment;
foreach ($fulfillments as $key => $fulfillment) {
if ($fulfillment->has('shipments') && !is_null($fulfillment->shipments)) {
$counts = self::countShipments($fulfillment->shipments);
if (!empty($price) && $counts['shipmentCount'] > 0) {
$shippingFee = self::getShippingFee($sub);
$shippingFees = $counts['unshippedCount'] * $shippingFee;
$price = self::deductUsingCoupon($price, $sub);
$eachShipmentAmount = $price / $counts['shipmentCount'];
$revenue = $eachShipmentAmount * $counts['unshippedCount'];
$revenue = $revenue + $shippingFees;
$defferedrevenue = $defferedrevenue + $revenue;
$defferedrevenue = number_format($defferedrevenue, 2);
}
}
}
}
return $defferedrevenue;
}
and these are the set of values return from sentry after running lines aboove in the laravel queue jobs
{
counts: {
shipmentCount: 4,
shippedCount: 1,
unshippedCount: 3
},
defferedrevenue: 1,049.25,
eachShipmentAmount: 349.75,
key: 1,
price: 1399.00,
revenue: 1049.25,
shippingFee: 0.00,
shippingFees: 0,
sub: Object Subscription
}
Why php is saying A non well formed numeric value encountered on this line
$defferedrevenue = $defferedrevenue + $revenue;
You're using number_format() here, which might add commas:
$defferedrevenue = $defferedrevenue + $revenue;
$defferedrevenue = number_format($defferedrevenue, 2);
So on the next loop iteration, you're likely getting something like:
$defferedrevenue = "1,234" + 1;
This generates a notice because "1,234" is a string that can't be automatically interpreted as a number. Just get rid of the number_format() line from inside the loop and put it after the loop ends:
return number_format($defferedrevenue, 2);

Stop multishipping from splitting orders in magento

The issue:
I need to stop the multishipping core module from splitting quantities into separate orders. I almost need it to act like Cart page, where I update quantity and it won't split them. I have a customer that may order 100 items (of the same thing) for one store and 20 for another. That then creates 120 separate orders and 120 lines to go through and add addresses.
I have searched everywhere and haven't found much help. Below I believe is the code that is associated with the splitting (core/Mage/Checkout/Model/Type/Multishipping). Also attached is what the issue is. Any direction is much appreciated.
ver 1.7
protected function _addShippingItem($quoteItemId, $data)
{
$qty = isset($data['qty']) ? (int) $data['qty'] : 1;
//$qty = $qty > 0 ? $qty : 1;
$addressId = isset($data['address']) ? $data['address'] : false;
$quoteItem = $this->getQuote()->getItemById($quoteItemId);
if ($addressId && $quoteItem) {
/**
* Skip item processing if qty 0
*/
if ($qty === 0) {
return $this;
}
$quoteItem->setMultishippingQty((int)$quoteItem->getMultishippingQty()+$qty);
$quoteItem->setQty($quoteItem->getMultishippingQty());
$address = $this->getCustomer()->getAddressById($addressId);
if ($address->getId()) {
if (!$quoteAddress = $this->getQuote()->getShippingAddressByCustomerAddressId($address->getId())) {
$quoteAddress = Mage::getModel('sales/quote_address')->importCustomerAddress($address);
$this->getQuote()->addShippingAddress($quoteAddress);
}
$quoteAddress = $this->getQuote()->getShippingAddressByCustomerAddressId($address->getId());
if ($quoteAddressItem = $quoteAddress->getItemByQuoteItemId($quoteItemId)) {
$quoteAddressItem->setQty((int)($quoteAddressItem->getQty()+$qty));
} else {
$quoteAddress->addItem($quoteItem, $qty);
}
/**
* Require shiping rate recollect
*/
$quoteAddress->setCollectShippingRates((boolean) $this->getCollectRatesFlag());
}
}
return $this;
}
So if anyone else has this issue I was able to figure it out. I was in the wrong function.
getQuoteShippingAddressesItems()
Located in core/Mage/Checkout/Model/Type/Multishipping.php around line 116.
Changed the following code:
for ($i = 0, $n = $item->getQty(); $i < $n; $i++)
To
for ($i = 0, $n = 1; $i < $n; $i++)
$addressItem->setQty($item->getQty)

Invalid argument supplied for foreach() inside shopping cart ,

I am trying to get more than 1 item in my shopping cart array but I run into an issue
This is my database after inserting 1 item with post method
Items is defined in db as text
After trying to insert second product the items result gets overwritten.
My developers tools output after clicking add to cart
ADD
I am using add to cart button from my modal >https://pastebin.com/HKSRTG4L that is submitting via ajax and parsed to add-cart.php
Where I have add to cart function : https://pastebin.com/guv0rB6x
This is my code from cart.php :
<?php
include_once $_SERVER['DOCUMENT_ROOT']."/EcomApp/konfiguracija.php";
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
include 'include/head.php';
include 'include/izbornik.php';
if($cart_id != ''){
$cartQ = $veza->prepare("SELECT * FROM cart WHERE id = '$cart_id';");
$cartQ->execute();
$result= $cartQ->fetch(PDO::FETCH_ASSOC);
$items = json_decode($result['items'],true);var_dump($items) ;
$i = 1;
$sub_total = 0;
$item_count = 0;
}
?>
<div class="col-md-12">
<div class="row">
<h2 class ="text-center">Your Shopping Cart </h2><hr>
<?php if($cart_id =='') :?>
<div class="bg-danger">
<p class="text-center text-danger">
Your shopping cart is empty!
</p>
</div>
<?php else: ?>
<table class="table" >
<thead><th>#</th><th>Item</th><th>Price</th><th>Quantity</th><th>Size</th><th>Sub Total</th></thead>
<tbody>
<?php
foreach ($items as $item){
$product_id =$item['id'];
$productQ = $veza ->prepare("SELECT * FROM products WHERE id = '$product_id'");
$productQ ->execute();
$product= $productQ->fetch(PDO::FETCH_ASSOC);
$sArray = explode (',',$product['sizes']);
foreach($sArray as $sizeString){
$s = explode(':',$sizeString);
if($s[0] ==$item['size']){
$available = $s[1];
}
}
?>
<tr>
<td><?=$i;?></td>
<td><?=$product['title'];?></td>
<td><?=$product['price'];?></td>
<td><?=$item['quantity'];?></td>
<td><?=$item['size'];?></td>
<td><?=$item['quantity'] * $product['price'];?></td>
</t>
<?php } ?>
</tbody>
</table>
<?php endif; ?>
</div>
<?php include 'include/footer.php';?>
I am 93% sure the problem is with array merge since currently the insert is overwriting the row with new results and not adding to the array.
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/konfiguracija.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
$product_id = sanitize($_POST['product_id']);
$size = sanitize($_POST['size']);
$available = sanitize($_POST['available']);
$quantity = sanitize($_POST['quantity']);
$item = array();
$item[]= array(
'id' => $product_id,
'size' => $size,
'quantity' => $quantity,
);
$domain = ($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$query = $veza->prepare("SELECT * FROM products WHERE id = '$product_id'");
$query ->execute();
$product = $query->fetch(PDO::FETCH_ASSOC);
$_SESSION['success_launch'] = $product['title']. 'was added to your cart.';
//check does cookie cart exist
if($cart_id != ''){
$cartQ= $veza->prepare("SELECT * FROM cart WHERE id = '$cart_id'");
$cart = $cartQ->fetch(PDO::FETCH_ASSOC);
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach ($prevous_items as $pitem){
if($item[0]['id']==$pitem['id'] && $item[0]['size'] == $pitem['size']){
$pitem ['quantity']= $pitem['quantity']+$item[0]['quantity'];
if ($pitem['quantity']>$available){
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if($item_match != 1){
$new_items = array_merge($item,(array)$previous_items);
}
$items_json = json_encode($new_items);
$cart_expire = date("Y-m-d H:i:s", strtotime("+30 days"));
$something=$veza->prepare("UPDATE cart SET items = '$items_json',expire_date= '$cart_expire'WHERE id ='$cart_id'");
$something ->execute();
setcookie(CART_COOKIE,'',1,'/',$domain,false);
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}else {
INSERT
//add cart inside database
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$smth=$veza->prepare("INSERT INTO cart (items,expire_date) VALUES ('$items_json','$cart_expire')");
$smth->execute();
$cart_id = $veza->lastInsertId();
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
var_dump($cart_id);
?>
add to cart function : https://pastebin.com/guv0rB6x
function add_to_cart(){
jQuery('#modal_errors').html("");
var size = jQuery('#size').val();
var quantity = jQuery('#quantity').val();
var available = jQuery('#available').val();
var error = '';
var data = jQuery("#add_product_form").serialize();
if(size == '' || quantity == '' || quantity == 0){
error += '<p class= "bg-danger text-center">You must choose a size and quantity</p>';
jQuery('#modal_errors').html(error);
return;
}else if (quantity>available){
error += '<p class= "bg-danger text-center">There are only '+available+' available.</p>';
jQuery('#modal_errors').html(error);
return;
}else{
jQuery.ajax({
url: '/EcomApp/admin/parsers/add_cart.php',
method : 'post',
data : data,
success : function(){
location.reload();
},
error : function(){alert("Something went wrong");}
});
}
}
konfiguracija.php there is a (Undefined offset: 1) on line 65
$user_data['last'] = $fn1;
but I think it is not directly connected to the functionality
try{
$veza = new PDO("mysql:host=" . $host . ";dbname=" . $dbname,$dbuser,$dbpass);
$veza->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$veza->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8';");
$veza->exec("SET NAMES 'utf8';");
}catch(PDOException $e){
switch($e->getCode()){
case 1049:
header("location: " . $eone . "error/wrongDBname.html");
exit;
break;
default:
header("location: " . $eone . "error/error.php?code=" . $e->getCode());
exit;
break;
}
}
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
require_once BASEURL.'helpers/helpers.php';
session_start();
//
$cart_id = '';
if(isset($_COOKIE[CART_COOKIE])){
$cart_id = sanitize($_COOKIE[CART_COOKIE]);
}
if(isset($_SESSION['SDUser'])){
$user_id =$_SESSION['SDUser'];
$query = $veza->prepare("SELECT* FROM korisnik WHERE id ='$user_id'");
$query->execute();
$user_data = $query->fetch(PDO::FETCH_ASSOC);
$fn = explode(' ', $user_data['full_name']);
$user_data['first'] = $fn[0];
$user_data['last'] = $fn[1];
// print_r($user_data);
}
if(isset($_SESSION['success_launch'])){
echo '<h1><p class="text-success">'.$_SESSION['success_launch'].'</p></h1>';
unset($_SESSION['success_launch']);
}
if(isset($_SESSION['error_launch'])){
echo '<div class="success"><p class="text-success">'.$_SESSION['error_launch'].'</p></div>';
unset($_SESSION['error_launch']);
}
In add_cart.php:
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach ($prevous_items as $pitem){
Notice that $previous_items and $prevous_items are different.
That's why you're getting:
Notice: Undefined variable: prevous_items in
/opt/lampp/htdocs/EcomApp/admin/parsers/add_cart.php on line 29
You didn't take my previous advice to make your life easier.
Apparently working code is not enough. Always validate and fail fast ( http://www.practical-programming.org/ppl/docs/articles/fail_fast_principle/fail_fast_principle.html ):
if(!$cart_id){
$cartQ = $veza->prepare("SELECT * FROM cart WHERE id = ?");
$cartQ->execute([(int)$cart_id]);
$result= $cartQ->fetch(PDO::FETCH_ASSOC);
if (!isset($result['items'])) {
throw new \RuntimeException("The items were not found.");
}
$items = json_decode($result['items'],true);
if (!$items) {
throw new \RuntimeException("Invalid items format.");
}
$i = 1;
$sub_total = 0;
$item_count = 0;
}
As said, do something like this:
<?php
$validKeys = ['product_id', 'size', 'available', 'quantity'];
foreach ($validKeys as $key) {
if (!isset($_POST[$key])) {
throw new RuntimeException("Parameter $key is missing.");
}
}
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/konfiguracija.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
$product_id = sanitize($_POST['product_id']);
$size = sanitize($_POST['size']);
$available = sanitize($_POST['available']);
$quantity = sanitize($_POST['quantity']);
Most probably you missed something in the client side (javascript or HTML form), for instance, you might have misspelled "product_id".
ADDED:
https://pastebin.com/guv0rB6x
function add_to_cart(){
jQuery('#modal_errors').html("");
var size = jQuery('#size').val();
var quantity = jQuery('#quantity').val();
var available = jQuery('#available').val();
var error = '';
var data = jQuery("#add_product_form").serialize();
if(size == '' || quantity == '' || quantity == 0){
error += '<p class= "bg-danger text-center">You must choose a size and quantity</p>';
jQuery('#modal_errors').html(error);
return;
}else if (quantity>available){
error += '<p class= "bg-danger text-center">There are only '+available+' available.</p>';
jQuery('#modal_errors').html(error);
return;
}else{
jQuery.ajax({
url: '/EcomApp/admin/parsers/add_cart.php',
method : 'post',
data : data,
success : function(){
location.reload();
},
error : function(){alert("Something went wrong");}
});
}
}
You're not checking if the "product_id" field is empty.
ADDED:
Replace:
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach ($prevous_items as $pitem){
if($item[0]['id']==$pitem['id'] && $item[0]['size'] == $pitem['size']){
$pitem ['quantity']= $pitem['quantity']+$item[0]['quantity'];
if ($pitem['quantity']>$available){
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if($item_match != 1){
$new_items = array_merge($item,(array)$previous_items);
}
With something like this:
$previous_items = json_decode($cart['items'], true);
if (!$previous_items) {
$previous_items = array();
}
$items_by_unique = array();
foreach (array_merge($item, $previous_items) as $item) {
if (!isset($item['id'], $item['size'], $item['quantity'])) {
throw new RuntimeException('Found a invalid invalid data: ' . json_encode($item));
}
$unique = $item['id'] . '-' . $item['size'];
if (isset($items_by_unique[$unique])) {
$old_item = $items_by_unique[$unique];
$item['quantity'] = $old_item['quantity'];
}
if ($item['quantity'] > $available) {
$item['quantity'] = $available;
}
$items_by_unique[$unique] = $item;
}
$items_json = json_encode(array_values($items_by_unique));
The code has lots of issues that make very hard to find the mistakes and it's very hard to answer a question which is really several questions which are always increasing, as if we're making a debugging service for free... We could be discussing here for several hours and days, like a job, until everything is corrected. In that case, it's going to be very hard to help and take care of our personal lives and jobs.
Anyway, I'm going to enumerate some issues that make the code very hard to debug.
Most of the returned values are not validated, assuming that they're what's expected, instead failing immediately when there's an error. That means that you may only notice there's a mistake a lot later and hunt for the its source, which might be in a different file.
For instance, when you do something like this:
$query = $veza->prepare("SELECT * FROM products WHERE id = '$product_id'");
$query->execute();
$product = $query->fetch(PDO::FETCH_ASSOC);
You should always check if $product is at least not empty:
if (!$product) {
throw new RuntimeException("The product #$product_id" was not found.");
}
Also, putting variables inside SQL statements can be very dangerous. If you're using prepared statements you should do something like this:
$query = $veza->prepare("SELECT * FROM products WHERE id = ? LIMIT 1");
$query->execute([$product_id]);
The code does not take advantage of reusability. You can implement classes or functions and test them independently.
For instance, you could have done something like this:
<?php
/**
* Add a new item ...
*
* If it's being requested more items then available ...
*
* #param array $newItem The new item that should be added.
* #param array $items The list of items where the item should be added.
* #param integer $available Available items.
* #return void
*/
function add_item(array $newItem, array &$items, int $available=MAX_INT_MAX)
{
throw_error_if_invalid_item($newItem);
$unique = $newItem['id'] . '-' . $newItem['size'];
if (isset($items_by_unique[$unique])) {
add_item_quantity(
$items_by_unique[$unique],
$item['quantity'],
$available
);
} else {
$items[] = $newItem;
}
}
/**
* Add quantity ...
*
* #param array $item ...
* #param integer $moreQuantity ...
* #param integer $available ...
* #return void
*/
function add_item_quantity(array &$item, int $moreQuantity, int $available=MAX_INT_MAX)
{
$item['quantity'] += $moreQuantity;
if ($item['quantity'] > $available) {
$item['quantity'] = $available;
}
}
/**
* ...
*
* #param array $item ...
* #return void
*/
function throw_error_if_invalid_item(array $item)
{
if (!isset($item['id'], $item['size'], $item['quantity'])) {
throw new RuntimeException(
'Found a invalid invalid item data: ' . json_encode($item)
);
}
}
Then you can make individual test in isolated files:
<?php
$item = array(
'id' => 10,
'size' => 'm',
'quantity' => 2,
);
add_item_quantity($item, 3, 10);
if ($item['quantity'] != 5) {
echo "wrong! quantity = {$item['quantity']}\n";
} else {
echo "correct!\n";
}
If you put your classes or functions in dedicated files, you can reuse them as a library making the code easy to read, testable and secure:
<?php
throw_error_if_invalid_item($_POST);
$newItem = create_item($_POST);
$items = fetch_cart_items($cart_id);
add_item($newItem, $items, 10);
save_cart_items($items);
show_json_items($json);
With classes it would be much easier (eg: you wouldn't have to worry about missing array keys) and you could use PHPUnit to test all the functions and methods automatically. Check how I did that for a simple project:
https://github.com/pedroac/nonce4php
You can also make any error or warning halt the script:
<?php
set_error_handler(
function (int $errno , string $errstr, string $errfile, int $errline) {
http_response_code(500);
echo "ERROR #$errono:$errfile:$errline: $errstr";
die();
}
);
set_exception_handler(
function (Throwable $exception) {
http_response_code(500);
echo $exception->getMessage();
die();
}
);
If you follow the good practices, it will be much easier to found mistakes and let others help you.
I fixed this issue by casting the second argument of array_merge to an array:
$new_items = array_merge($item, (array)$previous_items);

Add exactly 1 product to cart programmatically in Magento

Using Magento 1.8.1, on the checkout page, I'm trying to add a product to the cart in the code. Here is the code I'm using:
$totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$this->addProduct($free_samples_prod_id, 1);
}
else{
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $free_samples_prod_id) {
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
}
}
}
The code is in: app\code\core\Mage\Checkout\Model\Cart.php under public function init()
The product does get added sucessfully, however, everytime somebody visits their cart page, the quantity increases by one. How can I modify that code so the quantity is always 1?
Thank you
Axel makes a very good point, but to answer your immediate question, why not test for the product's presence before you add it
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$alreadyAdded = false;
foreach ($items as $item) {
if($item->getId() == $free_samples_prod_id) { $alreadyAdded = true; break; }
}
if(!$alreadyAdded) { $this->addProduct($free_samples_prod_id, 1); }
}

Categories