1

I have a custom plugin in which I have a controller action which I want to validate some values and then update a custom field on the Cart.

I can get the values from the form and validate them, I'm just missing how to get them saved to the Cart.

I've tried the following:

$this->cart->setRawPostContent('orderShippingOptions', $myValue);
$this->cart->setContentFromPost('fields');

And also just:

$this->cart->setContentFromPost(['orderShippingOptions' => $myValue]);

I'm feel like I'm in the right area, I'm just missing something simple.

Any help gratefully received.

3 Answers 3

3

You can do this directly as:

$cart->setContentFromPost(array( 'someKey' => $someValue ));
craft()->commerce_orders->saveOrder($cart);

(You'll need the saveOrder step as you're in your own controller, but note e.g. if you're doing this in e.g. a Commerce shipping calculator plugin, you can skip this step for efficiency reasons as a saveOrder occurs at the end of that process anyway).

3

Turns out I really overthought this one! It's exactly the same as you would usually do it in Craft.

$this->cart->getContent()->setAttributes(array(
    'orderShippingOptions' => $myValue
));

craft()->commerce_orders->saveOrder($this->cart);

The bit I was missing was craft()->commerce_orders->saveOrder($this->cart);

2
  • 2
    Or alternatively... $cart->setContentFromPost(array( 'someKey' => $someValue )); and then craft()->commerce_orders->saveOrder($cart); Commented May 23, 2016 at 13:06
  • Thanks Jeremy (again)! I thought I'd be pushing my luck if I asked you a follow up! This is much more succinct than mine, so if you want to add this as a proper answer, I'm happy to accept it. I'm going with this method. Commented May 23, 2016 at 13:24
2

For reference, the Craft 3 version of setContentFromPost is setFieldValuesFromRequest

And you can so things like:

$order->setFieldValue("customFieldHandle", "My value");

https://docs.craftcms.com/api/v3/craft-base-elementinterface.html#public-methods

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.