I am trying to update stock of product variants using a custom plugin on our Craft 3 eCommerce site (its a sync process with an external database). But I can't figure out how to update stock, I get an unknown property error for the field stock.
use Craft;
use craft\web\Controller;
use craft\helpers\ElementHelper;
use craft\commerce\elements\Product;
$productEntry = Product::find()->hasVariant(['sku' => 'mysku'])->first();
if($productEntry)
{
if (!$productEntry->hasUnlimitedStock)
{
$productEntry->setFieldValue('stock', '10');
echo Craft::$app->elements->saveElement($productEntry);
}
}
But I get a "Setting unknown property: craft\behaviors\CustomFieldBehavior::stock" error:-
2021-01-18 11:21:33 [-][1][9319132c27bbf8aa77f29e2606c2b4ea][error][yii\base\UnknownPropertyException] yii\base\UnknownPropertyException: Setting unknown property: craft\behaviors\CustomFieldBehavior::stock in /home/mysite/craftcms/vendor/yiisoft/yii2/base/BaseObject.php:163
Stack trace:
#0 /home/mysite/craftcms/storage/runtime/compiled_classes/CustomFieldBehavior_zmbofhbcdvie.php(895): yii\base\BaseObject->__set('stock', '10')
#1 /home/mysite/craftcms/vendor/craftcms/cms/src/base/Element.php(2672): craft\behaviors\CustomFieldBehavior->__set('stock', '10')
#2 /home/mysite/craftcms/plugins/mysite/src/controllers/SyncController.php(225): craft\base\Element->setFieldValue('stock', '10')
#3 /home/mysite/craftcms/plugins/mysite/src/controllers/SyncController.php(90): mysite\mysite\controllers\SyncController->updateEntries(Array)
#4 [internal function]: mysite\mysite\controllers\SyncController->actionSyncStock()
#5 /home/mysite/craftcms/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#6 /home/mysite/craftcms/vendor/yiisoft/yii2/base/Controller.php(180): yii\base\InlineAction->runWithParams(Array)
#7 /home/mysite/craftcms/vendor/craftcms/cms/src/web/Controller.php(190): yii\base\Controller->runAction('sync-stock', Array)
#8 /home/mysite/craftcms/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('sync-stock', Array)
#9 /home/mysite/craftcms/vendor/craftcms/cms/src/web/Application.php(274): yii\base\Module->runAction('mysite/sync/sy...', Array)
#10 /home/mysite/craftcms/vendor/craftcms/cms/src/web/Application.php(577): craft\web\Application->runAction('mysite/sync/sy...', Array)
#11 /home/mysite/craftcms/vendor/craftcms/cms/src/web/Application.php(253): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#12 /home/mysite/craftcms/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#13 /home/mysite/public_html/index.php(23): yii\base\Application->run()
#14 {main}
2021-01-18 11:21:32 [-][1][9319132c27bbf8aa77f29e2606c2b4ea][info][application] $_GET = [
'p' => 'actions/mysite/sync/sync-stock'
]