1

I wish to save product with its attributes. I have tried below code,It works fine while saving simple products. but if i gave configurable product sku in my csv file, then it shows an error as

 PHP Fatal error:  Uncaught Magento\\Framework\\Exception\\InputException: Option values are not specified. 

Please proovide me a solution to save configurable product with its attributes

strong text myfile.php

<?php

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$file = 'csv/test.csv';
$headers = false;
$handle = fopen($file, "r");
if (empty($handle) === false) {
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {

        if ($row[0] == 'sku')
            continue;
        // get all the attibute and options
        $sku = $row[0];
        $color = $row[1];
        $colorAttrOptionId = getAttrOptionId('color', $color, $objectManager);
        $productId = $objectManager->get('Magento\Catalog\Model\Product')->getIdBySku($sku);
        $_product = $objectManager->get('Magento\Catalog\Model\Product')->load($productId);
        $_product->setColor($colorAttrOptionId);
        $_product->setWebsiteIds(array(1));
        $_product->save();
    }
}
fclose($handle);
echo "Sucess";

function getAttrOptionId($attributeCode, $attributeLabel, $objectManager)
{

    $eavConfig = $objectManager->get('Magento\Eav\Model\Entity\Attribute');
    $attributeId = $eavConfig->getIdByCode('catalog_product', $attributeCode);
    $attr = $objectManager->get('Magento\Eav\Model\Entity\Attribute')->load($attributeId);
    $attributeType = $attr->getFrontendInput();

    $attroptionid = array();
    if ($attr->usesSource()) {
        if (strpos($attributeLabel, ',')) {
            $multiselectLabel = explode(',', $attributeLabel);
            foreach ($multiselectLabel as $multiselect) {
                $multiattroptionid = $attr->setStoreId(0)->getSource()->getOptionId($multiselect);
                $attroptionid [] = $multiattroptionid;
            } return $attroptionid;
        } else {
            if ($attributeType == 'multiselect') {
                $optionid = $attr->setStoreId(0)->getSource()->getOptionId($attributeLabel);
                $attroptionid = $optionid;
                return $attroptionid;
            } else if ($attributeType == 'select') {
                $attrbuteoptionid = $attr->setStoreId(0)->getSource()->getOptionId($attributeLabel);
                return $attrbuteoptionid;
            }
        }
    }
}

csv file

enter image description here

Array of my csv file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.