I have a plugin that is listening to the onSaveProduct event.

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


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->params['product']->defaultVariant->sku;
$expr = '/(?<=\s|^)[a-z]/i';

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

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


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

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


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:

            'sku' => $sku,

(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.

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.