3

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.

  • Can you first tell me image upload is your problem or how to save diffrent attribute when product create programetically in magento 2? – Dhiren Vasoya Oct 18 '16 at 9:36
  • Both Image Upload & Attribute As well. – Ankit Shah Oct 18 '16 at 9:42
  • [Update] Images Uploaded but not in Order as needed – Ankit Shah Oct 19 '16 at 4:03
  • Which Order you are talking about? – Dhiren Vasoya Oct 19 '16 at 4:40
  • Image Upload, Image 1, 2 & 3 it's not saved as mentioned. Order will be changed once saved in Table – Ankit Shah Oct 19 '16 at 5:48
5

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

  • 1
    Please help me to solve Backend Image related issue. Thanks – Ankit Shah Oct 24 '16 at 1:14
  • In this line - array(''label' => "Test", 'material' => 319), 'material' is your attribute name? – Dev Feb 28 '17 at 4:43
  • Yes it is. You can use your own – Ankit Shah Feb 28 '17 at 5:25
  • label is also another attribute right? so, we can add multiple custom attribute list in this array. – Dev Feb 28 '17 at 5:34
  • Yes both are customer attributes I have used for my purpose – Ankit Shah Feb 28 '17 at 5:43
3
+25

For upload image for product programmatically you used this code.

// Adding Image to product
$imagePath = "cnamessss.jpg"; // path of the image
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();

And I suggest you put your above code in try.....catch block, so if any error is occurs, you get idea.

  • Hi @Dhiren Let me try to check – Ankit Shah Oct 18 '16 at 10:02
  • Nope. It's not giving any error. Able to upload images but it's not within order. Updating Question – Ankit Shah Oct 19 '16 at 3:35
  • You are looking to set image1 as small_image, image2 as base image etc? – Dhiren Vasoya Oct 19 '16 at 6:09
  • No 3 different images wanna upload – Ankit Shah Oct 19 '16 at 6:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.