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

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

| improve this answer | |
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);

| improve this answer | |
  • 2
    Or alternatively... $cart->setContentFromPost(array( 'someKey' => $someValue )); and then craft()->commerce_orders->saveOrder($cart); – Jeremy Daalder May 23 '16 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. – Steve Holland May 23 '16 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

| improve this answer | |

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.