How to add Custom option value on coupon rules Magneto 2 - php

How to add Custom option value on coupon rules Magneto 2. I have a product which have some custom option like size, color etc. with different value, I want give discount on basic of size = 7'. I don't want use sku custom option.. Let me know how I fix it.
https://github.com/Turiknox/magento2-custom-total
Moulde I use for Discount but i have face a problem.
one Data I can't get cart information
$obj = $bootstrap->getObjectManager();
// Set the state (not sure if this is neccessary)
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
// Getting the object managers dependencies
$quote = $obj->get('Magento\Checkout\Model\Session')->getQuote();
$helper = $obj->get('\Magento\Checkout\Helper\Cart');
// Get quote and cart items collection
$quote = $helper->getQuote();
$quoteitems = $quote->getAllItems();
$coupon_code = 'Test23';
// Get cart contents
$cart= $helper->getCart();
foreach ($quoteitems as $item)
{
}
It goes to the infinity loop.

This one Run fast that's why here we can't load quote total, For Discount given you must set session core cookies which allow giving discount...

Related

How to change product name in the cart in Prestashop?

I want to change the names of some products in the cart. I was able to change the price of some products in the cart. But i can't change the names of some products in the cart.
How can i do that? Is it possible. Thanks for helps.
For your better understanding, below is some of the result from cart->getProducts() action.
The name of the products, as long as they are in the cart, is read from the product object, so you will have to override the cart->getProducts() method if you want to change their names dynamically.
But keep in mind that once a cart becomes an order, product name is copied / stored inside the orderDetail object, where you can freely intervene by renaming the "product_name" field once you know the original id_cart / id_order.
I solved the problem with the code below. If you encounter this problem, you can edit the code below for yourself. And you must do these actions after validateOrder function or validated the order.
$order = Order::getByCartId($cart->id);
$order_details = OrderDetail::getList($order->id);
foreach ($order_details as $order_detail) {
if ($order_detail['product_name'] === 'Installment' && (string)$order_detail['product_price'] == (string)$installment_fee) {
$order_detail_id = $order_detail['id_order_detail'];
}
}
if (!is_null($order_detail_id)) {
$order_detail = new OrderDetail($order_detail_id);
$order_detail->product_name = 'Changed product name';
$order_detail->save();
}

Exclude several shipping classes from a fee based on cart items dimensions in Woocommerce

I've been getting great help here during the year, regarding a woocommerce issue where I needed an automatic fee added based on total cart height in this thread and then later updated with width in this thread.
Now my only issue is that I need to exclude some shipping classes from the function, as they are shipped differently and don't need a Bulky fee added.
I've been playing around with the answer to "Add a fee based on cart items dimensions in Woocommerce", trying to add a class variable to it:
// Initializing variables
$total_height = 0;
$class = 1390,1392,1389;
$apply_fee = false;
But it instantly breaks the website. I've been searching on stackoverflow.com and Google for a way to do this but no luck, and I'm still not qualified enough for that type of advanced editing of code.
Appreciate any help I can get.
You can't have a list of ids like that with just commas between them. To fix this put the ids in an array. Within the foreach loop, check the shipping class id of the product, and if it's in the array exclude it.
$exclClasses = array(1390,1392,1389);
// Checking item with
if ( $cart_item['data']->get_width() > $width_threshold ) {
$apply_fee = true;
}
// make sure product isn't in excluded shipping classes
if (in_array( $cart_item['data']->get_shipping_class_id(), $exclClasses))
{
$apply_fee = false;
}
or to use 1 statement instead of 2
if ( $cart_item['data']->get_width() > $width_threshold && !in_array( $cart_item['data']->get_shipping_class_id(), $exclClasses)) {
$apply_fee = true;
}

return woocommerce item names from cart only if they are a certain variation

I'm more or less a total newbie to php. My goal is to get the names of items from the logged in user's cart and dynamically populate a GravityForms template with the information. I've successfully managed to do that with the code below, but there are three things that I'm failing to do. 1: I only want to populate the form with all items of a certain variation. 2: the echo function will list all of the item names, but not inside the relevant field, and the return function will populate the field, but only with the first item name. 3: I'd like to have the output items listed with some form of separator in between each item name. Here's what I have so far:
<?php
add_filter( 'gform_field_value_beat_names', 'beat_names_function' );
function beat_names_function( $value ) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach ($items as $item) {
$product_variation_id = $item['variation_id'];
$license_id = new WC_Product($product_variation_id);
$license_string = $license_id->get_formatted_name();
$beat_id = $item['data']->post;
$beat_name = $beat_id->post_title;
if (strpos($license_string, 'basic') !== false) {
echo $beat_name;
}
}
}?>
As you can see, I'm attempting to use strpos to isolate the particular item variation I want to target, using a certain word found in the name of the variation option, being "basic". I'm sure there's a more secure way of doing that, but it works for now. The problem lies with the return function I set up inside the conditional strpos statement, being that it will still just return the entire list of cart items, as opposed to only the items that I'm trying to isolate with the strpos conditional.
The ultimate goal is to create a license agreement that is dynamically populated with the relevant information, including the names of the items being licensed. The item variations are different license options that I have available for the products in my store. The purpose of the above code is to filter cart items by license type so that the wrong item names don't get listed on the wrong license agreement at checkout.
Any tips would be appreciated
Figured it out after some more tinkering. I broke it down step by step to help anyone as clueless as I am
add_filter( 'gform_field_value_basic_beat_names', 'basic_beat_names_function' );
function basic_beat_names_function( $value ) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
// the item names you want will be stored in this array
$license_check = array();
// Loop through cart items
foreach ($items as $item) {
// get the id number of each product variation in the cart. this won't work for "simple" products
$product_variation_id = $item['variation_id'];
// translate that id number into a string containing the name of the product, and the options applied to the product
$license_id = new WC_Product($product_variation_id);
$license_string = $license_id->get_formatted_name();
// check to see if the word "basic" is found anywhere in that string. "basic" is contained in the name of the product option being targeted
if (strpos($license_string, 'basic') !== false) {
// if the above condition is met, fetch the name of any products in the cart that have that option applied. The product name will be fetched from the title of the product's page
$beat_id = $item['data']->post;
$beat_name = $beat_id->post_title;
// store the retrieved product names in the $license_check array
$license_check [] = $beat_name;
}
}
// pull the stored product names from the $license_check array, and format them using implode and concatenation, then return the final result to the form field
return "\"" . implode("\", \"", $license_check) . "\"";
}
As a warning, the strpos method is a little hacky. It'll only work properly if your string is specific enough to target ONLY the option you're looking for.
As an example, here's the format for the product variation string being fed into the strpos function:
item-name-option-one-name-option-two-name – variation #xxx of item page title
So, if you want to filter items ONLY by option one, your safest bet would be to write the strpos function like so:
if (strpos($license_string, 'option-one-name') !== false) {
//do something
}
When all is said and done, the final result should look like: "item1", "item2", "item3", etc.
Then, to do the same with any other option, and output the result in a different field, or separate form altogether, I'll just duplicate this code, and replace any mention of the word "basic" with some different unique string contained in the other option. Don't forget to configure the gravity forms field as necessary too.

Magento - Get the associated product attributes of an item in the wishlist

In app/code/local/Mage/Catalog/Product/Type/Configurable/Price.php, I am trying to get the attribute values of an associated product within the wishlist. I've attempted several approaches but I can only seem to produce data for the parent product.
Latest attempt
$customer = Mage::getSingleton('customer/session')->getCustomer();
if($customer->getId()) {
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $wlitem) {
$wishitem = Mage::getModel('catalog/product')->setStoreId($wlitem->getStoreId())->load($wlitem->getProductId());
//echo $wishitem->getId() . '<br>';
if($product->getId() == $wishitem->getId()) { //if the current product id equals the wishlist product id
echo $wishitem->getSku()."</br>";
}
}
}
That only gets me the parent product's sku. What I ultimately want to get is the attribute value for 2 attributes that I added for configurable products (not super attributes) but it seems that $product in Price.php only has the parent product collection.
Other Attempts:
$item_s = Mage::getModel('wishlist/item')->loadWithOptions($product->getId(), 'simple_product')->getOptionsByCode();
$simple_product = $item_s['simple_product']->getData();
$simple_product_id = $simple_product['product_id'];
$sim_product = Mage::getModel('catalog/product')->load($simple_product_id);
print_r($sim_product);
This only resulted in an error on the page.
Also:
$_item = Mage::getModel('catalog/product')->load($product->getId());
//echo $_item->getData('ppuom');
//print_r($_item);
$simpleProduct = $_item->getOptionsByCode()['simple_product']->getItem()->getProduct();
print_r($simpleProduct);
Seems as if you were most of the way there. I've tested this on my Magento site and it worked for me. It's pretty simple actually, you just have to grab the right model for that collection. Also, it seems like you're changing the pricing?!?! Be careful that your wishlist items contain the necessary attributes used in your logic.
$_item = Mage::getModel('catalog/product')->load($product->getId());
$attribute1 = $_item->getData('attribute1_code'); //see admin for attribute code
$attribute2 = $_item->getData('attribute2_code'); //see admin for attribute code
OR
Make changes to your template's wishlist files rather than the pricing logic in the code folder. You'll have access to all the data you need and it won't interfere with the price.php file which is relied on heavily in the cart and other critical areas of the website. The price in the wishlist is recalculated when it's moved to the cart anyway.

Magento php add to cart with Custom price

I have the following issue:
I make calculations via jQuery in the frontend and want to add a product to the cart with the price calculated in the frontend.
I already wrote a custom module with an AjaxController to achieve the adding to cart part, but I know struggle with setting the custom price.
My script looks like this:
$_prod = json_decode(Mage::app()->getRequest()->getPost('zapfsaeule_product'));
$id = 347; // there is only this one bundle product added to the cart viar this scipt, so a static id is enough.
$params = array(
'product' => $id,
'related_product' => null,
'bundle_option' => array(
6 => 17, // static options for testing purpouses
5 => 13), //
'qty' => 1 // static qty for testing as well
);
$cart = Mage::getSingleton('checkout/cart');
$product = new Mage_Catalog_Model_Product();
$product->load($id);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$this->getResponse()->setBody('true'); // setting response to true, because its an ajax request.
$this->getResponse()->setHeader('Content-type', 'text/plain');
That's the code for adding the product.
For setting the price I tried the approach as mentioned in this thread on stackexchange:
https://magento.stackexchange.com/questions/4318/dynamically-calculated-prices-save-before-add-to-cart
But it didn't work. I guess the event observed here doesn't occur in my case, because I wrote a custom script.
But then there still would be the problem, IF the observer approach would work, how would I pass the calculated price to the observer?
I hope you understand the problem and can help me solve it.
Thanks in advance!
Best regards,
Martin
Reading through Mage_Checkout_Model_Cart::addProduct(), there doesn't appear to be a way to set the item's price from the parameters. Instead, you'll need to add the product, then grab the resulting item, and set its price:
$cart->addProduct($product, $params)
->save();
// grab the corresponding item
$item = $cart->getQuote()->getItemByProduct($product);
// set its custom price
$item->setOriginalCustomPrice($customPrice)
->save();
Haven't had the time to try this out, but it should be the right idea. Make sure that you set the original_custom_price field (using setOriginalCustomPrice()), not one of the other prices. The other prices are recalculated during the totals process.
This comes pretty late, but I just stumbled upon this.
I got it to work like this:
$cart = Mage::getSingleton('checkout/cart');
$cart->addProduct($product, 1); // 1 = qty. Pass your qty and params.
$item = $cart->getQuote()->getItemByProduct($product);
$item->setCustomPrice(0); // or some other value
$item->setOriginalCustomPrice(0); // or some other value
$item->getProduct()->setIsSuperMode(true); // this is crucial
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
If the params don't work, fetch the returned item from $cart->addProduct and change the price on the item before saving the cart.
$item = $cart->addProduct(...);
$item->setCustomPrice(...); {or whatever price attribute you like to set}
$cart->save();

Categories