0

I want to create order via code in Craft Commerce. How can I achieve that?

Thanks in advance.

2

First of all, it's important to know what version(s) of Craft and Commerce you're referring to. The code used in this answer applies to Craft 3, with Commerce 2-beta. Code for Craft 2 and Commerce 1 would look different, but the logic is similar.


I would start by looking at Commerce's codebase on Github (or in your plugins folder, if it's Craft 2), and more specifically the OrdersController, and even more specifically the actionSaveOrder and _setOrderFromPost methods.

It looks to me like you need to do two things:

Get an Order model:

// Find an existing order by ID
$order = Commerce::getInstance()->orders->getOrderById($orderId);

// ... Or create a new one
$order = new Order; # Don't forget to place use craft\commerce\elements\Order above your class

Populate the model (untested)

If you have an order model, you have to populate all the fields that matter. Status, addresses, I think you'd best start on an individual order page in the admin to see what fields are needed.

$order->isCompleted = true;
$order->billingAddressId = 4;
$order->gatewayId = 7;
... etc (includes creating and adding line items for your order)

Save the order and show why it doesn't work magically the first time around ;)

This is where the fun starts, which might depend on your definition of fun.

if (!Craft::$app->getElements()->saveElement($order)) {
    var_dump($order->errors);
}
2
  • Thanks for your reply. I am quite new to craft. So if you can share more detail then it will help me. Like, - Adding line items - Assigning payment method - Assigning address
    – user8244
    Apr 12 '18 at 13:52
  • 1
    It really depends on your use case and needs. I think you need to familiarize yourself with the underlying code (so, take a look at how Commerce does it) before trying anything as potentially complex as programmatically creating orders. This really is all I can provide you with, time wise, without actually building it for you ;)
    – Paul
    Apr 12 '18 at 13:56

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.