craftcms / shopify

Synchronize and extend product data from your Shopify storefront.
MIT License
45 stars 25 forks source link

getDefaultVariant() returning null in a EVENT_BEFORE_SYNCHRONIZE_PRODUCT event during the sync #117

Closed bleepsandblops closed 5 months ago

bleepsandblops commented 5 months ago

Description

It looks like some products do not have a default variant, as I'm getting this error message when running the sync with an event (see below):

Exception 'TypeError' with message 'craft\shopify\elements\Product::getDefaultVariant(): Return value must be of type array, null returned'

in /var/www/html/vendor/craftcms/shopify/src/elements/Product.php:320

My code of the event:

Event::on(
            Products::class,
            Products::EVENT_BEFORE_SYNCHRONIZE_PRODUCT,
            function(ShopifyProductSyncEvent $event) {
                // Example 1: Cancel the sync if a flag is set via a Shopify metafield:
                $metafields = $event->element->getMetaFields();
                $product = $event->element;

                if (
                    ($product->shopifyStatus == 'archived') ||
                    ($product->publishedAt == null)
                ) {
                    $event->isValid = false;
                }

                // Example 2: Set a field value from metafield data:
                if (($event->isValid) && ($product->getDefaultVariant() !== null)) {
                    echo $product->title . "\n";
                    echo $product->publishedScope . "\n";
                    $event->element->setFieldValue('shopifyPrice', $product->getDefaultVariant()['price']);
                }
            }
        );

The only way to make it work is to remove the return type in the getDefaultVariant() function definition here.

It's a shop with thousands of products, but I can't quite find the reason why some go through and some don't.

Steps to reproduce

  1. Run the ./craft shopify/sync/products command
  2. Get the error message on some products

Additional info

linear[bot] commented 5 months ago

PT-1783 getDefaultVariant() returning null in a EVENT_BEFORE_SYNCHRONIZE_PRODUCT event during the sync

bleepsandblops commented 5 months ago

Apologies, this looks like a duplicate of https://github.com/craftcms/shopify/issues/112

nfourtythree commented 5 months ago

Information updated in #112 .

Closing this as a duplicate.

Thanks!