Magento – How to create Configurable Product Programmatically

configurable-producterrormagento2programmatically

I have found some question same my own but have not found out the answer. I want to create a configurable product. I have create a form to save the product and get the child product details in configurable-matrix:

enter image description here

enter image description here

But when I'm trying to save this product, the error Option values are not specified. appear. Can someone help me to save the product or just release another way to save a configurable product. Thanks!

Best Answer

You have to set attribute id and its value to it. For example this array of data:

public function getProductData($data = [])
{
    $productData = [
        'stock_data' => [
            'min_qty_allowed_in_shopping_cart' => [
                [
                    'record_id' => "0",
                    'customer_group_id' => "32000",
                    'min_sale_qty' => "",
                ]
            ],
            'deferred_stock_update' => "1",
            'use_config_deferred_stock_update' => "1",
            'min_qty' => "0",
            'max_sale_qty' => "10000",
            'notify_stock_qty' => "1",
            'qty_increments' => "1",
            'min_sale_qty' => "1",
            'use_config_manage_stock' => "1",
            'manage_stock' => "1",
            'use_config_min_qty' => "1",
            'use_config_max_sale_qty' => "1",
            'use_config_backorders' => "1",
            'backorders' => "0",
            'use_config_notify_stock_qty' => "1",
            'use_config_enable_qty_inc' => "1",
            'enable_qty_increments' => "0",
            'use_config_qty_increments' => "1",
            'use_config_min_sale_qty' => "1",
            'is_qty_decimal' => "0",
            'is_decimal_divided' => "0",
        ],
        'use_config_is_returnable' => "1",
        'gift_wrapping_available' => "1",
        'use_config_gift_wrapping_available' => "1",
        'gift_message_available' => "0",
        'use_config_gift_message_available' => "1",
        'links_title' => "Links",
        'links_purchased_separately' => "0",
        'samples_title' => "Samples",
        'attribute_set_id' => "4",
        'status' => $this->isParentProductEnable(),
        'affect_product_custom_options' => "1",
        'name' => $data['title'],
        'title_rewrite' => "",
        'price' => "100",
        'weight' => "",
        'url_key' => "",
        'gift_wrapping_price' => "",
        'special_price' => "",
        'cost' => "",
        'msrp' => "",
        'quantity_and_stock_status' => [
            'qty' => "",
            'is_in_stock' => "1"
        ],
        'is_returnable' => "2",
        'website_ids' => [$this->getWebsiteId($data['division'])],
        'tax_class_id' => "2",
        'product_has_weight' => "1",
        'visibility' => "4",
        'color' => "49",
        'size' => "91",
        'options_container' => "container2",
        'weltpixel_exclude_from_sitemap' => "0",
        'msrp_display_actual_price_type' => "0",
        'description' => "",
        'short_description' => "",
        'custom_layout_update' => "",
        'sku' => $data['product_code'],
        'meta_title' => $data['title'],
        'meta_keyword' => $data['title'],
        'meta_description' => "",
        'configurable_attributes_data' => [
            self::COLOR_ATTRIBUTE_ID => [
                'attribute_id' => self::COLOR_ATTRIBUTE_ID,
                'code' => "color",
                'label' => "Color",
                'position' => "0",
                'values' => $this->getColorValue($data)
            ],
            self::SIZE_ATTRIBUTE_ID => [
                'attribute_id' => self::SIZE_ATTRIBUTE_ID,
                'code' => "size",
                'label' => "Size",
                'position' => "1",
                'values' => $this->getSizeValue($data)
            ]
        ],
        'associated_product_ids_serialized' => "[]",
        'configurable-matrix-serialized' => $this->getConfigurableMatrix($data)
    ];

    return $productData;
}

The important part is here:

 'configurable_attributes_data' => [
            self::COLOR_ATTRIBUTE_ID => [
                'attribute_id' => self::COLOR_ATTRIBUTE_ID,
                'code' => "color",
                'label' => "Color",
                'position' => "0",
                'values' => $this->getColorValue($data)
            ],
            self::SIZE_ATTRIBUTE_ID => [
                'attribute_id' => self::SIZE_ATTRIBUTE_ID,
                'code' => "size",
                'label' => "Size",
                'position' => "1",
                'values' => $this->getSizeValue($data)
            ]
        ],
'configurable-matrix-serialized' => $this->getConfigurableMatrix($data)

That would be the data indicating the simple products data.

Updated: These are methods for building simple products with configurable product:

private function getConfigurableMatrix($data)
{
    $jsonOutput = "[";
    // Get pair codes for matrix
    $colors = $data['colors'];
    $sizes = $this->getSizeArray($colors)['sizes'];
    $status = $this->isChildProductEnable();

    foreach ($colors as $color) {
        foreach ($sizes as $size) {
            $colorParam = [
                'id' => $this->getColorOptionId($color['color_id']),
                'lable' => $color['color_id']
            ];

            $sizeParam = [
                'id' => $this->getSizeOptionId($size['size']),
                'lable' => $size['size']
            ];

            $weight = $size['weight'] ? $size['weight'] : $this->getDefaultWeight();

            $jsonOutput .= $this->getConfigurableMatrixItem($data['title'], $size['sku'], $colorParam, $sizeParam, $size['quantity'], $weight, $size['price'], $status) . ",";
        }
    }

    $jsonOutput = rtrim($jsonOutput, ',');

    $jsonOutput .= "]";
    return $jsonOutput;
}



private function getConfigurableMatrixItem($name, $sku, $color = [], $size = [], $qty, $weight, $price, $status = 1)
{
    $item = [
        "id" => null,
        "product_link" => "",
        "name" => "$name {$color['lable']} {$size['lable']}",
        "sku" => "$sku",
        "status" => $status,
        "price" => "$price",
        "price_currency" => "$",
        "price_string" => "$$price",
        "weight" => "$weight",
        "qty" => "$qty",
        "variationKey" => "{$size['id']}-{$color['id']}",
        "configurable_attribute" => "{\"color\":\"{$color['id']}\",\"size\":\"{$size['id']}\"}",
        "thumbnail_image" => "",
        "media_gallery" => [
            "images" => []
        ],
        "image" => [],
        "attributes" => "Color : {$color['lable']}, Size: {$size['lable']}",
        "was_changed" => true,
        "canEdit" => 1,
        "newProduct" => 1,
        "record_id" => 0
    ];

    return json_encode($item);
}


private function getSizeOptionId($labelSize)
{
    if ($labelSize == '') return "";
    $attribute = $this->_eavConfig->getAttribute('catalog_product', 'size');

    $optionId = $attribute->getSource()->getOptionId($labelSize);

    if (!$optionId) {
        // Create a new Option
        $option['attribute_id'] = $attribute->getId();
        //$option['value'][$lableSize][0] = $lableSize;
        $option['value']['size'][0] = $labelSize;

        $eavSetup = $this->_eavSetupFactory->create();
        $eavSetup->addAttributeOption($option);

        $this->_eavConfig = $this->createObject('\Magento\Eav\Model\Config');
        $attribute = $this->_eavConfig->getAttribute('catalog_product', 'size');

        $optionId = $attribute->getSource()->getOptionId($labelSize);

        $this->insertSwatch($optionId, 0, $labelSize);
    }

    return $optionId;
}


private function getColorOptionId($labelColor)
{
    if ($labelColor == '') return "";
    $attribute = $this->_eavConfig->getAttribute('catalog_product', 'color');

    $optionId = $attribute->getSource()->getOptionId($labelColor);

    if (!$optionId) {
        // Create a new Option
        $option['attribute_id'] = $attribute->getId();
        //$option['value'][$labelColor][0] = $labelColor;
        $option['value']['color'][0] = $labelColor;

        $eavSetup = $this->_eavSetupFactory->create();
        $eavSetup->addAttributeOption($option);

        $this->_eavConfig = $this->createObject('\Magento\Eav\Model\Config');
        $attribute = $this->_eavConfig->getAttribute('catalog_product', 'color');

        $optionId = $attribute->getSource()->getOptionId($labelColor);

        $this->insertSwatch($optionId);
    }
    return $optionId;
}


private function insertSwatch($optionId, $type = 1, $value = "#ffffff")
{
    $swatch = $this->createObject('Magento\Swatches\Model\Swatch');

    $swatch->setData([
        'option_id' => $optionId,
        'store_id' => 0,
        'type' => $type,
        'value' => $value
    ]);

    $swatch->save();
}
Related Topic