Programatically creating products with custom attributes

I’m creating a product with a set of attributes using a cli script.

First of I’m setting the session for \Magento\Framework\App\State with setAreaCode('adminhtml') in the constructor. Then calling to a function which will create the product using the following:

public function __construct(
    \Magento\Catalog\Api\Data\ProductInterfaceFactory $productFactory,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->productFactory = $productFactory
    $this->productRepository = $productRepository
}

public function saveProduct(array $data): void
{
    $product = $this->getProduct($data['sku']);

    $product->setVisibility(self::DEFAULT_VISIBILITY);
    $product->setStatus(Status::STATUS_DISABLED);

    $product->setName($data['name']);
    $product->setSku($data['sku']);
    $product->setPrice($data['price']);
    $product->setAttributeSetId($product->getDefaultAttributeSetId());

    $product->setCustomAttribute('hardiness', $data['hardiness']);
    $product->setCustomAttribute('name_latin', $data['name_latin']);
    $product->setCustomAttribute('store_aisle_table', 1);
    $product->setCustomAttribute('store_aisle', $data['store_aisle']);

    $this->productRepository->save($product);
    $this->productRepository->save($product);
}

private function getProduct(string $sku): ProductInterface
{
    $product = null;

    try {
        $product = $this->productRepository->get($sku);
    } catch (NoSuchEntityException $e) {
        $product = $this->productFactory->create();
    }

    return $product;
}

So first of all the weirdness with using $this->productRepository->save() twice. It appears to me that some data cannot be set before the product exists in the database. e.g. the ‘price’ field doesn’t appear until I’ve used the save() function twice. However some of the attributes such as ‘price’ are required and as a result it won’t save the first time if this value hasn’t already been set.

The trouble is that the values set in the setCustomAttribute() function never appear in the admin.

From what I could discern from the database, once I do the second save() some other extra fields also appear in the database, specifically I was looking at the catalog_product_entity_varchar table, and the dummy values I had assigned to store_ailse had appeared in relation to the correct entity_id, however when I look at the product from the admin panel they don’t show up though.

Through some digging it appears that there is a bug in Magento 2.3 with the setCustomAttribute() function, however if I save the fields using the form in Catalog > Products to create a new product these fields get correctly filled in, so how is this form achieving it then.

Any pointers would be appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *