I want to create order via code in Craft Commerce. How can I achieve that?
Thanks in advance.
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:
// 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
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)
This is where the fun starts, which might depend on your definition of fun.
if (!Craft::$app->getElements()->saveElement($order)) {
var_dump($order->errors);
}