簡體   English   中英

如何在 Drupal 8 Commerce 中以編程方式創建產品

[英]How to create products programmatically in Drupal 8 commerce

我正在使用當前的 commerce 2.x.dev 進行在線商店開發。 對我來說,這是 Commerce 2 的第一個項目。

當我開始從事產品導入工作時,我發現 Feeds 模塊不穩定,因此我決定編寫自定義數據導入解決方案(從 CSV/XML 源導入批處理/隊列 API 數據)。

因此,此時我無法通過代碼找到有關正確創建產品實體的任何信息。 我探索了 Drupal Commerce 文檔部分: http : //docs.drupalcommerce.org/v2/product/products.html但它只包含手動產品管理的 UI 說明。

我認為從代碼處理產品/訂單實體的簡短說明對開發人員非常有幫助,尤其是對於開始使用 commerce 2 並有一些 7.x commerce 經驗的開發人員。

要以編程方式創建具有 3 個產品變體的產品,請在自定義模塊中使用以下代碼:

use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;

function my_module_install() { 

// Create variations

$variation1 = ProductVariation::create([
  'type' => 'default',
  'sku' => 'var1',
  'price' => new Price('24.00', 'EUR'),  
]);
$variation1->save();

$variation2 = ProductVariation::create([
  'type' => 'default',
  'sku' => 'var2',
  'price' => new Price('50.00', 'EUR'),  
]);
$variation2->save();

$variation3 = ProductVariation::create([
  'type' => 'default',
  'sku' => 'var3',
  'price' => new Price('115.00', 'EUR'), 
]);
$variation3->save();    

// Create product using variations previously saved

$product = Product::create([
  'type' => 'default',
  'title' => t('Your Product Name'),
  'variations' => [$variation1, $variation2, $variation3],
]);
$product->save();

}

我希望它能回答你的問題。 隨意了解更多詳情。

最好的問候

您需要閱讀此文檔( 創建產品)並以相同的方式執行。

已編輯

$variation_blue_large = \Drupal\commerce_product\Entity\ProductVariation::create([ 
  'type' => 'my_custom_variation_type',
  'sku' => '001',
  'price' => new \Drupal\commerce_price\Price('10.00', 'USD'),
  'attribute_color' => $blue,
  'attribute_size' => $large,
])->save();

$variations = [
  $variation_blue_large,
];

$product = \Drupal\commerce_product\Entity\Product::create([
  'uid' => 1,
  'type' => 'my_custom_product_type',
  'title' => 'My Custom Product',
  'stores' => [$store],
  'variations' => $variations,
]);
$product->save();

**加載具有多朋友變化的產品**

use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;

// Load existing  variations

 $result = \Drupal::entityQuery('commerce_product_variation')
          ->condition('type', 'variation_type')
             ->execute();
  $entity_manager = \Drupal::entityManager();
      $product_variation = $entity_manager->getStorage('commerce_product_variation')->loadMultiple($result);


//Add variation to Product
$product = Product::create([
  'type' => 'hakuro_plate',
  'title' => t('Your Product Name custom New testing'),
  'variations' =>$product_variation,
]);
$product->save();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM