Magento 2 – Save All Product Data Outside Magento with Images

magento2PHPproductproduct-attributeproduct-images

I have below code with Image Upload which is working fine. But images are not stored in Database Table as mentioned in Order.

include('app/bootstrap.php');

use Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

try {
    $_product = $objectManager->create('Magento\Catalog\Model\Product');
    $_productImages = $objectManager->create('Magento\CatalogImportExport\Model\Import\Product');

    $importDir = __DIR__ . '/pub/media/import/';
    $image1Name = "1.jpg";
    $image2Name = "2.png";
    $image3Name = "3.png";
    $image1 = $importDir . $image1Name;
    $image2 = $importDir . $image2Name;
    $image3 = $importDir . $image3Name;

    //$_product->addData(array('custom_attribute' => 'foobar')); // To SET Attribute Value

    $_product->setName('Test Product')
            ->setDescription('Test Product')
            ->setShortDescription('Test Product')
            ->setUrlKey('test-product')
            ->setCategoryIds(array(38, 41))
            ->setTypeId('simple')
            ->setAttributeSetId(4)
            ->setSku('test-SKU')
            ->setWebsiteIds(array(1))
            ->setStoreId(1)
            ->setVisibility(4)
            ->setPrice(1.5)
            ->setStatus(1)
            ->setWeight(0.5);

    $_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
            )
    );

    $_product->addImageToMediaGallery($image1, array('image', 'small_image', 'thumbnail'), false, false); // Add Image 1
    $_product->addImageToMediaGallery($image2, array('image', 'small_image', 'thumbnail'), false, false); // Add Image 2    
    $_product->addImageToMediaGallery($image3, array('image', 'small_image', 'thumbnail'), false, false); // Add Image 3        
    $_product->save();

    echo "<pre>";
    echo "Product Id: ".$_product->getId();
    echo "</pre>";    
    exit;
} catch (Exception $e) {
    print_r($e->getMessage());
}

Images are not displaying in Order.

I have my Customer Attribute Set named "Furniture" with it's All Attributes. Example: Type, Color, Size

Attribute set i can set here mine using setAttributeSetId. How to set Particular Attribute Set's Attribute Value in Above Code.

In short i need to Set All Fields which You do from Magento Admin while Adding New Product.

Best Answer

Finally, I got mine 90% Answer. Posting to help the community.

Below code you can use Add Product with Image & Attribute Set & Attributes Outside Magento

This is for Single Product. For multiple product you have to put in Loop & you have to create Product Object Each Time

include('app/bootstrap.php');

use Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

try {
    $_product = $objectManager->create('Magento\Catalog\Model\Product');
    $_productImages = $objectManager->create('Magento\CatalogImportExport\Model\Import\Product');

    $importDir = __DIR__ . '/pub/media/import/';
    $image1Name = "1.jpg";
    $image2Name = "2.png";
    $image3Name = "3.png";
    $image1 = $importDir . $image1Name;
    $image2 = $importDir . $image2Name;
    $image3 = $importDir . $image3Name;

    $_product->setName('Test Product')
            ->setDescription('Test Product')
            ->setShortDescription('Test Product')
            ->setUrlKey('test-product')
            ->setCategoryIds(array(38, 41)) // 38 - A Category, 41 - B Category
            ->setTypeId('simple')
            ->setAttributeSetId(16) // 4 - Default, 16 - My Custom Attribute (Newly Created)
            ->setSku('test-SKU')
            ->setWebsiteIds(array(1)) // Your Website Id
            ->setStoreId(1) // Your Store Id
            ->setVisibility(4)
            ->setPrice(1.5)
            ->setStatus(1)
            ->setWeight(0.5);

    $_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
            )
    );

    // START SET ATTRIBUTES OF MY NEW ATTRIBUTE STE
    $_product->addData(
            array(
                'label' => "Test",
                'material' => 319, // 319 - Gold, 320  - Silver
            )
    );
    // END SET ATTRIBUTES OF MY NEW ATTRIBUTE STE

    // START SET IMAGES
    $_product->addImageToMediaGallery($image3, array('image', 'small_image', 'thumbnail'), false, false); // Add Image 3
    $_product->addImageToMediaGallery($image2, array('image', 'small_image', 'thumbnail'), false, false); // Add Image 2    
    $_product->addImageToMediaGallery($image1, array('image', 'small_image', 'thumbnail'), false, false); // Add Image 1        
    // STOP  SET IMAGES    


    $_product->save();

    echo "<pre>";
    echo "Success: Product Id: " . $_product->getId();
    echo "</pre>";
    exit;
} catch (Exception $e) {
    print_r($e->getMessage());
}

Below Pending Things & Queries

[1] Image Related Issue

Backend Catalog Product

  • Product Edit: In "Images & Videos", Image order is 1,3,2, it should take 1,2,3

[2] Attribute Dropdown Use Value instead of Id

Magento 2: Product/Customer Attribute with Dropdown Not Taking it's Given Value

Hoping for solution above queries.

Thanks

Related Topic