Commerce: How can I save a custom SKU from a plugin? I have a plugin that is listening to the onSaveProduct event.

In my product settings, in the "Automatic SKU Format" field I have: 

{product.title}


That way I am always working the main product title.

For the SKU, I want to only use the first initial of each word - so I am doing this from my plugin:

...
$default_sku = $event-&gt;params['product']-&gt;defaultVariant-&gt;sku;
$expr = '/(?&lt;=\s|^)[a-z]/i';

preg_match_all($expr, $default_sku, $matches);

$sku = strtoupper(implode('', $matches[0]));

...

error_log((craft()-&gt;config-&gt;get('devMode')) ? 'SKU: ' . $sku : '');


Let's say I have "My Super Product" as the title. The above is generating this: MSP  

Perfect!

But, now I'm not sure how to go back and re-save the product.

Do I need to re-find the product and then set the defaultSku and then re-save it? Not sure how to proceed.

Thank you for any suggestions!
You should be able to do this the usual way of setting entry fields in a plugin I think:

        $product-&gt;setContentFromPost(array(
            'sku' =&gt; $sku,
        );
        craft()-&gt;commerce_products-&gt;saveProduct($product);


(Alternatively, you could listen to onBeforeSaveProduct -  https://craftcommerce.com/docs/events-reference#commerce_products.onbeforesaveproduct - and since the product will be saved after that anyway you could probably leave out the call to saveProduct in that case)

I don't think I've tried it with products but it certainly works with orders for much the same sort of thing.