Программное создание настраиваемого продукта Magento

Как вы знаете, настраиваемый продукт magento -это продукт с простыми продуктами, которые отличаются назначенным им самим параметром (атрибутом).

Мы можем использовать этот вывод для расширения нашего кода для создания простых продуктов для работы с конфигурируемыми.

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$simpleProduct = Mage::getModel('catalog/product');
try {
$simpleProduct
    ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
    ->setAttributeSetId(20) //ID of a attribute set named 'default'
    ->setTypeId('simple') //product type
    ->setCreatedAt(Mage::getModel('core/date')->date('Y-m-d H:i:s')) //product creation time
    ->setSku('simple-green') //SKU
    ->setName('test simple product green color') //product name
    ->setWeight(4.0000)
    ->setStatus(1) //product status (1 - enabled, 2 - disabled)
    ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
    ->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)
    ->setPrice(11.22) //price in form 11.22
    ->setCost(22.33) //price in form 11.22
    ->setSpecialPrice(00.44) //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)
    ->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
    ->setMetaTitle('test meta title 2')
    ->setMetaKeyword('test meta keyword 2')
    ->setMetaDescription('test meta description 2')
    ->setDescription('This is a long description')
    ->setShortDescription('This is a short description')
    ->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
    ->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' => 999 //qty
        )
    )
    ->setCategoryIds(array(3, 10)); //assign product to categories
    $simpleProduct->save();
} catch (Exception $e) {
    Mage::log($e->getMessage());
    echo $e->getMessage();
}

Приведенный выше код создаст простой продукт.

Теперь нам нужно создать настраиваемый продукт и назначить ему этот простой продукт.

$configProduct = Mage::getModel('catalog/product');,
try {
$configProduct
        ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
        ->setAttributeSetId(20) //ID of a attribute set named 'default'
        ->setTypeId('configurable') //product type
        ->setCreatedAt(Mage::getModel('core/date')->date('Y-m-d H:i:s')) //product creation time
        ->setSku('configurable-product') //SKU
        ->setName('test config product') //product name
        ->setWeight(4.0000)
        ->setStatus(1) //product status (1 - enabled, 2 - disabled)
        ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
        ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
        ->setManufacturer(28) //manufacturer id
        ->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)
        ->setPrice(11.22) //price in form 11.22
        ->setCost(22.33) //price in form 11.22
        ->setSpecialPrice(00.44) //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)
        ->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
        ->setMetaTitle('test meta title 2')
        ->setMetaKeyword('test meta keyword 2')
        ->setMetaDescription('test meta description 2')
        ->setDescription('This is a long description')
        ->setShortDescription('This is a short description')
        ->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
        ->setStockData(array(
                'use_config_manage_stock' => 0, //'Use config settings' checkbox
                'manage_stock' => 1, //manage stock
                'is_in_stock' => 1, //Stock Availability
            )
        )
        ->setCategoryIds(array(3, 10)) //assign product to categories
    ;
    /**/
    /** assigning associated product to configurable */
    /**/
    $configProduct->getTypeInstance()->setUsedProductAttributeIds(array(92)); //attribute ID of attribute 'color' in my store
    $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
 
    $configProduct->setCanSaveConfigurableAttributes(true);
    $configProduct->setConfigurableAttributesData($configurableAttributesData);
 
    $configurableProductsData = array();
    $configurableProductsData['920'] = array( //['920'] = id of a simple product associated with this configurable
        '0' => array(
            'label' => 'Green', //attribute label
            'attribute_id' => '92', //attribute ID of attribute 'color' in my store
            'value_index' => '24', //value of 'Green' index of the attribute 'color'
            'is_percent' => '0', //fixed/percent price for this option
            'pricing_value' => '21' //value for the pricing
        )
    );
    $configProduct->setConfigurableProductsData($configurableProductsData);
    $configProduct->save();
 
    echo 'success';
} catch (Exception $e) {
    Mage::log($e->getMessage());
    echo $e->getMessage();
}

И это все! Ваш настраиваемый продукт должен быть правильно настроен и виден на интерфейсе!

Обратите внимание, что необходимо назначить один и тот же набор атрибутов как конфигурируемому продукту, так и связанным с ним продуктам.

В комментариях кода Вы найдете короткий комментарий для каждого из используемых методов.

статья взята с сайта:https://inchoo.net/

чек на запчасти

Добавить комментарий