I tried to update all product information by product id but it's not working for me for all information. With below code "SKU" update successfully but unable to update other information like product name and other custom attribute value.
How can I update all the information about the products using PHP script?
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
$product = $productFactory->create()->setStoreId($storeId)->load($product_id);
$product->setStatus(1);
$product->setName('test pr 123');
$product->setSku('test sku');
$product->setDescription("new product description.");
$product->setShortDescription("new short description.");
$product->save();
Here I'm adding a script hope this will help and solve your problem
use Magento\Framework\App\Bootstrap;
require __DIR__ . 'app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$instance = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$product_collections = $instance ->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $product_collections->create();
foreach ($collections as $product) {
$id = $product->getId();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($id);
$product->setWebsiteIds(array(1));
$product->save();
echo $id.'-';
}
Add your attribute which you need to update in code
If you just want to override some attribute values, you should use the addAttributeUpdate function. With that you can also update attribute values for different store views.
I use a kind of this code to update my products descriptions etc. for several stores.
$productRepository = $objectManager->get('Magento\Catalog\Model\ProductRepository');
// YOU WANT TO LOAD BY ID?
$id = "YOUR ID HERE";
// YOU WANT TO LOAD BY SKU?
$sku = "YOUR SKU HERE";
if($id) {
$product = $productRepository->getById($id);
}
if($sku) {
$product = $productRepository->get($sku);
}
$shortDescriptionAttributeCode = "short_description";
$descriptionAttributeCode = "description";
$shortDescriptionAttributeValue = "YOUR NEW VALUE";
$descriptionAttributeValue = "YOUR NEW VALUE";
$product->addAttributeUpdate($shortDescriptionAttributeCode, $shortDescriptionAttributeValue, 0);
$product->addAttributeUpdate($descriptionAttributeCode, $descriptionAttributeValue, 0);
Related
I'm making a script that should make a copy of an existing order.
I can create the overall order, with this code:
$order = new Order($_GET["id_order"]);
$order->add();
But there's no products in the order - I tried with this:
$order_detail = new OrderDetail($_GET["id_order"]);
$order_detail->add();
What am I doing wrong, how can I copy an existing order?
You can duplicate an order using the duplicateObject() method from the ObjectModel class.
Here is a function that should do the trick :
function duplicateOrder($id_order)
{
$order = new Order($id_order);
$duplicatedOrder = $order->duplicateObject();
$orderDetailList = $order->getOrderDetailList();
foreach ($orderDetailList as $detail) {
$orderDetail = new orderDetail($detail['id_order_detail']);
$duplicatedOrderDetail = $orderDetail->duplicateObject();
$duplicatedOrderDetail->id_order = $duplicatedOrder->id;
$duplicatedOrderDetail->save();
}
$orderHistoryList = $order->getHistory(Configuration::get('PS_LANG_DEFAULT'));
foreach ($orderHistoryList as $history) {
$orderHistory = new OrderHistory($history['id_order']);
$duplicatedOrderHistory = $orderHistory->duplicateObject();
$duplicatedOrderHistory->id_order = $duplicatedOrder->id;
$duplicatedOrderHistory->save();
}
}
How to update cart item using item ID ? I have searched a lot but could not success, here is my codes -
require_once '../app/Mage.php';
Mage::app('default');
$qty = $_REQUEST['quantity'];
$item_id = (int) $_REQUEST['item_id'];
$cart = Mage::getSingleton('checkout/cart');
$quoteItem = $cart->getQuote()->getItemById($item_id);
/*$quoteItem = Mage::getModel('sales/quote_item')->getCollection()
->addFieldToFilter('item_id', array('in' => array($item_id)));*/
print_r($quoteItem);
if (!$quoteItem) {
Mage::throwException('Quote item is not found.');
}
if ($qty == 0) {
$cart->removeItem($id);
} else {
$quoteItem->setQty($qty)->save();
}
$cart->save();
I am implementing it in API , however same code is working fine in website.Please help!!!
I used the below code to update cart items and I am using observer to do that. can you please try this.
$quote = $observer->getEvent()->getQuote();
var_dump($quote->getId());
$quote = Mage::getSingleton('checkout/session')->getQuote();
//var_dump($quote->getId());
$cartItems = $quote->getAllItems();
//$storeId = Mage::app()->getStore()->getId();
foreach ($cartItems as $item) {
//echo $item->getSku();
$item->set__($value); // desired quote field from database
$item->save();
}
$quote->save();
I'm developing an import products cron.
In my code I have:
if ($supplier = Supplier::getIdByName(trim($prodotto['Supplier']['Name']))) {
$product->id_supplier = (int)$supplier;
} else {
$supplier = new Supplier();
$supplier->name = $prodotto['Supplier']['Name'];
$supplier->active = true;
$supplier->add();
$product->id_supplier = (int)$supplier->id;
$supplier->associateTo($product->id_shop_list);
}
The result is:
product created
supplier created
product without supplier
Where am I wrong?
You have to add also a new ProductSupplier, after you saved te new product use this snippet of code (obviously, adapt it to your needs :)):
// Product supplier
if (isset($product->id_supplier) && property_exists($product, 'supplier_reference'))
{
$id_product_supplier = ProductSupplier::getIdByProductAndSupplier((int)$product->id, 0, (int)$product->id_supplier);
if ($id_product_supplier)
$product_supplier = new ProductSupplier((int)$id_product_supplier);
else
$product_supplier = new ProductSupplier();
$product_supplier->id_product = $product->id;
$product_supplier->id_product_attribute = 0;
$product_supplier->id_supplier = $product->id_supplier;
$product_supplier->product_supplier_price_te = $product->wholesale_price;
$product_supplier->product_supplier_reference = $product->supplier_reference;
$product_supplier->save();
}
I need to let customer edit their pending payment order. By default, woocommerce only allow change the payment method. So, I have created a custom template for this feature.
The problem now I encountered is I can't get the shipping packages in the template.
Here is the code that I adapted from the wc_cart_totals_shipping_html() :
$packages = WC()->shipping->get_packages();
print_r($packages);
foreach ( $packages as $i => $package ) {
//blah blah blah
}
The print_r($packages) give me the null array. But on the checkout page, it's working fine.
Any idea why? Or, get the shipping packages by other method?
Please try this -
global $woocommerce;
$customerZipCode = 75098;
$zipResultArr = csd_check_zip_and_state($customerZipCode);
$bh_packages = $woocommerce->cart->get_shipping_packages();
$bh_packages[0]['destination']['state'] = $zipResultArr['state'];
$bh_packages[0]['destination']['postcode'] = $customerZipCode ;
$bh_packages[0]['destination']['city'] = $zipResultArr['city'];
$bh_packages[0]['destination']['address'] = '';
$bh_packages[0]['destination']['address_2'] = '';
//Calculate costs for passed packages
$bh_shipping_methods = array();
foreach( $bh_packages as $bh_package_key => $bh_package ) {
$bh_shipping_methods[$bh_package_key] = $woocommerce->shipping->calculate_shipping_for_package($bh_package, $bh_package_key);
}
$shippingArr = $bh_shipping_methods[0]['rates'];
if(!empty($shippingArr)) {
$response = array();
foreach ($shippingArr as $value) {
$shipping['label'] = $value->label;
$shipping['cost'] = $value->cost;
$response['shipping'][] = $shipping;
}
}
// This is your shipping
print_r($response);
I am currently learning how to create configurable product for Magento. Its all working fine, the product was successfully imported using my codes including its associated products. The problem is the product does not show up in front-end. I have to manually go to the back-end, edit the product and save it. Take note I do not have to change anything, I just need to open it, and save. Only then it will show up in front-end. Any idea why is that?
define('MAGENTO', dirname(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
require_once 'FeedMag.php';
$myFeed = new FeedMag();
Mage::app();
// test data
$sku = "TESTSKU2";
$inventory = "10";
$stockData['qty'] = $inventory;
$stockData['is_in_stock'] = 1;
$simple['Description'] = 'Configurable Product 1';
$simple['ShortDescription'] = 'Short Description';
$simple['LongDescription'] = 'Long Description';
$simple['BrandCode'] = 'Nike';
$attr['color'] = 'Blue';
$attr['size'] = 1;
$price = 11;
// get attribute id
foreach($attr AS $key=>$value) {
$attr_ids[] = $myFeed->attributeValueExists($key, $value);
}
$new = false;
echo "<pre>";
try {
// get product id from SKU
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
// load product if id exist or create a new one
if($id && $id > 0) {
$product = Mage::getModel('catalog/product')->load($id);
}
else {
$product = Mage::getModel('catalog/product')->setSku($sku);
$new = true;
}
// set it to configurable
$product->setTypeId('configurable');
// get attributes' id
$usingAttributeIds = $new_array = array();
foreach( $attr as $key=>$value ) {
$attribute = $product -> getResource() -> getAttribute( $key );
if ( $product -> getTypeInstance() -> canUseAttribute( $attribute ) ) {
if ( $new ) { // fix for duplicating attributes error
$usingAttributeIds[] = $attribute -> getAttributeId();
}
}
}
// if we have attributes' ID, set it to the product
if ( !empty( $usingAttributeIds ) ) {
$product -> getTypeInstance() -> setUsedProductAttributeIds( $usingAttributeIds );
$attributes_array = $product->getTypeInstance()->getConfigurableAttributesAsArray();
foreach($attributes_array as $key => $attribute_value) {
$attributes_array[$key]['label'] = $attribute_value['frontend_label'];
}
$product -> setConfigurableAttributesData($attributes_array);
$product -> setCanSaveConfigurableAttributes( true );
$product -> setCanSaveCustomOptions( true );
}
// set product data
$product->setStoreId(0)
->setAttributeSetId(4)
->setStockData($stockData)
->setPrice($price)
->setName($simple['Description'])
->setShortDescription($simple['ShortDescription'])
->setDescription($simple['LongDescription'])
->setCategoryIds(array(3))
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setBrand($simple['BrandCode'])
->setStatus(1)
->setTaxClassId(2) //Taxable goods
->save();
// get previous children if any
$associated = Mage::getModel('catalog/product_type_configurable')
->getChildrenIds($product->getId());
// add new simple product to configurable product
$associated[0][] = Mage::getModel('catalog/product')->getIdBySku('SIMPLE1');
// add all simple product to configurable product
Mage::getResourceModel('catalog/product_type_configurable')
->saveProducts($product->getId(), array_unique($associated[0]));
}
catch (Mage_Core_Exception $e) {
echo $e->getMessage();
}
catch (Exception $e) {
echo $e;
}
echo "</pre>";
FeedMag is a custom class made by my colleague. There's a lot of method in there but for this purpose I'll be using just one; attributeValueExists to check if said attribute exists and if it does, its ID will be returned.
Simple product already exists so I just need to use it (SIMPLE1).
Its an issue with the indices when importing. You must be missing a field in the export sheet that is required to associate the items and the store. The reason it works when you save is because its rebuilding the table indices which is filling in that missing data.