以编程方式创建可配置产品,并将简单产品分配给Magento2产品中的可配置产品


10

到目前为止,这是我所做的。创建了简单且可配置的产品。问题是我无法将简单产品分配给可配置产品。这是代码(ID和属性适用于默认样本数据)。

    //simple product
    $simple_product = $this->_objectManager->create('\Magento\Catalog\Model\Product');
    $simple_product->setSku('test-simple');
    $simple_product->setName('test name simple');
    $simple_product->setAttributeSetId(4);
    $simple_product->setSize_general(193); // value id of S size
    $simple_product->setStatus(1);
    $simple_product->setTypeId('simple');
    $simple_product->setPrice(10);
    $simple_product->setWebsiteIds(array(1));
    $simple_product->setCategoryIds(array(31));
    $simple_product->setStockData(array(
        'use_config_manage_stock' => 0, //'Use config settings' checkbox
        'manage_stock' => 1, //manage stock
        'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
        'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
        'is_in_stock' => 1, //Stock Availability
        'qty' => 100 //qty
        )
    );

    $simple_product->save();

    $simple_product_id = $simple_product->getId();
    echo "simple product id: ".$simple_product_id."\n";


    //configurable product
    $configurable_product = $this->_objectManager->create('\Magento\Catalog\Model\Product');
    $configurable_product->setSku('test-configurable');
    $configurable_product->setName('test name configurable');
    $configurable_product->setAttributeSetId(4);
    $configurable_product->setStatus(1);
    $configurable_product->setTypeId('configurable');
    $configurable_product->setPrice(11);
    $configurable_product->setWebsiteIds(array(1));
    $configurable_product->setCategoryIds(array(31));
    $configurable_product->setStockData(array(
        'use_config_manage_stock' => 0, //'Use config settings' checkbox
        'manage_stock' => 1, //manage stock
        'is_in_stock' => 1, //Stock Availability
        )
    );

    $configurable_product->getTypeInstance()->setUsedProductAttributeIds(array(152),$configurable_product); //attribute ID of attribute 'size_general' in my store
    $configurableAttributesData = $configurable_product->getTypeInstance()->getConfigurableAttributesAsArray($configurable_product);

    $configurable_product->setCanSaveConfigurableAttributes(true);
    $configurable_product->setConfigurableAttributesData($configurableAttributesData);

    $configurableProductsData = array();
    $configurableProductsData[$simple_product_id] = array( //[$simple_product_id] = id of a simple product associated with this configurable
        '0' => array(
            'label' => 'S', //attribute label
            'attribute_id' => '152', //attribute ID of attribute 'size_general' in my store
            'value_index' => '193', //value of 'S' index of the attribute 'size_general'
            'is_percent'    => 0,
            'pricing_value' => '10',
        )
    );
    $configurable_product->setConfigurableProductsData($configurableProductsData);

    $configurable_product->save();

    echo "configurable product id: ".$configurable_product->getId()."\n";

您有最终解决方案吗?
Praful Rajput

$ attributeSetId应该是什么?
Abdo Tasks '18

Answers:


7

您可以查看API功能测试以创建可配置产品

代码应如下所示:

$product = $productFactory->create(['name'=> 'configurable product', ... ]);
$configurableOption = $optionFactory->create([]);
$linkedProduct = $linkFactory->create([]);
$product->getExtensionAttributes()->setConfigurableProductOptions($configurableOption);
$product->getExtensionAttributes()->setConfigurableProductLinks($linkedProduct);
$productRepository->save($product)

请注意,API当前不生成简单的产品,需要提前创建它们。


2
对于将来的读者:这是正确的方法(以及示例,单独的答案)。但是,注意最后一行非常重要。您必须通过产品存储库进行保存。$product->save()直接调用不会触发可配置数据的保存(如中的\Magento\ConfigurableProduct\Model\Plugin\AroundProductRepositorySave)。
Ryan Hoerr

5

我创建了示例脚本。应该直接在DI上替换所有ObjectManager的直接用法

    $ob = ObjectManager::getInstance();

    /** @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepo */
    $attributeRepo =  $ob->get(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class);

    $attribute = $attributeRepo->get('color');  // color should be in default attribute set

    /** @var \Magento\Catalog\Api\ProductRepositoryInterface $pr */
    $pr = $ob->get(ProductRepositoryInterface::class);
    $ids = [];
    $values = [];
    foreach($attribute->getOptions() as $option) {
        $id = $option->getValue();
        /** @var \Magento\Catalog\Api\Data\ProductInterface $p */
        $p = $ob->get(\Magento\Catalog\Api\Data\ProductInterface::class);
        $p->setSku('simple-'. $id);
        $p->setName('Configurable Product option #'. $option->getLabel());
        $p->setPrice(10 + $id);
        $p->setTypeId('simple');
        $p->setCustomAttribute($attribute->getAttributeCode(), $id);
        $p = $pr->save($p);
        $ids[] = $p->getId();
        /** @var \Magento\ConfigurableProduct\Api\Data\OptionValueInterface $opVal */
        $opVal =  $ob->create(\Magento\ConfigurableProduct\Api\Data\OptionValueInterface::class);
        $opVal->setValueIndex($id);
        $values[] = $opVal;
    }
    /** @var \Magento\Catalog\Api\Data\ProductInterface $cp */
    $cp = $ob->get(\Magento\Catalog\Api\Data\ProductInterface::class);
    $cp->setSku('configurable');
    $cp->setName('Configurable product');


    /** @var \Magento\ConfigurableProduct\Api\Data\OptionInterface $option */
    $option = $ob->create(\Magento\ConfigurableProduct\Api\Data\OptionInterface::class);
    $option->setLabel('Product Color');
    $option->setAttributeId($attribute->getAttributeId());
    $option->setValues($values);

    $exteAttrs = $cp->getExtensionAttributes();
    $exteAttrs->setConfigurableProductLinks($ids);
    $exteAttrs->setConfigurableProductOptions([
        $option
    ]);

    $pr->save($cp);

https://github.com/magento/magento2/blob/2.1/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable.php其它示例


嗨,安迪,谢谢您的解决方案。但是$ cp-> getExtensionAttributes()每次都为null,无论我做什么和更改。例如:“ PHP致命错误:在null上调用成员函数setConfigurableProductOptions()”
mmmgigi 2015年

使用类似$ productExtension = $ product-> getExtensionAttributes()的代码;如果($ productExtension === null){$ productExtension = $ this-> productExtensionFactory-> create(); }
KAndy 2015年

@Kandy,请检查您的答案,因为不完整,它不起作用。您必须解决$option->setValues($values),但特别是您忘记了$cp->setExtensionAttributes($exteAttrs)
LucScu '16


这只是对想要创建简单产品的人们的提示...可配置产品是简单产品的集合,因此这里也提供了简单产品创建代码!
quickshiftin

1

下面的代码对我来说很好用。

/* Associate simple product to configurable */
$associatedProductIds = array($simplProductId1,$simplProductId2,$simplProductId3,$simplProductId4);//Simple Product ids array
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($configProductId); // Load Configurable Product
$attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute');
$position = 0;
$attributes = array($attributeColorId, $attributeSizeId); // Super Attribute Ids Used To Create Configurable Product(list of supper attribute ids what ever belong to that the attribute set under which the configurable product is)
foreach ($attributes as $attributeId) {
    $data = array('attribute_id' => $attributeId, 'product_id' => $configProductId, 'position' => $position);
    $position++;
    $attributeModel->setData($data);//->save();
}
$product->setTypeId("configurable");
$product->setAffectConfigurableProductAttributes($attributeSetId);
$objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $product);
$product->setNewVariationsAttributeSetId($attributeSetId);
$product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products
$product->setCanSaveConfigurableAttributes(true);
$product->save();

不行 给我的错误是,该选项未定义
Asish Hira

给我同样的错误,未定义选项-@Asish您是否解决了此问题
Nidhi

@Asish&Nidhi:是的,对于我和ofcz u hv宣告选择权,效果很好
Ipsita Rout

@Nidhi不,我无法解决。
Asish Hira

您可以添加@IpsitaRout代码来声明选项吗?
Asish Hira
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.