كل ما تريد معرفته عن استيراد وتصدير منتجات الحزمة
نشرت: 2015-01-26مرحبا ! قراء مدونة ماجسولوشن ! هل لديك ما يكفي من المعرفة حول استيراد وتصدير منتجات الحزمة؟ تحقق من هذه المقالة لتفهم تمامًا استيراد وتصدير منتجات الحزمة في Magento.
آخر تحديث: لقد أصدرنا للتو الإصدار 2.0 من Claue Multipurpose Magento 2 Theme ، مع مجموعة من تحسينات الأداء والميزات الحصرية. تحقق من هذا الموضوع الآن: Claue Magento Theme 2. 0

عرض حي
يعد Claue - Clean، Minimal Magento 2 & 1 Theme نموذجًا ممتازًا لمتجر تجارة إلكترونية حديث ونظيف يحتوي على أكثر من 40 تخطيطًا للصفحة الرئيسية والعديد من الخيارات للتسوق ، والمدونة ، والمحفظة ، وتخطيطات محدد مواقع المتاجر ، وصفحات مفيدة أخرى. يأتي إصدار Claue 2. 0 مع مجموعة من الميزات الحصرية بما في ذلك:
- أن تكون مبنية على موضوع Luma.
- تلبية جميع معايير موضوع Magento
- تحسن كبير في الأداء
- متوافق مع معظم ملحقات الطرف الثالث.
- متوافق تمامًا مع Magento 2.4.x
هذه النسخة المتقدمة الثانية تختلف تمامًا عن سابقتها. وبالتالي ، إذا كنت تستخدم الإصدار 1 من Claue وترغب في التحديث إلى الإصدار 2 من Claue ، فيمكنك فقط إعادة إنشاء موقع ويب جديد بدلاً من التحديث من الإصدار القديم. الآن ، دعنا نعود إلى الموضوع الرئيسي.
سنذكر في هذا المقال مسألتين:
- تصدير منتج الحزمة إلى ملف CSV بالتنسيقات المتاحة.
- استيراد ملف CSV يحتوي على معلومات المنتج إلى قاعدة بيانات Magento
إنشاء وحدة حزمة المنتج مع الهياكل التالية:
التطبيق \ كود \ محلي \ MGS \ Productbundle \ وحدات تحكم \ Adminhtml \ ProductbundleController.php
التطبيق \ كود \ محلي \ MGS \ Productbundle \ etc \ config.xml
التطبيق \ كود \ محلي \ MGS \ Productbundle \ مساعد \ Data.php
التطبيق \ الخ \ الوحدات النمطية MGS_Productbundle.xml
app \ design \ adminhtml \ default \ default \ layout \ productbundle.xml
app \ design \ adminhtml \ default \ default \ template \ productbundle \ productbundlebackend.phtml
قم بإنشاء ملف MGS_Productbundle.xml لتنشيط الوحدة
MGS _Productbundle.xml
<?xml version="1.0"?>
<config>
<modules>
<MGS_Productbundle>
<active>true</active>
<codePool>local</codePool>
</MGS_Productbundle>
</modules>
</config>
إنشاء قائمة للاستيراد والتصدير في config.xml

config.xml
<?xml version="1.0"?>
<config>
<modules>
<MGS_Productbundle>
<version>0.1.0</version>
</MGS_Productbundle>
</modules>
<admin>
<routers>
<productbundle>
<use>admin</use>
<args>
<module>MGS_Productbundle</module>
<frontName>productbundle</frontName>
</args>
</productbundle>
</routers>
</admin>
<adminhtml>
<menu>
<productbundle module="productbundle">
<title>Product Bundle</title>
<sort_order>71</sort_order>
<children>
<export module="productbundle">
<title>Export to CSV</title>
<sort_order>0</sort_order>
<action>productbundle/adminhtml_productbundle/export</action>
</export>
<import module="productbundle">
<title>Import from CSV</title>
<sort_order>1</sort_order>
<action>productbundle/adminhtml_productbundle/index</action>
</import>
</children>
</productbundle>
</menu>
<acl>
<resources>
<all>
<title>Allow Everything</title>
</all>
<admin>
<children>
<MGS_Productbundle>
<title>Productbundle Module</title>
<sort_order>10</sort_order>
</MGS_Productbundle>
</children>
</admin>
</resources>
</acl>
<layout>
<updates>
<productbundle>
<file>productbundle.xml</file>
</productbundle>
</updates>
</layout>
</adminhtml>
<global>
<helpers>
<productbundle>
<class>MGS_Productbundle_Helper</class>
</productbundle>
</helpers>
</global>
</config>
أنشئ نموذجًا لاستيراد منتج الحزمة من ملف CSV

productbundle.xml
<?xml version="1.0"?>
<layout version="0.1.0">
<productbundle_adminhtml_productbundle_index>
<reference name="content">
<block type="core/template" name="productbundle" template = "productbundle/productbundlebackend.phtml" />
</reference>
</productbundle_adminhtml_productbundle_index>
</layout>
productbundlebackend.phtml
<script type="text/javascript">
function importAction()
{
var file = $('fileimport').value;
if (file == '') {
alert('Please choose file import.');
return false;
}
$('import_form').submit();
}
</script>
<div class="imporproductbackend">
<div class="entry-edit">
<form id="import_form" name="edit_form" method="post" action="<?php echo $this->getUrl('*/*/import')?>" enctype="multipart/form-data" >
<div class="content-header">
<table cellspacing="0" class="grid-header">
<tr>
<td><h3><?php echo $this->__('Import Bundle Products')?></h3></td>
<td class="a-right">
<button onclick="importAction()" class="scalable save" type="button"><span><?php echo $this->__('Import') ?></span></button>
</td>
</tr>
</table>
</div>
<input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />
<h4 class="icon-head head-edit-form fieldset-legend"><?php echo $this->__('Import bundle product form csv')?></h4>
<fieldset id="my-fieldset">
<table cellspacing="0" class="form-list">
<tr>
<td class="label"><?php echo $this->__('Import file')?> </td>
<td class="input-ele">
<input type="file" name="fileimport" id="fileimport" class="" title="Select File to Import"/>
</td>
</tr>
</table>
</fieldset>
</form>
</div>
</div>
منتجات حزمة التصدير:
لتصدير منتجات الحزمة إلى ملف CSV ، تحتاج إلى استخراج جميع منتجات الحزمة عن طريق تشغيل هذا السطر من التعليمات البرمجية:
$products = Mage::getResourceModel('catalog/product_collection')->addAttributeToFilter('type_id', array('eq' => 'bundle'));بعد التعرف على منتجات الحزمة هذه واستخراجها ، يمكنك الانتقال إلى تصديرها إلى ملف CSV.
أولاً ، ستقوم بإنشاء ملف CSV بالتنسيق المتاح عن طريق تشغيل الكود التالي:
$csv_export = '';
if($csv_export == ''){
$file = 'bundle';
$data_title = array('sku', 'website_ids', 'attribute_set_id', 'type_id', 'name', 'description', 'short_description', 'category_ids', 'has_options', 'sku_type', 'weight_type', 'shipment_type', 'status', 'price_type', 'price_view', 'special_price', 'is_in_stock', 'qty', 'bundle_options_selections');
Mage::helper('productbundle')->createCsvfile($file,$data_title);
$CSVFileName = Mage::getSingleton('core/session')->getCsvexport();
}
يتم إنشاء وظيفة createCsvfile ($ file، $ data_title) لإنشاء ملف CSV جديد وتسجيل عناوين للأعمدة ، قم بتشغيل هذا الكود:
// Create new file csv
public function createCsvfile($file,$data_title)
{
if(!is_dir(Mage::getBaseDir() . DS . "var" . DS . "exportcsv")){
mkdir(Mage::getBaseDir() . DS . "var" . DS . "exportcsv", 0777, true);
}
$csv_folder = Mage::getBaseDir() . DS . "var" . DS . "exportcsv";
$filename = str_replace('.csv','',$file).'_'.date("YmdHis");
$CSVFileName = $csv_folder. DS .$filename.'.csv';
$FileHandle = fopen($CSVFileName, 'w') or die("can't open file");
fclose($FileHandle);
$fp = fopen($CSVFileName, 'a');
fputcsv($fp, $data_title);
Mage::getSingleton('core/session')-&gt;setCsvexport($CSVFileName);
}إلى جانب المعلومات الأساسية لمنتج الحزمة مثل sku والاسم والوصف ... تحتاج إلى إضافة معلومات عن الخيارات والتحديدات لكل خيار.
قم بتشغيل هذا الرمز لاستخراج معلومات الخيارات:
$optionCollection = $bundled_product->getTypeInstance()->getOptionsCollection(); $selectionCollection = $bundled_product->getTypeInstance()->getSelectionsCollection($bundled_product->getTypeInstance()->getOptionsIds()); $options = $optionCollection->appendSelections($selectionCollection);
احصل على مجموعة مختارة من الخيارات من خلال هذا الرمز:
foreach( $options as $option ){
$_selections = $option->getSelections();
}
بعد ذلك ستقوم بدمج جميع المعلومات الخاصة بالخيارات والتحديدات لكل خيار في سلسلة وحفظ هذه السلسلة في عمود من ملف CSV. قم بتشغيل الكود التالي:
$csv_export = '';
if($csv_export == ''){
$file = 'bundle';
$data_title = array('sku', 'website_ids', 'attribute_set_id', 'type_id', 'name', 'description', 'short_description', 'category_ids', 'has_options', 'sku_type', 'weight_type', 'shipment_type', 'status', 'price_type', 'price_view', 'special_price', 'is_in_stock', 'qty', 'bundle_options_selections');
Mage::helper('productbundle')->createCsvfile($file,$data_title);
$CSVFileName = Mage::getSingleton('core/session')->getCsvexport();
}
foreach($products as $product){
$bundled_product = new Mage_Catalog_Model_Product();
$bundled_product->load($product->getId());
$b_website_ids = implode(',',$bundled_product->getWebsiteIds());
$b_attribute_set_id = $bundled_product->getData('attribute_set_id');
$b_type_id = $bundled_product->getData('type_id');
$b_sku = $bundled_product->getData('sku');
$b_name = $bundled_product->getData('name');
$b_description = $bundled_product->getData('description');
$b_short_description = $bundled_product->getData('short_description');
$b_category_ids = implode(',',$bundled_product->getCategoryIds());
$b_has_options = $bundled_product->getData('has_options');
$b_sku_type = $bundled_product->getData('sku_type');
$b_weight_type = $bundled_product->getData('weight_type');
$b_shipment_type = $bundled_product->getData('shipment_type');
$b_status = $bundled_product->getData('status');
$b_price_type = $bundled_product->getData('price_type');
$b_price_view = $bundled_product->getData('price_view');
$b_special_price = $bundled_product->getData('special_price');
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($bundled_product);
$b_is_in_stock = $stock->getIsInStock();
$b_qty = $stock->getQty();
$optionCollection = $bundled_product->getTypeInstance()->getOptionsCollection();
$selectionCollection = $bundled_product->getTypeInstance()->getSelectionsCollection($bundled_product->getTypeInstance()->getOptionsIds());
$options = $optionCollection->appendSelections($selectionCollection); // get all options
$options_arr = array();
if(count($options)){
foreach( $options as $option )
{
$o_required = $option->getData('required');
$o_position = $option->getData('position');
$o_type = $option->getData('type');
$o_title = $option->getData('default_title');
$_selections = $option->getSelections(); // get all items of each option
$selections_arr = array();
if(count($_selections)){
foreach( $_selections as $selection )
{
// data of product selection
$selection_price_value = $selection->getData('selection_price_value');
$selection_price_type = $selection->getData('selection_price_type');
$selection_qty = $selection->getData('selection_qty');
$selection_can_change_qty = $selection->getData('selection_can_change_qty');
$position = $selection->getData('position');
$is_default = $selection->getData('is_default');
// data of product to import new product
$selection = Mage::getModel('catalog/product')->loadByAttribute('sku', $selection->getData('sku'));
$website_ids = implode(',',$selection->getWebsiteIds());
$attribute_set_id = $selection->getData('attribute_set_id');
$type_id = $selection->getData('type_id');
$sku = $selection->getData('sku');
$name = $selection->getData('name');
$description = $selection->getData('description');
$short_description = $selection->getData('short_description');
$category_ids = implode(',',$selection->getCategoryIds());
$has_options = $selection->getData('has_options');
$msrp_enabled = $selection->getData('msrp_enabled');
$msrp_display_actual_price_type = $selection->getData('msrp_display_actual_price_type');
$price = $selection->getData('price');
$special_price = $selection->getData('special_price');
$msrp = $selection->getData('msrp');
$status = $selection->getData('status');
$tax_class_id = $selection->getData('tax_class_id');
$weight = $selection->getData('weight');
// $stock_item = $selection->getData('stock_item');
$stock_item = '';
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($selection);
$is_in_stock = $stock->getIsInStock();
$qty = $stock->getQty();
$selections_arr[] = implode('#sa#', array($website_ids, $attribute_set_id, $type_id, $sku, $name, $description, $short_description, $category_ids, $has_options, $msrp_enabled, $msrp_display_actual_price_type, $price, $special_price, $msrp, $status, $tax_class_id, $weight, $stock_item, $is_in_stock, $qty, $selection_price_value, $selection_price_type, $selection_qty, $selection_can_change_qty, $position, $is_default));
}
}
$options_arr[] = implode('#oa#',array($o_required, $o_position, $o_type, $o_title, implode('#s#',$selections_arr)));
}
}
$bundle_options_selections = implode('#o#', $options_arr);
$data = array($b_sku, $b_website_ids, $b_attribute_set_id, $b_type_id, $b_name, $b_description, $b_short_description, $b_category_ids, $b_has_options, $b_sku_type, $b_weight_type, $b_shipment_type, $b_status, $b_price_type, $b_price_view, $b_special_price, $b_is_in_stock, $b_qty, $bundle_options_selections);
$fp = fopen($CSVFileName, 'a');
fputcsv($fp, $data);
}
يتم تكوين ملف CSV كامل على النحو التالي:


منتج حزمة الاستيراد
لاستيراد منتجات الحزمة ، سوف تتحقق من كل سطر من ملف CSV لمعرفة ما إذا كان أحد المنتجات موجودًا أم لا بواسطة SKU. بالنسبة لتلك المنتجات غير الموجودة ، ستحتاج إلى استيرادها.
إذا كانت المنتجات التي تم تحديدها من الخيارات غير موجودة ، فأنت بحاجة إلى استيراد تلك التي تحتوي على المعلومات المتوفرة لملف CSV للحصول على معرف لتحديد منتجات الحزمة. يمكنك الحصول على معرف منتجات التحديد باتباع هذه القاعدة:
public function getSelectionId($selection_data){
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $selection_data[3]);
if($product){
$product_id = $product->getData('entity_id');
}
else{ //create new product width data of selection product
$newProductData = array(
// websites - Array of website ids to which you want to assign a new product
'website_ids' => explode(',',$selection_data[0]),
'sku' => $selection_data[3],
'name' => $selection_data[4],
'description' => $selection_data[5],
'short_description' => $selection_data[6],
'status' => $selection_data[14],
'weight' => $selection_data[16],
'tax_class_id' => $selection_data[15],
'price' => $selection_data[11],
'special_price' => $selection_data[12],
'created_at' => strtotime('now'),
);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
$product->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
->setAttributeSetId($selection_data[1])
->setTypeId($selection_data[2])
->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID))
->setCategoryIds(explode(',', $selection_data[7]));
try{
$product->addData($newProductData);
$product->getResource()->save($product);
$product->setMediaGallery(array('images' => array(), 'values' => array()));
$product->save();
$stockItem = Mage::getModel('cataloginventory/stock_item');
$stockItem->loadByProduct($product->getId());
$stockItem->assignProduct($product);
$stockItem->setData('product_id',$product->getId());
$stockItem->setData('is_in_stock', $selection_data[19]);
$stockItem->setData('qty',$selection_data[20]);
$stockItem->setData('manage_stock', 1);
$stockItem->setData('stock_id', 1);
$stockItem->setData('use_config_manage_stock', 0);
$stockItem->save();
$product_id = $product->getId();
} catch (Exception $e) {
Mage::log($e->getMessage());
die("error: ".$e->getMessage());
}
}
return $product_id;
}
عندما يتم ملء جميع معلومات منتجات الحزمة مع خياراتها وتحديداتها ، ستقوم بإنشاء منتجات الحزمة باتباع الكود أدناه:
$new_product++;
try{
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$bundleProduct = Mage::getModel('catalog/product');
$bundleProduct
->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID) //you can set data in store scope
->setWebsiteIds(explode(',',$b_website_ids)) //website ID the product is assigned to, as an array
->setAttributeSetId($b_attribute_set_id) //ID of a attribute set named 'default'
->setTypeId('bundle') //product type
->setCreatedAt(strtotime('now')) //product creation time
// ->setUpdatedAt(strtotime('now')) //product update time
->setSkuType($b_sku_type) //SKU type (0 - dynamic, 1 - fixed)
->setSku($b_sku) //SKU
->setName($b_name) //product name
->setWeightType($b_weight_type) //weight type (0 - dynamic, 1 - fixed)
// ->setWeight(4.0000)
->setShipmentType($b_shipment_type) //shipment type (0 - together, 1 - separately)
->setStatus($b_status) //product status (1 - enabled, 2 - disabled)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
->setManufacturer(28) //manufacturer id
->setColor(24)
// ->setNewsFromDate('06/26/2014') //product set as new from
// ->setNewsToDate('06/30/2014') //product set as new to
// ->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
->setPriceType($b_price_type) //price type (0 - dynamic, 1 - fixed)
->setPriceView($b_price_view) //price view (0 - price range, 1 - as low as)
->setSpecialPrice($b_special_price) //special price in form 11.22
// ->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
// ->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
/*only available if price type is 'fixed'*/
// ->setPrice(11.22) //price, works only if price type is fixed
// ->setCost(22.33) //price in form 11.22
// ->setMsrpEnabled(1) //enable MAP
// ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
// ->setMsrp(99.99) //Manufacturer's Suggested Retail Price
// ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
/*only available if price type is 'fixed'*/
// ->setMetaTitle('test meta title 2')
// ->setMetaKeyword('test meta keyword 2')
// ->setMetaDescription('test meta description 2')
->setDescription($b_description)
->setShortDescription($b_short_description)
->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
->setStockData(array(
'use_config_manage_stock' => 1, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'is_in_stock' => $b_is_in_stock, //Stock Availability
)
)
->setCategoryIds(explode(',',$b_category_ids)); //assign product to categories
if($b_has_options == 1){
$i = 0;
$i2 = 0;
$bundleOptions = array();
$bundleSelections = array();
$bundle_options = explode('#o#',$bundle_options_selections);
foreach ($bundle_options as $bun_option){
$option_data = explode('#oa#', $bun_option);
$bundleOptions[$i] = array(
'required' => $option_data[0],
'option_id' => '',
'position' => $option_data[1],
'type' => $option_data[2],
'title' => $option_data[3],
'delete' => '',
);
$bundle_selections = explode ("#s#", $option_data[4]);
foreach ($bundle_selections as $bun_selection){
$selection_data = explode('#sa#', $bun_selection);
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $selection_data[3]);
$product_id = Mage::helper('productbundle')->getSelectionId($selection_data);
$bundleSelections[$i][] = array(
'product_id' => $product_id,
// 'selection_qty' => $selection_data[22],
'selection_qty' => $selection_data[22],
'selection_can_change_qty' => $selection_data[23],
'position' => $selection_data[24],
'is_default' => $selection_data[25],
'selection_id' => '',
'selection_price_type' => $selection_data[21],
'selection_price_value' => $selection_data[20],
'option_id' => '',
'delete' => ''
);
$i2++;
}
$i++;
}
}
//registering a product because of Mage_Bundle_Model_Selection::_beforeSave
Mage::register('product', $bundleProduct);
Mage::register('current_product', $bundleProduct);
//flags for saving custom options/selections
$bundleProduct->setCanSaveCustomOptions(true);
$bundleProduct->setCanSaveBundleSelections(true);
$bundleProduct->setAffectBundleProductSelections(true);
//setting the bundle options and selection data
$bundleProduct->setBundleOptionsData($bundleOptions);
$bundleProduct->setBundleSelectionsData($bundleSelections);
$bundleProduct->save();
Mage::getSingleton('adminhtml/session')->addSuccess('Import success');
} catch (Exception $e) {
Mage::log($e->getMessage());
echo "error: ".$e->getMessage();
}
هناك بعض الطرق الأخرى لاستيراد / تصدير منتجات الحزمة التي تجيدها. نود أن نسمع تعليقاتك ونرغب في مشاركة معرفتنا بعد ذلك. شكرا للقراءة.
يمكنك تنزيل الملحق الكامل هنا
