I'm trying to get, update, and save products &/or variants in my plugin controller, and am stuck on accessing/changing/saving updated fields.

// get product ID from post
$variant_id = craft()->request->getPost('variant_id');

// create criteria
$criteria = craft()->elements->getCriteria('Commerce_Variant');
$criteria->id = $variant_id;

// query
$variant = $criteria->first();

The above works just fine and gets the variant. But now I need to update a few fields and save it. Any idea how to do this?

$variant->getContent()->myCustomField = 'new value';

How would I then save $variant?

  • 1
    More proper answer now below... Nov 17 '16 at 5:02

This is the general mechanism for updating custom fields on elements - use setContentFromPost and then call the element's save function.

        'fieldHandle' => $newValue,

You should catch exceptions around that really, to handle any errors that may arise (as the model gets validated during save etc.)

  • I'm running into the same type of error I keep getting for trying to access fields etc. In this case it is: 'Call to a member function setContentFromPost() on a non-object' Am I going about retrieving the variant models the wrong way for it to not be returning an object?
    – taylor
    Nov 17 '16 at 7:23
  • Oops, I was getting an array returned through ->find(), changed to ->first(). Now your suggestion works! I'll be sure to catch exceptions. Super appreciate the help Jeremy.
    – taylor
    Nov 17 '16 at 7:26
  • 1
    No worries. Hoping you're going to build us all a totally sweet product editing system! Nov 17 '16 at 8:22

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.