Order

Type
Class
Namespace
craft\commerce\elements
Inherits
craft\commerce\elements\Order » craft\base\Element » craft\base\Component » craft\base\Model » yii\base\Model » yii\base\Component » yii\base\BaseObject
Implements
ArrayAccess, IteratorAggregate, craft\base\ComponentInterface, craft\base\ElementInterface, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface
Uses traits
craft\base\ClonefixTrait, craft\base\ElementTrait, craft\commerce\elements\traits\OrderDeprecatedTrait, craft\commerce\elements\traits\OrderElementTrait, craft\commerce\elements\traits\OrderValidatorsTrait, yii\base\ArrayableTrait, yii\base\StaticInstanceTrait
Since
2.0

Order or Cart model.

View source

# Public Properties

Property Description
activeValidators yii\validators\Validator – The validators applicable to the current scenario.
adjustmentSubtotal float, integer
adjustments craft\commerce\models\OrderAdjustment[]
adjustmentsTotal float
ancestors craft\elements\db\ElementQueryInterface, craft\base\ElementInterface
archived boolean – Whether the element is archived
attributes array – Attribute values (name => value).
availableShippingMethodOptions craft\commerce\models\ShippingMethodOption[]
availableShippingMethods craft\commerce\base\ShippingMethodInterface[]
awaitingFieldValues boolean – Whether the element is still awaiting its custom field values
behaviors yii\base\Behavior – List of behaviors attached to this component
billingAddress craft\commerce\models\Address, null
billingAddressId integer, null – Billing address ID
billingSameAsShipping boolean – Make this the shipping address the same as the billing address
cancelUrl string – Cancel URL
children craft\elements\db\ElementQueryInterface, craft\base\ElementInterface
contentId integer, null – The element’s content row ID
contentTable string
couponCode string, null – Coupon Code
cpEditUrl string, null
currency string – Currency
currentRevision craft\base\ElementInterface, null
customer craft\commerce\models\Customer, null
customerId integer – Customer ID
customerLinkHtml string
dateAuthorized DateTime – Date authorized
dateCreated DateTime, null – The date that the element was created
dateDeleted DateTime, null – The date that the element was trashed
dateOrdered DateTime – Date ordered
datePaid DateTime – Date paid
dateUpdated DateTime, null – The date that the element was last updated
descendants craft\elements\db\ElementQueryInterface, craft\base\ElementInterface
dirtyAttributes string[]
dirtyFields string[]
draftId integer, null – The ID of the draft’s row in the drafts table
duplicateOf craft\base\ElementInterface, null – The element that this element is being duplicated by.
editorHtml string – The HTML for the editor HUD
email string, null
enabled boolean – Whether the element is enabled
enabledForSite boolean, null – Whether the element is enabled for the given site.
errors array – Errors for all attributes or the specified attribute.
estimatedBillingAddress craft\commerce\models\Address, null
estimatedBillingAddressId integer – Estimated Billing address ID
estimatedBillingSameAsShipping boolean – Whether estimated billing address should be set to the same address as estimated shipping
estimatedShippingAddress craft\commerce\models\Address, null
estimatedShippingAddressId integer – Estimated Shipping address ID
fieldColumnPrefix string
fieldContext string
fieldLayout craft\models\FieldLayout, null
fieldLayoutId integer, null – The element’s field layout ID
fieldParamNamespace string, null – The field param namespace
fieldValues array – The field values (handle => value)
firstErrors array – The first errors.
gateway craft\commerce\base\GatewayInterface, null
gatewayId integer, null – Gateway ID
gqlTypeName string
hardDelete boolean – Whether the element is being hard-deleted.
hasDescendants boolean
hasFreshContent boolean – Whether the element’s content is fresh
histories craft\commerce\models\OrderHistory[]
id integer, null – The element’s ID
isActiveCart boolean
isCompleted boolean – Is completed
isDraft boolean
isEditable boolean
isEmpty boolean
isHomepage boolean
isPaid boolean
isRevision boolean
isUnpaid boolean
isUnsavedDraft boolean
itemSubtotal float
itemTotal float
iterator ArrayIterator – An iterator for traversing the items in the list.
lastIp string, null – Last IP address
lastTransaction craft\commerce\models\Transaction, null
level integer, null – The element’s level within its structure
lft integer, null – The element’s left position within its structure
lineItems craft\commerce\models\LineItem[]
link \Twig\Markup, null
makePrimaryBillingAddress boolean – Make this the customer‘s primary billing address
makePrimaryShippingAddress boolean – Make this the customer‘s primary shipping address
message string, null – Message
nestedTransactions craft\commerce\models\Transaction[]
newSiteIds integer[] – The site IDs that the element was just propagated to for the first time.
next craft\base\ElementInterface, null
nextSibling craft\base\ElementInterface, null
number string – Number
orderAdjustments array
orderLanguage integer, null – Order status ID
orderStatus craft\commerce\models\OrderStatus, null
orderStatusHtml string
orderStatusId integer, null – Order status ID
origin string – Order origin
outstandingBalance float
paidStatus string
paidStatusHtml string
parent craft\base\ElementInterface, null
paymentCurrency string
paymentSource craft\commerce\models\PaymentSource, null
paymentSourceId boolean – Payment source ID
pdfUrl string, null – The URL to the order’s PDF invoice, or null if the PDF template doesn’t exist
prev craft\base\ElementInterface, null
prevSibling craft\base\ElementInterface, null
previewTargets array
previewing boolean – Whether the element is currently being previewed.
propagateAll boolean – Whether all element attributes should be propagated across all its supported sites, even if that means overwriting existing site-specific values.
propagating boolean – Whether the element is being saved in the context of propagating another site's version of the element.
recalculationMode string
ref string, null
reference string – Reference
registerUserOnOrderComplete boolean – Register user on order complete
resaving boolean – Whether the element is being resaved by a ResaveElement job or a resave console command.
returnUrl string – Return URL
revisionId integer – The ID of the revision’s row in the revisions table
rgt integer, null – The element’s right position within its structure
root integer, null – The element’s structure’s root ID
route mixed – The route that the request should use, or null if no special action should be taken
scenario string – The scenario that this model is in.
searchScore integer, null – The element’s search score, if the craft\elements\db\ElementQuery::search() parameter was used when querying for the element
serializedFieldValues array
shippingAddress craft\commerce\models\Address, null
shippingAddressId integer, null – Shipping address ID
shippingMethod craft\commerce\models\ShippingMethod, null
shippingMethodHandle string – Shipping Method Handle
shippingMethodId integer, null
shippingSameAsBilling boolean – Make this the shipping address the same as the billing address
shortNumber string
shouldRecalculateAdjustments boolean
siblings craft\elements\db\ElementQueryInterface, craft\base\ElementInterface
site craft\models\Site
siteId integer, null – The site ID the element is associated with
slug string, null – The element’s slug
sourceId integer, null
sourceUid string
status string, null
storedItemTotal float – The item total as stored in the database from last retrieval
storedTotalDiscount float – The total of discount adjustments as stored in the database from last retrieval
storedTotalPaid float – The total paid as stored in the database from last retrieval
storedTotalPrice float – The total price as stored in the database from last retrieval
storedTotalShippingCost float – The total shipping cost adjustments as stored in the database from last retrieval
storedTotalTax float – The total tax adjustments as stored in the database from last retrieval
storedTotalTaxIncluded float – The total tax included adjustments as stored in the database from last retrieval
structureId integer, null – The element’s structure ID
supportedSites integer[], array
tempId string, null – The element’s temporary ID (only used if the element's URI format contains {id})
title string, null – The element’s title
total float
totalAuthorized float
totalDescendants integer
totalDiscount float
totalPaid float
totalPrice float
totalQty integer
totalSaleAmount float
totalShippingCost float
totalTax float
totalTaxIncluded float
totalTaxablePrice float
totalWeight float
transactions craft\commerce\models\Transaction[]
trashed boolean – Whether the element has been soft-deleted.
uiLabel string
uid string, null – The element’s UID
uri string, null – The element’s URI
uriFormat string, null
url string, null
user craft\elements\User, null
validators ArrayObject, yii\validators\Validator – All the validators declared in the model.

# adjustmentSubtotal

Type
float, integer
Access
Read-only

View source

# adjustments

Type
craft\commerce\models\OrderAdjustment[]

View source

# adjustmentsTotal

Type
float
Access
Read-only

View source

# availableShippingMethodOptions

Type
craft\commerce\models\ShippingMethodOption[]
Access
Read-only
Since
3.1

View source

# billingAddress

Type
craft\commerce\models\Address, null

View source

# billingAddressId

Type
integer, null

Billing address ID

View source

Example

echo $order->billingAddressId;

# billingSameAsShipping

Type
boolean

Make this the shipping address the same as the billing address

View source

Example

echo $order->billingSameAsShipping;

# cancelUrl

Type
string

Cancel URL

View source

Example

echo $order->cancelUrl;

# couponCode

Type
string, null

Coupon Code

View source

Example

echo $order->couponCode;

# cpEditUrl

Type
string, null
Access
Read-only

View source

# currency

Type
string

Currency

View source

Example

echo $order->currency;

# customer

Type
craft\commerce\models\Customer, null

View source

# customerId

Type
integer

Customer ID

View source

# customerLinkHtml

Type
string
Access
Read-only
Since
3.0

View source

# dateAuthorized

Type
DateTime

Date authorized

View source

Example

echo $order->dateAuthorized;

# dateOrdered

Type
DateTime

Date ordered

View source

Example

echo $order->dateOrdered;

# datePaid

Type
DateTime

Date paid

View source

Example

echo $order->datePaid;

# email

Type
string, null

View source

# estimatedBillingAddress

Type
craft\commerce\models\Address, null
Since
2.2

View source

# estimatedBillingAddressId

Type
integer
Since
2.2

Estimated Billing address ID

View source

# estimatedBillingSameAsShipping

Type
boolean
Since
2.2

Whether estimated billing address should be set to the same address as estimated shipping

View source

# estimatedShippingAddress

Type
craft\commerce\models\Address, null
Since
2.2

View source

# estimatedShippingAddressId

Type
integer
Since
2.2

Estimated Shipping address ID

View source

# gateway

Type
craft\commerce\base\GatewayInterface, null
Access
Read-only

View source

# gatewayId

Type
integer, null

Gateway ID

View source

Example

echo $order->gatewayId;

# histories

Type
craft\commerce\models\OrderHistory[]
Access
Read-only

View source

# isActiveCart

Type
boolean
Access
Read-only

View source

# isCompleted

Type
boolean

Is completed

View source

Example

echo $order->isCompleted;

# isEditable

Type
boolean
Access
Read-only

View source

# isEmpty

Type
boolean
Access
Read-only

View source

# isPaid

Type
boolean
Access
Read-only

View source

# isUnpaid

Type
boolean
Access
Read-only

View source

# itemSubtotal

Type
float
Access
Read-only

View source

# itemTotal

Type
float
Access
Read-only

View source

# lastIp

Type
string, null

Last IP address

View source

Example

echo $order->lastIp;

# lastTransaction

Type
craft\commerce\models\Transaction, null
Access
Read-only

View source

# lineItems

Type
craft\commerce\models\LineItem[]

View source

Type
\Twig\Markup, null
Access
Read-only

View source

# makePrimaryBillingAddress

Type
boolean

Make this the customer‘s primary billing address

View source

Example

echo $order->makePrimaryBillingAddress;

# makePrimaryShippingAddress

Type
boolean

Make this the customer‘s primary shipping address

View source

Example

echo $order->makePrimaryShippingAddress;

# message

Example

echo $order->message;

# nestedTransactions

Type
craft\commerce\models\Transaction[]
Access
Read-only

View source

# number

Example

echo $order->number;

# orderAdjustments

Type
array
Access
Read-only

View source

# orderLanguage

Type
integer, null

Order status ID

View source

Example

echo $order->orderStatusId;

# orderStatus

Type
craft\commerce\models\OrderStatus, null
Access
Read-only

View source

# orderStatusHtml

Type
string
Access
Read-only

View source

# orderStatusId

Type
integer, null

Order status ID

View source

Example

echo $order->orderStatusId;

# origin

Type
string

Order origin

View source

Example

echo $order->origin;

# outstandingBalance

Type
float
Access
Read-only

View source

# paidStatus

Type
string
Access
Read-only

View source

# paidStatusHtml

Type
string
Access
Read-only

View source

# paymentCurrency

Type
string

View source

# paymentSource

Type
craft\commerce\models\PaymentSource, null

View source

# paymentSourceId

Type
boolean

Payment source ID

View source

Example

echo $order->paymentSourceId;

# pdfUrl

Type
string, null
Access
Read-only

The URL to the order’s PDF invoice, or null if the PDF template doesn’t exist

View source

# recalculationMode

Type
string

View source

# reference

Type
string

Reference

View source

Example

echo $order->reference;

# registerUserOnOrderComplete

Type
boolean

Register user on order complete

View source

Example

echo $order->registerUserOnOrderComplete;

# returnUrl

Type
string

Return URL

View source

Example

echo $order->returnUrl;

# shippingAddress

Type
craft\commerce\models\Address, null

View source

# shippingAddressId

Type
integer, null

Shipping address ID

View source

Example

echo $order->shippingAddressId;

# shippingMethod

Type
craft\commerce\models\ShippingMethod, null
Access
Read-only

View source

# shippingMethodHandle

Type
string

Shipping Method Handle

View source

# shippingMethodId

Type
integer, null
Access
Read-only

View source

# shippingSameAsBilling

Type
boolean

Make this the shipping address the same as the billing address

View source

Example

echo $order->shippingSameAsBilling;

# shortNumber

Type
string
Access
Read-only

View source

# storedItemTotal

Type
float

The item total as stored in the database from last retrieval

View source

Example

echo $order->storedItemTotal;

# storedTotalDiscount

Type
float

The total of discount adjustments as stored in the database from last retrieval

View source

Example

echo $order->storedTotalDiscount;

# storedTotalPaid

Type
float

The total paid as stored in the database from last retrieval

View source

Example

echo $order->storedTotalPaid;

# storedTotalPrice

Type
float

The total price as stored in the database from last retrieval

View source

Example

echo $order->storedTotalPrice;

# storedTotalShippingCost

Type
float

The total shipping cost adjustments as stored in the database from last retrieval

View source

Example

echo $order->storedTotalShippingCost;

# storedTotalTax

Type
float

The total tax adjustments as stored in the database from last retrieval

View source

Example

echo $order->storedTotalTax;

# storedTotalTaxIncluded

Type
float

The total tax included adjustments as stored in the database from last retrieval

View source

Example

echo $order->storedTotalTaxIncluded;

# total

Type
float
Access
Read-only

View source

# totalAuthorized

Type
float
Access
Read-only

View source

# totalDiscount

Type
float
Access
Read-only

View source

# totalPaid

Type
float
Access
Read-only

View source

# totalPrice

Type
float
Access
Read-only

View source

# totalQty

Type
integer
Access
Read-only

View source

# totalSaleAmount

Type
float
Access
Read-only

View source

# totalShippingCost

Type
float
Access
Read-only

View source

# totalTax

Type
float
Access
Read-only

View source

# totalTaxIncluded

Type
float
Access
Read-only

View source

# totalTaxablePrice

Type
float
Access
Read-only

View source

# totalWeight

Type
float
Access
Read-only

View source

# transactions

Type
craft\commerce\models\Transaction[]
Access
Read-only

View source

# user

Type
craft\elements\User, null
Access
Read-only

View source

# Protected Properties

Property Description
revisionCreatorId string, null – Revision creator ID to be saved
revisionNotes string, null – Revision notes to be saved

# Public Methods

Method Description
__call() Calls the named method which is not a class method.
__clone()
__construct() Constructor.
__get() Returns the value of a component property.
__isset() Checks if a property is set.
__set() Sets the value of a component property.
__toString() Returns the string representation of the element.
__unset() Sets a component property to be null.
_getAdjustmentsTotalByType()
actions() Returns the available element actions for a given source.
activeAttributes() Returns the attribute names that are subject to validation in the current scenario.
addError() Adds a new error to the specified attribute.
addErrors() Adds a list of errors.
addLineItem() Adds a line item to the order. Updates the line item if the ID of that line item is already in the cart.
addModelErrors() Adds errors from another model, with a given attribute name prefix.
afterDelete() Performs actions after an element is deleted.
afterMoveInStructure() Performs actions after an element is moved within a structure.
afterOrderComplete() Called after the order successfully completes
afterPropagate() Performs actions after an element is fully saved and propagated to other sites.
afterRestore() Performs actions after an element is restored.
afterSave() Performs actions after an element is saved.
afterValidate() This method is invoked after validation ends.
attachBehavior() Attaches a behavior to this component.
attachBehaviors() Attaches a list of behaviors to the component.
attributeHints() Returns the attribute hints.
attributeLabels() Returns the attribute labels.
attributes() Returns the list of attribute names.
beforeDelete() Performs actions before an element is deleted.
beforeMoveInStructure() Performs actions before an element is moved within a structure.
beforeRestore() Performs actions before an element is restored.
beforeSave() Performs actions before an element is saved.
beforeValidate() This method is invoked before validation starts.
behaviors()
canGetProperty() Returns a value indicating whether a property can be read.
canSetProperty() Returns a value indicating whether a property can be set.
className() Returns the fully qualified name of this class.
clearErrors() Removes errors for all attributes or a single attribute.
createValidators() Creates validator objects based on the validation rules specified in rules().
currencyAttributes() The attributes on the order that should be made available as formatted currency.
datetimeAttributes() Returns the names of any attributes that should hold DateTime values.
defaultTableAttributes() Returns the list of table attribute keys that should be shown by default.
defineRules() Returns the validation rules for attributes.
detachBehavior() Detaches a behavior from the component.
detachBehaviors() Detaches all behaviors from the component.
displayName()
eagerLoadingMap() Returns an array that maps source-to-target element IDs based on the given sub-property handle.
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component.
exporters() Returns the available export options for a given source.
extraFields() Returns the list of fields that can be expanded further and returned by toArray().
fields()
find() Creates an \ElementQueryInterface instance for query purpose.
findAll() Returns a list of elements that match the specified ID(s) or a set of element criteria parameters.
findOne() Returns a single element instance by a primary key or a set of element criteria parameters.
formName() Returns the form name that this model class should use.
generateAttributeLabel() Generates a user friendly attribute label based on the give attribute name.
getActiveValidators() Returns the validators applicable to the current scenario.
getAdjustmentSubtotal() Returns the total of adjustments made to order.
getAdjustments()
getAdjustmentsByType()
getAdjustmentsTotal()
getAdjustmentsTotalByType()
getAncestors() Returns the element’s ancestors.
getAttributeHint() Returns the text hint for the specified attribute.
getAttributeLabel() Returns the text label for the specified attribute.
getAttributeStatus() Returns the status of a given attribute.
getAttributes() Returns attribute values.
getAvailableShippingMethodOptions()
getAvailableShippingMethods()
getBehavior() Returns the named behavior object.
getBehaviors() Returns all behaviors attached to this component.
getBillingAddress() Get the billing address on the order.
getChildren() Returns the element’s children.
getContentTable() Returns the name of the table this element’s content is stored in.
getCpEditUrl() Returns the element’s edit URL in the control panel.
getCurrentRevision() Returns the element’s current revision, if one exists.
getCustomer()
getCustomerLinkHtml() Customer represented as HTML
getDescendants() Returns the element’s descendants.
getDirtyAttributes() Returns a list of attribute names that have changed since the element was first loaded.
getDirtyFields() Returns a list of custom field handles that have changed since the element was first loaded.
getEagerLoadedElementCount() Returns the count of eager-loaded elements for a given handle.
getEagerLoadedElements() Returns the eager-loaded elements for a given handle.
getEditorHtml() Returns the HTML for the element’s editor HUD.
getEmail() Returns the email for this order. Will always be the registered users email if the order's customer is related to a user.
getEnabledForSite() Returns whether the element is enabled for the current site.
getError() Returns the first error of the specified attribute.
getErrorSummary() Returns the errors for all attributes as a one-dimensional array.
getErrors() Returns the errors for all attributes or a single attribute.
getEstimatedBillingAddress()
getEstimatedShippingAddress()
getFieldColumnPrefix() Returns the field column prefix this element’s content uses.
getFieldContext() Returns the field context this element’s content uses.
getFieldLayout() Returns the field layout used by this element.
getFieldParamNamespace() Returns the namespace used by custom field params on the request.
getFieldStatus() Returns the status of a given field.
getFieldValue() Returns the value for a given field.
getFieldValues() Returns the element’s normalized custom field values, indexed by their handles.
getFirstError() Returns the first error of the specified attribute.
getFirstErrors() Returns the first error of every attribute in the model.
getGateway()
getGqlTypeName() Returns the GraphQL type name for this element type.
getHasDescendants() Returns whether the element has descendants.
getHasFreshContent() Returns whether the element’s content is "fresh" (unsaved and without validation errors).
getHistories()
getHtmlAttributes() Returns any attributes that should be included in the element’s DOM representation in the control panel.
getId() Returns the element’s ID.
getIsActiveCart() Returns whether this order is the user's current active cart.
getIsDraft() Returns whether this is a draft.
getIsEditable() Returns whether the current user can edit the element.
getIsEmpty() Returns whether the order has any items in it.
getIsHomepage() Returns whether this element represents the site homepage.
getIsPaid()
getIsRevision() Returns whether this is a revision.
getIsUnpaid()
getIsUnsavedDraft() Returns whether the element is an unsaved draft.
getItemSubtotal() Returns the total of all line item's subtotals.
getItemTotal()
getIterator() Returns an iterator for traversing the attributes in the model.
getLastTransaction()
getLineItems()
getLink() Returns an anchor pre-filled with this element’s URL and title.
getNestedTransactions() Returns an array of transactions for the order that have child transactions set on them.
getNext() Returns the next element relative to this one, from a given set of criteria.
getNextSibling() Returns the element’s next sibling.
getOrderAdjustments()
getOrderStatus()
getOrderStatusHtml()
getOutstandingBalance() Returns the difference between the order amount and amount paid.
getPaidStatus() What is the status of the orders payment
getPaidStatusHtml() Paid status represented as HTML
getParent() Returns the element’s parent.
getPaymentCurrency() Returns the current payment currency, and defaults to the primary currency if not set.
getPaymentSource() Returns the order's selected payment source if any.
getPdfUrl() Returns the URL to the order’s PDF invoice.
getPrev() Returns the previous element relative to this one, from a given set of criteria.
getPrevSibling() Returns the element’s previous sibling.
getPreviewTargets() Returns the additional locations that should be available for previewing the element, besides its primary URL.
getRecalculationMode() Gets the recalculation mode of the order
getRef() Returns the reference string to this element.
getRoute() Returns the route that should be used when the element’s URI is requested.
getScenario() Returns the scenario that this model is used in.
getSearchKeywords() Returns the search keywords for a given search attribute.
getSerializedFieldValues() Returns an array of the element’s serialized custom field values, indexed by their handles.
getShippingAddress() * Get the shipping address on the order.
getShippingMethod()
getShippingMethodId()
getShortNumber()
getShouldRecalculateAdjustments()
getSiblings() Returns all of the element’s siblings.
getSite() Returns the site the element is associated with.
getSourceId() Returns the element’s ID, or if it’s a draft/revision, its source element’s ID.
getSourceUid() Returns the element’s UUID, or if it’s a draft/revision, its source element’s UUID.
getStatus() Returns the element’s status.
getSupportedSites() Returns the sites this element is associated with.
getTableAttributeHtml() Returns the HTML that should be shown for a given attribute in Table View.
getThumbUrl() Returns the URL to the element’s thumbnail, if there is one.
getTotal() Returns the raw total of the order, which is the total of all line items and adjustments. This number can be negative, so it is not the price of the order.
getTotalAuthorized()
getTotalDescendants() Returns the total number of descendants that the element has.
getTotalDiscount()
getTotalPaid() Returns the total purchase and captured transactions belonging to this order.
getTotalPrice() Get the total price of the order, whose minimum value is enforced by the configured {@link Settings::minimumTotalPriceStrategy strategy set for minimum total price}.
getTotalQty() Returns total number of items.
getTotalSaleAmount() Returns the total sale amount.
getTotalShippingCost()
getTotalTax()
getTotalTaxIncluded()
getTotalTaxablePrice() Returns the total price of the order, minus any tax adjustments.
getTotalWeight()
getTransactions()
getUiLabel() Returns what the element should be called within the control panel.
getUriFormat() Returns the URI format used to generate this element’s URI.
getUrl() Returns the element’s full URL.
getUser()
getValidators() Returns all the validators declared in rules().
gqlScopesByContext() Returns the GraphQL scopes required by element's context.
gqlTypeNameByContext() Returns the GraphQL type name by an element's context.
hasContent() Returns whether elements of this type will be storing any data in the content table (titles or custom fields).
hasEagerLoadedElements() Returns whether elements have been eager-loaded with a given handle.
hasErrors() Returns a value indicating whether there is any validation error.
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event.
hasLineItems()
hasMethod() Returns a value indicating whether a method is defined.
hasOutstandingBalance()
hasProperty() Returns a value indicating whether a property is defined for this component.
hasStatuses() Returns whether elements of this type have statuses.
hasTitles() Returns whether elements of this type have traditional titles.
hasUris() Returns whether elements of this type can have their own slugs and URIs.
indexHtml() Returns the element index HTML.
init() Initializes the object.
instance() Returns static class instance, which can be used to obtain meta information.
isAncestorOf() Returns whether this element is an ancestor of another one.
isAttributeActive() Returns a value indicating whether the attribute is active in the current scenario.
isAttributeRequired() Returns a value indicating whether the attribute is required.
isAttributeSafe() Returns a value indicating whether the attribute is safe for massive assignments.
isChildOf() Returns whether this element is a direct child of another one.
isDescendantOf() Returns whether this element is a descendant of another one.
isFieldDirty() Returns whether a custom field value has changed since the element was first loaded.
isFieldEmpty() Returns whether a field is empty.
isLocalized() Returns whether elements of this type store content on a per-site basis.
isNextSiblingOf() Returns whether this element is the direct next sibling of another one.
isParentOf() Returns whether this element is a direct parent of another one.
isPrevSiblingOf() Returns whether this element is the direct previous sibling of another one.
isSiblingOf() Returns whether this element is a sibling of another one.
load() Populates the model with input data.
loadMultiple() Populates a set of models with the data from end user.
lowerDisplayName() Returns the lowercase version of displayName().
markAsClean() Resets the record of dirty attributes and fields.
markAsComplete() Marks the order as complete and sets the default order status, then saves the order.
markAsDirty() Marks all fields and attributes as dirty.
off() Detaches an existing event handler from this component.
offsetExists() Returns whether there is an element at the specified offset.
offsetGet() Returns the element at the specified offset.
offsetSet() Sets the element at the specified offset.
offsetUnset() Sets the element value at the specified offset to null.
on() Attaches an event handler to an event.
onUnsafeAttribute() This method is invoked when an unsafe attribute is being massively assigned.
pluralDisplayName() Returns the plural version of displayName().
pluralLowerDisplayName() Returns the plural, lowercase version of displayName().
recalculate() Regenerates all adjusters and updates line items, depending on the current recalculationMode
refHandle() Returns the handle that should be used to refer to this element type from reference tags.
removeBillingAddress()
removeEstimatedBillingAddress()
removeEstimatedShippingAddress()
removeLineItem() Removes a specific line item from the order.
removeShippingAddress()
rules() Returns the validation rules for attributes.
safeAttributes() Returns the attribute names that are safe to be massively assigned in the current scenario.
scenarios() Returns a list of scenarios and the corresponding active attributes.
searchableAttributes() Defines which element attributes should be searchable.
setAdjustments()
setAttributes() Sets the attribute values in a massive way.
setBillingAddress() Set the billing address on the order.
setCustomer()
setDirtyAttributes() Sets the list of dirty attribute names.
setEagerLoadedElementCount() Sets the count of eager-loaded elements for a given handle.
setEagerLoadedElements() Sets some eager-loaded elements on a given handle.
setEmail() Sets the orders email address. Will have no affect if the order's customer is a registered user.
setEnabledForSite() Sets whether the element is enabled for the current site.
setEstimatedBillingAddress()
setEstimatedShippingAddress()
setFieldParamNamespace() Sets the namespace used by custom field params on the request.
setFieldValue() Sets the value for a given field.
setFieldValues() Sets the element’s custom field values.
setFieldValuesFromRequest() Sets the element’s custom field values, when the values have come from post data.
setGatewayId() Sets the order's selected gateway id.
setLineItems()
setNext() Sets the default next element.
setParent() Sets the element’s parent.
setPaymentCurrency()
setPaymentSource() Sets the order's selected payment source
setPrev() Sets the default previous element.
setRecalculationMode() Sets the recalculation mode of the order
setRevisionCreatorId() Sets the revision creator ID to be saved.
setRevisionNotes() Sets the revision notes to be saved.
setScenario() Sets the scenario for the model.
setShippingAddress() Set the shipping address on the order.
setShouldRecalculateAdjustments()
sortOptions() Returns the sort options for the element type.
sources() Returns the source definitions that elements of this type may belong to.
statuses() Returns all of the possible statuses that elements of this type may have.
tableAttributes() Defines all of the available columns that can be shown in table views.
toArray() Converts the model into an array.
trackChanges() Returns whether Craft should keep track of attribute and custom field changes made to this element type, including when the last time they were changed, and who was logged-in at the time.
trigger() Triggers an event.
updateOrderPaidInformation() Updates the paid status and paid date of the order, and marks as complete if the order is paid or authorized.
validate() Performs the data validation.
validateAddress() Validates addresses, and also adds prefixed validation errors to order
validateAddressCanBeUsed() Validates that an address belongs to the order‘s customer.
validateAddressReuse() Validates that shipping address isn't being set to be the same as billing address, when billing address is set to be shipping address
validateCouponCode()
validateCustomFieldAttribute() Calls a custom validation function on a custom field.
validateCustomFieldContentSize() Validates that the content size is going to fit within the field’s database column.
validateGatewayId()
validateLineItems() Validates line items, and also adds prefixed validation errors to order
validateMultiple() Validates multiple models.
validatePaymentCurrency()
validatePaymentSourceId()

# __toString()

Returns the string representation of the element.

View source

Returns

string

# _getAdjustmentsTotalByType()

View source

Arguments

Returns

float, integer

# addLineItem()

Adds a line item to the order. Updates the line item if the ID of that line item is already in the cart.

View source

Arguments

# afterOrderComplete()

Called after the order successfully completes

View source

# afterSave()

Performs actions after an element is saved.

View source

Arguments

  • $isNew (boolean) – Whether the element is brand new

# attributes()

Returns the list of attribute names.

By default, this method returns all public non-static properties of the class. You may override this method to change the default behavior.

View source

Returns

array – List of attribute names.

# beforeValidate()

This method is invoked before validation starts.

The default implementation raises a beforeValidate event. You may override this method to do preliminary checks before validation. Make sure the parent implementation is invoked so that the event can be raised.

View source

Returns

boolean – Whether the validation should be executed. Defaults to true. If false is returned, the validation will stop and the model is considered invalid.

# behaviors()

View source

Returns

array

# currencyAttributes()

The attributes on the order that should be made available as formatted currency.

View source

Returns

array

# datetimeAttributes()

Returns the names of any attributes that should hold DateTime values.

View source

Returns

string[]

# defineRules()

Returns the validation rules for attributes.

See rules() for details about what should be returned.

Models should override this method instead of rules() so EVENT_DEFINE_RULES handlers can modify the class-defined rules.

View source

Returns

array

# displayName()

View source

Returns

null, string

# extraFields()

Returns the list of fields that can be expanded further and returned by toArray().

This method is similar to fields() except that the list of fields returned by this method are not returned by default by toArray(). Only when field names to be expanded are explicitly specified when calling toArray(), will their values be exported.

The default implementation returns an empty array.

You may override this method to return a list of expandable fields based on some context information (e.g. the current application user).

View source

Returns

array – The list of expandable field names or field definitions. Please refer to fields() on the format of the return value.

# fields()

View source

Returns

array

# getAdjustmentSubtotal()

Returns the total of adjustments made to order.

View source

Returns

float, integer

# getAdjustments()

View source

Returns

craft\commerce\models\OrderAdjustment[]

# getAdjustmentsByType()

Since
3.0

View source

Arguments

Returns

array

# getAdjustmentsTotal()

View source

Returns

float

# getAdjustmentsTotalByType()

DEPRECATED

Deprecated in 2.2

View source

Arguments

Returns

float, integer

# getAvailableShippingMethodOptions()

Since
3.1

View source

Returns

craft\commerce\models\ShippingMethodOption[]

# getBillingAddress()

Get the billing address on the order.

View source

Returns

craft\commerce\models\Address, null

# getCpEditUrl()

Returns the element’s edit URL in the control panel.

View source

Returns

string, null

# getCustomer()

View source

Returns

craft\commerce\models\Customer, null

# getCustomerLinkHtml()

Since
3.0

Customer represented as HTML

View source

Returns

string

# getEmail()

Returns the email for this order. Will always be the registered users email if the order's customer is related to a user.

View source

Returns

string, null

Throws

# getEstimatedBillingAddress()

Since
2.2

View source

Returns

craft\commerce\models\Address, null

# getEstimatedShippingAddress()

Since
2.2

View source

Returns

craft\commerce\models\Address, null

# getGateway()

View source

Returns

craft\commerce\base\GatewayInterface, null

Throws

# getHistories()

View source

Returns

craft\commerce\models\OrderHistory[]

# getIsActiveCart()

Returns whether this order is the user's current active cart.

View source

Returns

boolean

Throws

# getIsEditable()

Returns whether the current user can edit the element.

View source

Returns

boolean

# getIsEmpty()

Returns whether the order has any items in it.

View source

Returns

boolean

# getIsPaid()

View source

Returns

boolean

# getIsUnpaid()

View source

Returns

boolean

# getItemSubtotal()

Returns the total of all line item's subtotals.

View source

Returns

float

# getItemTotal()

View source

Returns

float

# getLastTransaction()

View source

Returns

craft\commerce\models\Transaction, null

# getLineItems()

View source

Returns

craft\commerce\models\LineItem[]

Returns an anchor pre-filled with this element’s URL and title.

View source

Returns

\Twig\Markup, null

# getNestedTransactions()

Returns an array of transactions for the order that have child transactions set on them.

View source

Returns

craft\commerce\models\Transaction[]

# getOrderAdjustments()

View source

Returns

array

# getOrderStatus()

View source

Returns

craft\commerce\models\OrderStatus, null

# getOrderStatusHtml()

View source

Returns

string

# getOutstandingBalance()

Returns the difference between the order amount and amount paid.

View source

Returns

float

# getPaidStatus()

What is the status of the orders payment

View source

Returns

string

# getPaidStatusHtml()

Paid status represented as HTML

View source

Returns

string

# getPaymentCurrency()

Returns the current payment currency, and defaults to the primary currency if not set.

View source

Returns

string

Throws

# getPaymentSource()

Returns the order's selected payment source if any.

View source

Returns

craft\commerce\models\PaymentSource, null

Throws

# getPdfUrl()

Returns the URL to the order’s PDF invoice.

View source

Arguments

  • $option (string, null) – The option that should be available to the PDF template (e.g. “receipt”)

Returns

string, null – The URL to the order’s PDF invoice, or null if the PDF template doesn’t exist

Throws

# getRecalculationMode()

Gets the recalculation mode of the order

View source

Returns

string

# getShippingAddress()

  • Get the shipping address on the order.

View source

Returns

craft\commerce\models\Address, null

# getShippingMethod()

View source

Returns

craft\commerce\models\ShippingMethod, null

# getShippingMethodId()

View source

Returns

integer, null

# getShortNumber()

View source

Returns

string

# getTotal()

Returns the raw total of the order, which is the total of all line items and adjustments. This number can be negative, so it is not the price of the order.

See also craft\commerce\elements\Order::getTotalPrice() – The actual total price of the order View source

Returns

float

# getTotalAuthorized()

View source

Returns

float

# getTotalDiscount()

View source

Returns

float

# getTotalPaid()

Returns the total purchase and captured transactions belonging to this order.

View source

Returns

float

# getTotalPrice()

Get the total price of the order, whose minimum value is enforced by the configured {@link Settings::minimumTotalPriceStrategy strategy set for minimum total price}.

View source

Returns

float

# getTotalQty()

Returns total number of items.

View source

Returns

integer

# getTotalSaleAmount()

Returns the total sale amount.

View source

Returns

float

# getTotalShippingCost()

View source

Returns

float

# getTotalTax()

View source

Returns

float

# getTotalTaxIncluded()

View source

Returns

float

# getTotalTaxablePrice()

DEPRECATED

Deprecated in 2.2.9. Use craft\commerce\adjusters\Tax::_getOrderTotalTaxablePrice() instead.

Returns the total price of the order, minus any tax adjustments.

View source

Returns

float

# getTotalWeight()

View source

Returns

float

# getTransactions()

View source

Returns

craft\commerce\models\Transaction[]

# getUser()

View source

Returns

craft\elements\User, null

Throws

# hasLineItems()

View source

Returns

boolean

# hasOutstandingBalance()

View source

Returns

boolean

# init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

View source

# lowerDisplayName()

Returns the lowercase version of displayName().

View source

Returns

string

# markAsComplete()

Marks the order as complete and sets the default order status, then saves the order.

View source

Returns

boolean

Throws

# pluralDisplayName()

Returns the plural version of displayName().

View source

Returns

string

# pluralLowerDisplayName()

Returns the plural, lowercase version of displayName().

View source

Returns

string

# recalculate()

Regenerates all adjusters and updates line items, depending on the current recalculationMode

View source

Throws

# removeBillingAddress()

Since
3.1

View source

# removeEstimatedBillingAddress()

Since
3.1

View source

# removeEstimatedShippingAddress()

Since
3.1

View source

# removeLineItem()

Removes a specific line item from the order.

View source

Arguments

# removeShippingAddress()

Since
3.1

View source

# setAdjustments()

View source

Arguments

# setBillingAddress()

Set the billing address on the order.

View source

Arguments

# setCustomer()

Since
3.x

View source

Arguments

# setEmail()

Sets the orders email address. Will have no affect if the order's customer is a registered user.

View source

Arguments

# setEstimatedBillingAddress()

Since
2.2

View source

Arguments

# setEstimatedShippingAddress()

Since
2.2

View source

Arguments

# setGatewayId()

Sets the order's selected gateway id.

View source

Arguments

# setLineItems()

View source

Arguments

# setPaymentCurrency()

View source

Arguments

  • $value (string) – The payment currency code

# setPaymentSource()

Sets the order's selected payment source

View source

Arguments

# setRecalculationMode()

Sets the recalculation mode of the order

View source

Arguments

  • $value

# setShippingAddress()

Set the shipping address on the order.

View source

Arguments

# updateOrderPaidInformation()

Updates the paid status and paid date of the order, and marks as complete if the order is paid or authorized.

View source

# Protected Methods

Method Description
defineActions() Defines the available element actions for a given source.
defineDefaultTableAttributes() Returns the list of table attribute keys that should be shown by default.
defineExporters() Defines the available element exporters for a given source.
defineSearchableAttributes() Defines which element attributes should be searchable.
defineSortOptions() Returns the sort options for the element type.
defineSources() Defines the sources that elements of this type may belong to.
defineTableAttributes() Defines all of the available columns that can be shown in table views.
extractFieldsFor() Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id".
extractRootFields() Extracts the root field names from nested fields.
fieldByHandle() Returns the field with a given handle.
fieldLayoutFields() Returns each of this element’s fields.
findByCondition() Finds Element instance(s) by the given condition.
htmlAttributes() Returns any attributes that should be included in the element’s DOM representation in the control panel.
normalizeFieldValue() Normalizes a field’s value.
prepElementQueryForTableAttribute() Preps the element criteria for a given table attribute
previewTargets() Returns the additional locations that should be available for previewing the element, besides its primary URL.
resolveFields() Determines which fields can be returned by toArray().
route() Returns the route that should be used when the element’s URI is requested.
tableAttributeHtml() Returns the HTML that should be shown for a given attribute in Table View.

# Constants

Constant Description
ATTR_STATUS_CONFLICTED
ATTR_STATUS_MODIFIED
ATTR_STATUS_OUTDATED
HOMEPAGE_URI
ORIGIN_CP Order created from the control panel.
ORIGIN_REMOTE Order created by a remote source.
ORIGIN_WEB Order created from the front end.
PAID_STATUS_OVERPAID Payments exceed order total.
PAID_STATUS_PAID Payments equal order total.
PAID_STATUS_PARTIAL Payments less than order total.
PAID_STATUS_UNPAID Payments total zero on non-free order.
RECALCULATION_MODE_ADJUSTMENTS_ONLY Recalculates adjustments only; does not recalculate line items or populate from purchasables.
RECALCULATION_MODE_ALL Recalculates line items, populates from purchasables, and regenerates adjustments.
RECALCULATION_MODE_NONE Does not recalculate anything on the order.
SCENARIO_DEFAULT The name of the default scenario.
SCENARIO_ESSENTIALS
SCENARIO_LIVE
STATUS_ARCHIVED
STATUS_DISABLED
STATUS_ENABLED

# Events

# EVENT_AFTER_ADD_LINE_ITEM

Type
yii\base\Event

The event that is triggered after a line item has been added to an order.

use craft\commerce\elements\Order;
use craft\commerce\events\LineItemEvent;
use craft\commerce\models\LineItem;
use yii\base\Event;

Event::on(
    Order::class,
    Order::EVENT_AFTER_ADD_LINE_ITEM,
    function(LineItemEvent $event) {
        // @var LineItem $lineItem
        $lineItem = $event->lineItem;
        // @var bool $isNew
        $isNew = $event->isNew;
        // ...
    }
);

# EVENT_AFTER_COMPLETE_ORDER

Type
yii\base\Event

The event that is triggered after an order is completed.

use craft\commerce\elements\Order;
use yii\base\Event;

Event::on(
    Order::class,
    Order::EVENT_AFTER_COMPLETE_ORDER,
    function(Event $event) {
        // @var Order $order
        $order = $event->sender;
        // ...
    }
);

# EVENT_AFTER_ORDER_AUTHORIZED

Type
yii\base\Event

This event is raised after an order is authorized in full and completed

Plugins can get notified after an order is authorized in full and completed

use craft\commerce\elements\Order;
use yii\base\Event;

Event::on(Order::class, Order::EVENT_AFTER_ORDER_AUTHORIZED, function(Event $e) {
    // @var Order $order
    $order = $e->sender;
    // ...
});

# EVENT_AFTER_ORDER_PAID

Type
yii\base\Event

The event that is triggered after an order is paid and completed.

use craft\commerce\elements\Order;
use yii\base\Event;

Event::on(
    Order::class,
    Order::EVENT_AFTER_ORDER_PAID,
    function(Event $event) {
        // @var Order $order
        $order = $event->sender;
        // ...
    }
);

# EVENT_AFTER_REMOVE_LINE_ITEM

Type
yii\base\Event

The event that is triggered after a line item has been removed from an order.

# EVENT_BEFORE_ADD_LINE_ITEM

Type
yii\base\Event

The event that is triggered before a new line item has been added to the order.

use craft\commerce\elements\Order;
use craft\commerce\models\LineItem;
use craft\commerce\events\LineItemEvent;
use yii\base\Event;

Event::on(
    Order::class,
    Order::EVENT_BEFORE_ADD_LINE_ITEM,
    function(LineItemEvent $event) {
        // @var LineItem $lineItem
        $lineItem = $event->lineItem;
        // @var bool $isNew
        $isNew = $event->isNew;
        // @var bool $isValid
        $isValid = $event->isValid;
        // ...
    }
);

# EVENT_BEFORE_COMPLETE_ORDER

Type
yii\base\Event

The event that is triggered before an order is completed.

use craft\commerce\elements\Order;
use yii\base\Event;

Event::on(
    Order::class,
    Order::EVENT_BEFORE_COMPLETE_ORDER,
    function(Event $event) {
        // @var Order $order
        $order = $event->sender;
        // ...
    }
);