1

I am trying to add a Single Product with the following code. Even though I set the StoreId to 0 and Status to Enabled, the product is saved with Status disabled and StoreId 3.

It is really annoying that these attributes are not changing no matter I do.

<?php
$product = $this->productFactory->create();
$product->setStoreId(0);
$product->setWebsiteIds($this->websiteIds);
$product->setSku($fullStock->getSku() . '_' . $fullStock->getLot());
$product->setName($parentProduct->getName() . " (" . $fullStock->getLot() . ")");
$product->setAttributeSetId($parentProduct->getAttributeSetId());
$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$product->setVisibility($parentProduct->getVisibility());
$product->setTypeId('simple');
$product->setWeight($parentProduct->getWeight());
$product->setExtensionAttributes($parentProduct->getExtensionAttributes());
$product->setOptions($parentProduct->getOptions());
$product->setCustomAttributes($parentProduct->getCustomAttributes());
$product->setParentSku($fullStock->getSku());
$product->setLotSku($fullStock->getLot());
$product->setIsLot(true);
$product->setPrice($productPrice->getRegularPrice());
if (
    $productPrice->getPromotionalPrice() !== null &&
    $productPrice->getPromotionalPrice()->getStartDate() < new \DateTime() &&
    $productPrice->getPromotionalPrice()->getEndDate() > new \DateTime()
) {
    $product->setData('special_price', $productPrice->getPromotionalPrice()->getValue());
    $product->setData('special_from_date', $productPrice->getPromotionalPrice()->getStartDate()->format('Y-m-d'));
    $product->setData('special_to_date', $productPrice->getPromotionalPrice()->getEndDate()->format('Y-m-d'));
}
try {
    $product = $this->productRepository->save($product);
} catch (\Exception $e) {
    $this->logger->warning("New lot product cannot be saved. (LOT: {$fullStock->getLot()}) (PARENT_SKU: {$parentProduct->getSku()})");
    $this->logger->warning($e->getMessage());
    return false;
}

EDIT2: I cannot change the StoreId of a product. Here is the steps to reproduce.

<?php
// $this->fullStockUpdate->execute();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productFactory = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterfaceFactory::class);
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);

/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$sku = "Product - ".\time();
$name = "Product - ".\time();
$product = $productFactory->create();
$product->setSku($sku)
    ->setName($name)
    ->setTypeId('simple')
    ->setVisibility(4)
    ->setPrice(1) //set sample price, the price will manually set
    ->setAttributeSetId(4) // Default attribute set for products
    ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
    ->setStore(0)
    ->setIsLot(false);
//set different url for simple products with the same name,
$url = strtolower(preg_replace('#[^0-9a-z]+#i', '-', $name));
$product->setUrlKey($url);
try {
    $product = $productRepository->save($product);
    echo "(1) (ID: {$product->getId()}) (SKU: {$product->getSku()}) (STATUS: {$product->getStatus()}) (STORE: {$product->getStoreId()})\n";
} catch (\Exception $e) {
    echo $e->getMessage();
    echo "\n";
    echo $e->getTraceAsString();
    return;
}

try {
    $product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
    $product = $productRepository->save($product);
    echo "(2) (ID: {$product->getId()}) (SKU: {$product->getSku()}) (STATUS: {$product->getStatus()}) (STORE: {$product->getStoreId()})\n";
} catch (\Exception $e) {
    echo $e->getMessage();
    echo "\n";
    echo $e->getTraceAsString();
}

Here is the outputs:

(1) (ID: 6637) (SKU: Product - 1499427117) (STATUS: 2) (STORE: 3)
(2) (ID: 6637) (SKU: Product - 1499427117) (STATUS: 2) (STORE: 3)
0

Debug your stores, how many stores you have. Try simple products with minimal data.
The following code create simple product with base minmal product options. If the product will be created right like you expected, then debug the other options you have added in your code. Debug your code step by step.

                    $product = $this->productFactory->create();
                    $product->setSize($size)
                            ->setColor($color)
                            ->setSku($sku)
                            ->setName($name)
                            ->setTypeId('simple')
                            ->setVisibility(4)
                            ->setPrice(1) //set sample price, the price will manually set
                            ->setAttributeSetId(4) // Default attribute set for products
                            ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
                        //set different url for simple products with the same name,
                        $url = strtolower(preg_replace('#[^0-9a-z]+#i', '-', $name));
                        $product->setUrlKey($url);
                        $this->productRepository->save($product);
  • I have 3 store views. It is setting the store 3 by default. – Bunyamin Inan Jul 7 '17 at 11:27
0

Right now there is not solution for this bug. You can follow the issue with the following link http://github.com/magento/magento2/issues/5664.

Here is a workaround. I do not like work-arounds, but it works.

Here is the dependencies:

public function __construct(
    \Magento\Framework\App\ResourceConnection $resourceConnection
){
    $this->resourceConnection = $resourceConnection;
}

Here is the status update code:

/**
 * Changes product status
 *
 * This function changes the status of given product.
 *
 * @param \Magento\Catalog\Api\Data\ProductInterface $product
 * @param int $status
 */
protected function changeStatus(\Magento\Catalog\Api\Data\ProductInterface $product, $status)
{
    $resourceConnection = $this->resourceConnection;
    $connection = $resourceConnection->getConnection();

    $tableEavAttribute = $resourceConnection->getTableName('eav_attribute');
    $tableProductEntityInt = $resourceConnection->getTableName('catalog_product_entity_int');
    $tableEavEntityType = $resourceConnection->getTableName('eav_entity_type');

    $entityTypeIdProduct = $connection->fetchOne("SELECT `entity_type_id` FROM `{$tableEavEntityType}` WHERE `entity_type_code` = 'catalog_product' LIMIT 0,1;");
    $attributeIdStatus = $connection->fetchOne("SELECT `attribute_id` FROM `{$tableEavAttribute}` WHERE `attribute_code` = 'status' AND `entity_type_id` = {$entityTypeIdProduct}");
    $connection->update($tableProductEntityInt, ['value' => $status], "`attribute_id` = {$attributeIdStatus} AND `row_id` = {$product->getRowId()}");
}

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.