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\base\OrderDeprecatedTrait, craft\commerce\base\OrderValidatorsTrait, yii\base\ArrayableTrait, yii\base\StaticInstanceTrait
Since
2.0

Order or Cart model.

View source

Public Properties

PropertyDescription
$activeValidatorsyii\validators\Validator – The validators applicable to the current $scenario.
$adjustmentSubtotalfloat, integer
$adjustmentscraft\commerce\models\OrderAdjustment[]
$adjustmentsTotalfloat
$ancestorscraft\elements\db\ElementQueryInterface, craft\base\ElementInterface
$archivedboolean – Whether the element is archived
$attributesarray – Attribute values (name => value).
$availableShippingMethodsarray
$awaitingFieldValuesboolean – Whether the element is still awaiting its custom field values
$behaviorsyii\base\Behavior – List of behaviors attached to this component
$billingAddresscraft\commerce\models\Address, null
$billingAddressIdinteger – Billing address ID
$billingSameAsShippingboolean – Whether billing address should be set to the same address as shipping
$cancelUrlstring – Cancel URL
$childrencraft\elements\db\ElementQueryInterface, craft\base\ElementInterface
$contentIdinteger, null – The element’s content row ID
$contentTablestring
$couponCodestring – Coupon Code
$cpEditUrlstring, null
$currencystring – Currency
$customercraft\commerce\models\Customer, null
$customerIdinteger – Customer ID
$dateCreatedDateTime, null – The date that the element was created
$dateOrderedDateTime – Date ordered
$datePaidDateTime – Date paid
$dateUpdatedDateTime, null – The date that the element was last updated
$descendantscraft\elements\db\ElementQueryInterface, craft\base\ElementInterface
$editorHtmlstring – The HTML for the editor HUD
$emailstring
$enabledboolean – Whether the element is enabled
$enabledForSiteboolean – Whether the element is enabled for this site.
$errorsarray – Errors for all attributes or the specified attribute.
$fieldColumnPrefixstring
$fieldContextstring
$fieldLayoutcraft\models\FieldLayout, null
$fieldLayoutIdinteger, null – The element’s field layout ID
$fieldParamNamespacestring, null – The field param namespace
$fieldValuesarray – The field values (handle => value)
$firstErrorsarray – The first errors.
$gatewaycraft\commerce\base\GatewayInterface, null
$gatewayIdinteger, null – Gateway ID
$hasDescendantsboolean
$hasFreshContentboolean – Whether the element’s content is fresh
$historiescraft\commerce\models\OrderHistory[]
$idinteger, null – The element’s ID
$isActiveCartboolean
$isCompletedboolean – Is completed
$isEditableboolean
$isEmptyboolean
$isPaidboolean
$isUnpaidboolean
$itemSubtotalfloat
$itemTotalfloat
$iteratorArrayIterator – An iterator for traversing the items in the list.
$lastIpstring – Last IP
$lastTransactioncraft\commerce\models\Transaction, null
$levelinteger, null – The element’s level within its structure
$lftinteger, null – The element’s left position within its structure
$lineItemscraft\commerce\models\LineItem[]
$linkTwig_Markup, null
$makePrimaryBillingAddressboolean – Whether billing address should be made primary
$makePrimaryShippingAddressboolean – Whether shipping address should be made primary
$messagestring – Message
$nestedTransactionscraft\commerce\models\Transaction[]
$nextcraft\base\ElementInterface, null
$nextSiblingcraft\base\ElementInterface, null
$numberstring – Number
$orderAdjustmentsarray
$orderLanguagestring – Order locale
$orderLocalestring
$orderStatuscraft\commerce\models\OrderStatus, null
$orderStatusIdinteger – Order status ID
$outstandingBalancefloat
$paidStatusstring
$paidStatusHtmlstring
$parentcraft\base\ElementInterface, null
$paymentCurrencystring
$paymentSourcecraft\commerce\models\PaymentSource, null
$paymentSourceIdinteger, null – Payment source ID
$pdfUrlstring, null – The URL to the order’s PDF invoice, or null if the PDF template doesn’t exist
$prevcraft\base\ElementInterface, null
$prevSiblingcraft\base\ElementInterface, null
$propagatingboolean – Whether the element is being saved in the context of propagating another site's version of the element.
$refstring, null
$returnUrlstring – Return URL
$rgtinteger, null – The element’s right position within its structure
$rootinteger, null – The element’s structure’s root ID
$routemixed – The route that the request should use, or null if no special action should be taken
$scenariostring – The scenario that this model is in.
$searchScoreinteger, null – The element’s search score, if the craft\elements\db\ElementQuery::search() parameter was used when querying for the element
$serializedFieldValuesarray
$shippingAddresscraft\commerce\models\Address, null
$shippingAddressIdinteger – Shipping address ID
$shippingMethodcraft\commerce\models\ShippingMethod, null
$shippingMethodHandlestring – Shipping Method Handle
$shippingMethodIdinteger, null
$shippingSameAsBillingboolean – Whether shipping address should be set to the same address as billing
$shortNumberstring
$shouldRecalculateAdjustmentsboolean
$siblingscraft\elements\db\ElementQueryInterface, craft\base\ElementInterface
$sitecraft\models\Site
$siteIdinteger, null – The site ID the element is associated with
$slugstring, null – The element’s slug
$statusstring, null
$structureIdinteger, null – The element’s structure ID
$supportedSitesinteger[], array
$tempIdstring, null – The element’s temporary ID (only used if the element's URI format contains {id})
$titlestring, null – The element’s title
$totalDescendantsinteger
$totalDiscountfloat
$totalPaidfloat
$totalPricefloat
$totalQtyinteger
$totalSaleAmountfloat
$totalShippingCostfloat
$totalTaxfloat
$totalTaxIncludedfloat
$totalTaxablePricefloat
$totalWeightfloat
$transactionscraft\commerce\models\Transaction[]
$uidstring, null – The element’s UID
$uristring, null – The element’s URI
$uriFormatstring, null
$urlstring, null
$usercraft\elements\User, null
$validatorsArrayObject, yii\validators\Validator – All the validators declared in the model.

$adjustmentSubtotal

Type
float, integer
Access
Read-only

View source

Signature

public float, integer getAdjustmentSubtotal ( )

$adjustments

Signature

public craft\commerce\models\OrderAdjustment[] getAdjustments ( )
public void setAdjustments ( array $adjustments )

$adjustmentsTotal

Type
float
Access
Read-only

View source

Signature

public float getAdjustmentsTotal ( )

$availableShippingMethods

Type
array
Access
Read-only

View source

Signature

public array getAvailableShippingMethods ( )

$billingAddress

Signature

public craft\commerce\models\Address, null getBillingAddress ( )
public void setBillingAddress ( $address )

$billingAddressId

Type
integer

Billing address ID

View source

Signature

public integer $billingAddressId = null

$billingSameAsShipping

Type
boolean

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

View source

Signature

public boolean $billingSameAsShipping = null

$cancelUrl

Type
string

Cancel URL

View source

Signature

public string $cancelUrl = null

$couponCode

Type
string

Coupon Code

View source

Signature

public string $couponCode = null

$cpEditUrl

Type
string, null
Access
Read-only

View source

Signature

public string, null getCpEditUrl ( )

$currency

Type
string

Currency

View source

Signature

public string $currency = null

$customer

Signature

public craft\commerce\models\Customer, null getCustomer ( )

$customerId

Type
integer

Customer ID

View source

Signature

public integer $customerId = null

$dateOrdered

Type
DateTime

Date ordered

View source

Signature

public DateTime $dateOrdered = null

$datePaid

Type
DateTime

Date paid

View source

Signature

public DateTime $datePaid = null

$email

Signature

public string getEmail ( )
public void setEmail ( $value )

$fieldLayout

Signature

public craft\models\FieldLayout, null getFieldLayout ( )

$gateway

Signature

public craft\commerce\base\GatewayInterface, null getGateway ( )

$gatewayId

Type
integer, null
Access
Write-only

Gateway ID

View source

Signature

public void setGatewayId ( \craft\commerce\elements\int $gatewayId )

$histories

Signature

public craft\commerce\models\OrderHistory[] getHistories ( )

$isActiveCart

Type
boolean
Access
Read-only

View source

Signature

public boolean getIsActiveCart ( )

$isCompleted

Type
boolean

Is completed

View source

Signature

public boolean $isCompleted = false

$isEditable

Type
boolean
Access
Read-only

View source

Signature

public boolean getIsEditable ( )

$isEmpty

Type
boolean
Access
Read-only

View source

Signature

public boolean getIsEmpty ( )

$isPaid

Type
boolean
Access
Read-only

View source

Signature

public boolean getIsPaid ( )

$isUnpaid

Type
boolean
Access
Read-only

View source

Signature

public boolean getIsUnpaid ( )

$itemSubtotal

Type
float
Access
Read-only

View source

Signature

public float getItemSubtotal ( )

$itemTotal

Type
float
Access
Read-only

View source

Signature

public float getItemTotal ( )

$lastIp

Signature

public string $lastIp = null

$lastTransaction

Signature

public craft\commerce\models\Transaction, null getLastTransaction ( )

$lineItems

Signature

public craft\commerce\models\LineItem[] getLineItems ( )
public void setLineItems ( array $lineItems )
Type
Twig_Markup, null
Access
Read-only

View source

Signature

public Twig_Markup, null getLink ( )

$makePrimaryBillingAddress

Type
boolean

Whether billing address should be made primary

View source

Signature

public boolean $makePrimaryBillingAddress = null

$makePrimaryShippingAddress

Type
boolean

Whether shipping address should be made primary

View source

Signature

public boolean $makePrimaryShippingAddress = null

$message

Signature

public string $message = null

$nestedTransactions

Signature

public craft\commerce\models\Transaction[] getNestedTransactions ( )

$number

Signature

public string $number = null

$orderAdjustments

Type
array
Access
Read-only

View source

Signature

public array getOrderAdjustments ( )

$orderLanguage

Type
string

Order locale

View source

Signature

public string $orderLanguage = null

$orderStatus

Signature

public craft\commerce\models\OrderStatus, null getOrderStatus ( )

$orderStatusId

Type
integer

Order status ID

View source

Signature

public integer $orderStatusId = null

$outstandingBalance

Type
float
Access
Read-only

View source

Signature

public float getOutstandingBalance ( )

$paidStatus

Type
string
Access
Read-only

View source

Signature

public string getPaidStatus ( )

$paidStatusHtml

Type
string
Access
Read-only

View source

Signature

public string getPaidStatusHtml ( )

$paymentCurrency

Signature

public string getPaymentCurrency ( )
public void setPaymentCurrency ( $value )

$paymentSource

Signature

public craft\commerce\models\PaymentSource, null getPaymentSource ( )
public void setPaymentSource ( craft\commerce\models\PaymentSource $paymentSource )

$paymentSourceId

Type
integer, null

Payment source ID

View source

Signature

public integer, null $paymentSourceId = null

$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

Signature

public string, null getPdfUrl ( $option = null )

$returnUrl

Type
string

Return URL

View source

Signature

public string $returnUrl = null

$shippingAddress

Signature

public craft\commerce\models\Address, null getShippingAddress ( )
public void setShippingAddress ( $address )

$shippingAddressId

Type
integer

Shipping address ID

View source

Signature

public integer $shippingAddressId = null

$shippingMethod

Signature

public craft\commerce\models\ShippingMethod, null getShippingMethod ( )

$shippingMethodHandle

Type
string

Shipping Method Handle

View source

Signature

public string $shippingMethodHandle = null

$shippingMethodId

Type
integer, null
Access
Read-only

View source

Signature

public integer, null getShippingMethodId ( )

$shippingSameAsBilling

Type
boolean

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

View source

Signature

public boolean $shippingSameAsBilling = null

$shortNumber

Type
string
Access
Read-only

View source

Signature

public string getShortNumber ( )

$shouldRecalculateAdjustments

Signature

public boolean getShouldRecalculateAdjustments ( )
public void setShouldRecalculateAdjustments ( \craft\commerce\elements\bool $value )

$totalPaid

Type
float
Access
Read-only

View source

Signature

public float getTotalPaid ( )

$totalPrice

Type
float
Access
Read-only

View source

Signature

public float getTotalPrice ( )

$totalQty

Type
integer
Access
Read-only

View source

Signature

public integer getTotalQty ( )

$totalSaleAmount

Type
float
Access
Read-only

View source

Signature

public float getTotalSaleAmount ( )

$totalTaxablePrice

Type
float
Access
Read-only

View source

Signature

public float getTotalTaxablePrice ( )

$totalWeight

Type
float
Access
Read-only

View source

Signature

public float getTotalWeight ( )

$transactions

Signature

public craft\commerce\models\Transaction[] getTransactions ( )

$user

Signature

public craft\elements\User, null getUser ( )

Public Methods

MethodDescription
__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 an object property to null.
actions()Returns the available element actions for a given source (if one is provided).
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
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.
beforeSave()Performs actions before an element is saved.
beforeValidate()This method is invoked before validation starts.
behaviors()Returns a list of behaviors that this component should behave as.
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().
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.
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.
extraFields()Returns the list of fields that can be expanded further and returned by toArray().
fields()Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.
find()Creates an craft\elements\db\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()
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.
getAttributes()Returns attribute values.
getAvailableShippingMethods()
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getBillingAddress()
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 CP edit URL.
getCustomer()
getDescendants()Returns the element’s descendants.
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.
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.
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.
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()
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.
getIsEditable()Returns whether the current user can edit the element.
getIsEmpty()Returns whether the order has any items in it.
getIsPaid()
getIsUnpaid()
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()
getOrderLocale()
getOrderStatus()
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.
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()
getShippingMethod()
getShippingMethodId()
getShortNumber()
getShouldRecalculateAdjustments()
getSiblings()Returns all of the element’s siblings.
getSite()Returns the site the element is associated with.
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.
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()
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 adjustmemnts.
getTotalWeight()
getTransactions()
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().
hasContent()Returns whether elements of this type will be storing any data in the content table (tiles 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.
hasMethod()Returns a value indicating whether a method is defined.
hasOutstandingBalance()
hasProperty()Returns a value indicating whether a property is defined.
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.
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.
markAsComplete()Marks the order as complete and sets the default order status, then saves the order.
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.
recalculate()Regenerates all adjusters and update line item and order totals.
refHandle()Returns the handle that should be used to refer to this element type from reference tags.
removeLineItem()Removes a specific line item from the order.
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()
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.
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.
setScenario()Sets the scenario for the model.
setShippingAddress()
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.
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.
updateOrderPaidTotal()
validate()Performs the data validation.
validateAddress()Validates addresses, and also adds prefixed validation errors to order
validateAddressBelongsToOrdersCustomer()Validates address belongs to the orders custome.
validateAddressReuse()Validates that shipping address isn't being set to be the same as billing adress, 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.
validatePaymentSourceId()

__toString()

Returns the string representation of the element.

View source

Returns

string

Signature

public string __toString ( )

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

Signature

public void addLineItem ( $lineItem )

afterOrderComplete()

Called after the order successfully completes

View source

Signature

public void afterOrderComplete ( )

afterSave()

Performs actions after an element is saved.

View source

Arguments

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

Signature

public void afterSave ( \craft\commerce\elements\bool $isNew )

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.

Signature

public array attributes ( )

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.

Signature

public boolean beforeValidate ( )

datetimeAttributes()

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

View source

Returns

string[]

Signature

public string[] datetimeAttributes ( )

displayName()

Signature

public static null, string displayName ( )

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.

Signature

public array extraFields ( )

find()

Creates an craft\elements\db\ElementQueryInterface instance for query purpose.

The returned craft\elements\db\ElementQueryInterface instance can be further customized by calling methods defined in craft\elements\db\ElementQueryInterface before one() or all() is called to return populated \craft\commerce\elements\ElementInterface instances. For example,

// Find the entry whose ID is 5
$entry = Entry::find()->id(5)->one();
// Find all assets and order them by their filename:
$assets = Asset::find()
    ->orderBy('filename')
    ->all();

If you want to define custom criteria parameters for your elements, you can do so by overriding this method and returning a custom query class. For example,

class Product extends Element
{
    public static function find()
    {
        // use ProductQuery instead of the default ElementQuery
        return new ProductQuery(get_called_class());
    }
}

You can also set default criteria parameters on the ElementQuery if you don’t have a need for a custom query class. For example,

class Customer extends ActiveRecord
{
    public static function find()
    {
        return parent::find()->limit(50);
    }
}

View source

Returns

craft\commerce\elements\db\OrderQuery – The newly created craft\commerce\elements\db\OrderQuery instance.

Signature

public static craft\commerce\elements\db\OrderQuery find ( )

getAdjustmentSubtotal()

Returns the total of adjustments made to order.

View source

Returns

float, integer

Signature

public float, integer getAdjustmentSubtotal ( )

getAdjustments()

Signature

public craft\commerce\models\OrderAdjustment[] getAdjustments ( )

getAdjustmentsTotal()

Signature

public float getAdjustmentsTotal ( )

getAdjustmentsTotalByType()

View source

Arguments

Returns

float, integer

Signature

public float, integer getAdjustmentsTotalByType ( $types, $included = false )

getAvailableShippingMethods()

Signature

public array getAvailableShippingMethods ( )

getBillingAddress()

Signature

public craft\commerce\models\Address, null getBillingAddress ( )

getCpEditUrl()

Returns the element’s CP edit URL.

View source

Returns

string, null

Signature

public string, null getCpEditUrl ( )

getCustomer()

Signature

public craft\commerce\models\Customer, null getCustomer ( )

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

Signature

public string getEmail ( )

getFieldLayout()

Returns the field layout used by this element.

View source

Returns

craft\models\FieldLayout, null

Signature

public craft\models\FieldLayout, null getFieldLayout ( )

getGateway()

Signature

public craft\commerce\base\GatewayInterface, null getGateway ( )

getHistories()

Signature

public craft\commerce\models\OrderHistory[] getHistories ( )

getIsActiveCart()

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

View source

Returns

boolean

Signature

public boolean getIsActiveCart ( )

getIsEditable()

Returns whether the current user can edit the element.

View source

Returns

boolean

Signature

public boolean getIsEditable ( )

getIsEmpty()

Returns whether the order has any items in it.

View source

Returns

boolean

Signature

public boolean getIsEmpty ( )

getIsPaid()

Signature

public boolean getIsPaid ( )

getIsUnpaid()

Signature

public boolean getIsUnpaid ( )

getItemSubtotal()

Returns the total of all line item's subtotals.

View source

Returns

float

Signature

public float getItemSubtotal ( )

getItemTotal()

Signature

public float getItemTotal ( )

getLastTransaction()

Signature

public craft\commerce\models\Transaction, null getLastTransaction ( )

getLineItems()

Signature

public craft\commerce\models\LineItem[] getLineItems ( )

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

View source

Returns

Twig_Markup, null

Signature

public Twig_Markup, null getLink ( )

getNestedTransactions()

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

View source

Returns

craft\commerce\models\Transaction[]

Signature

public craft\commerce\models\Transaction[] getNestedTransactions ( )

getOrderAdjustments()

Signature

public array getOrderAdjustments ( )

getOrderStatus()

Signature

public craft\commerce\models\OrderStatus, null getOrderStatus ( )

getOutstandingBalance()

Returns the difference between the order amount and amount paid.

View source

Returns

float

Signature

public float getOutstandingBalance ( )

getPaidStatus()

What is the status of the orders payment

View source

Returns

string

Signature

public string getPaidStatus ( )

getPaidStatusHtml()

Paid status represented as HTML

View source

Returns

string

Signature

public string getPaidStatusHtml ( )

getPaymentCurrency()

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

View source

Returns

string

Signature

public string getPaymentCurrency ( )

getPaymentSource()

Returns the order's selected payment source if any.

View source

Returns

craft\commerce\models\PaymentSource, null

Throws

Signature

public craft\commerce\models\PaymentSource, null getPaymentSource ( )

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

Signature

public string, null getPdfUrl ( $option = null )

getSearchKeywords()

Returns the search keywords for a given search attribute.

View source

Arguments

Returns

string

Signature

public string getSearchKeywords ( \craft\commerce\elements\string $attribute )

getShippingAddress()

Signature

public craft\commerce\models\Address, null getShippingAddress ( )

getShippingMethod()

Signature

public craft\commerce\models\ShippingMethod, null getShippingMethod ( )

getShippingMethodId()

Signature

public integer, null getShippingMethodId ( )

getShortNumber()

Signature

public string getShortNumber ( )

getShouldRecalculateAdjustments()

Signature

public boolean getShouldRecalculateAdjustments ( )

getTableAttributeHtml()

Returns the HTML that should be shown for a given attribute in Table View.

This method can be used to completely customize what actually shows up within the table’s body for a given attribute, rather than simply showing the attribute’s raw value. For example, if your elements have an “email” attribute that you want to wrap in a mailto: link, your getTableAttributesHtml() method could do this:

switch ($attribute) {
    case 'email':
        return $this->email ? '<a href="mailto:'.$this->email.'">'.$this->email.'</a>' : '';
    // ...
}
return parent::getTableAttributeHtml($attribute);

craft\base\Element::getTableAttributeHtml() provides a couple handy attribute checks by default, so it is a good idea to let the parent method get called (as shown above). They are:

  • If the attribute name is ‘link’ or ‘uri’, it will be linked to the front-end URL.
  • If the attribute is a custom field handle, it will pass the responsibility off to the field class.
  • If the attribute value is a DateTime object, the date will be formatted with a localized date format.
  • For anything else, it will output the attribute value as a string.

View source

Arguments

  • $attribute (string) – The attribute name.

Returns

string – The HTML that should be shown for a given attribute in Table View.

Signature

public string getTableAttributeHtml ( \craft\commerce\elements\string $attribute )

getTotalPaid()

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

View source

Returns

float

Signature

public float getTotalPaid ( )

getTotalPrice()

Signature

public float getTotalPrice ( )

getTotalQty()

Returns total number of items.

View source

Returns

integer

Signature

public integer getTotalQty ( )

getTotalSaleAmount()

Returns the total sale amount.

View source

Returns

float

Signature

public float getTotalSaleAmount ( )

getTotalTaxablePrice()

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

View source

Returns

float

Signature

public float getTotalTaxablePrice ( )

getTotalWeight()

Signature

public float getTotalWeight ( )

getTransactions()

Signature

public craft\commerce\models\Transaction[] getTransactions ( )

getUser()

Signature

public craft\elements\User, null getUser ( )

hasContent()

Returns whether elements of this type will be storing any data in the content table (tiles or custom fields).

View source

Returns

boolean – Whether elements of this type will be storing any data in the content table.

Signature

public static boolean hasContent ( )

hasOutstandingBalance()

Signature

public boolean hasOutstandingBalance ( )

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

Signature

public void init ( )

markAsComplete()

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

View source

Returns

boolean

Throws

Signature

public boolean markAsComplete ( )

recalculate()

Regenerates all adjusters and update line item and order totals.

View source

Throws

Signature

public void recalculate ( )

removeLineItem()

Removes a specific line item from the order.

View source

Arguments

Signature

public void removeLineItem ( craft\commerce\models\LineItem $lineItem )

rules()

Returns the validation rules for attributes.

Validation rules are used by validate() to check if attribute values are valid. Child classes may override this method to declare different validation rules.

Each rule is an array with the following structure:

[
    ['attribute1', 'attribute2'],
    'validator type',
    'on' => ['scenario1', 'scenario2'],
    //...other parameters...
]

where

  • attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
  • validator type: required, specifies the validator to be used. It can be a built-in validator name, a method name of the model class, an anonymous function, or a validator class name.
  • on: optional, specifies the scenarios array in which the validation rule can be applied. If this option is not set, the rule will apply to all scenarios.
  • additional name-value pairs can be specified to initialize the corresponding validator properties. Please refer to individual validator class API for possible properties.

A validator can be either an object of a class extending \craft\commerce\elements\Validator, or a model class method (called inline validator) that has the following signature:

// $params refers to validation parameters given in the rule
function validatorName($attribute, $params)

In the above $attribute refers to the attribute currently being validated while $params contains an array of validator configuration options such as max in case of string validator. The value of the attribute currently being validated can be accessed as $this->$attribute. Note the $ before attribute; this is taking the value of the variable $attribute and using it as the name of the property to access.

Yii also provides a set of \craft\commerce\elements\Validator::builtInValidators. Each one has an alias name which can be used when specifying a validation rule.

Below are some examples:

[
    // built-in "required" validator
    [['username', 'password'], 'required'],
    // built-in "string" validator customized with "min" and "max" properties
    ['username', 'string', 'min' => 3, 'max' => 12],
    // built-in "compare" validator that is used in "register" scenario only
    ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
    // an inline validator defined via the "authenticate()" method in the model class
    ['password', 'authenticate', 'on' => 'login'],
    // a validator of class "DateRangeValidator"
    ['dateRange', 'DateRangeValidator'],
];

Note, in order to inherit rules defined in the parent class, a child class needs to merge the parent rules with child rules using functions such as array_merge().

View source

Returns

array – Validation rules

Signature

public array rules ( )

setAdjustments()

Signature

public void setAdjustments ( array $adjustments )

setBillingAddress()

Signature

public void setBillingAddress ( $address )

setEmail()

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

View source

Arguments

Signature

public void setEmail ( $value )

setGatewayId()

Sets the order's selected gateway id.

View source

Arguments

Signature

public void setGatewayId ( \craft\commerce\elements\int $gatewayId )

setLineItems()

Signature

public void setLineItems ( array $lineItems )

setPaymentCurrency()

View source

Arguments

  • $value (string) – The payment currency code

Signature

public void setPaymentCurrency ( $value )

setPaymentSource()

Sets the order's selected payment source

View source

Arguments

Signature

public void setPaymentSource ( craft\commerce\models\PaymentSource $paymentSource )

setShippingAddress()

Signature

public void setShippingAddress ( $address )

setShouldRecalculateAdjustments()

View source

Arguments

Signature

public void setShouldRecalculateAdjustments ( \craft\commerce\elements\bool $value )

updateOrderPaidInformation()

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

View source

Signature

public void updateOrderPaidInformation ( )

updateOrderPaidTotal()

Signature

public void updateOrderPaidTotal ( )

Protected Methods

MethodDescription
defineActions()Defines the available element actions for a given source (if one is provided).
defineDefaultTableAttributes()Returns the list of table attribute keys that should be shown by default.
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
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.

defineActions()

Defines the available element actions for a given source (if one is provided).

View source

Arguments

  • $source (string, null) – The selected source’s key, if any.

Returns

array – The available element actions.

Signature

protected static array defineActions ( \craft\commerce\elements\string $source = null )

defineDefaultTableAttributes()

Returns the list of table attribute keys that should be shown by default.

View source

Arguments

  • $source (string) – The selected source’s key

Returns

string[] – The table attributes.

Signature

protected static string[] defineDefaultTableAttributes ( \craft\commerce\elements\string $source = null )

defineSearchableAttributes()

Defines which element attributes should be searchable.

View source

Returns

string[] – The element attributes that should be searchable

Signature

protected static string[] defineSearchableAttributes ( )

defineSortOptions()

Returns the sort options for the element type.

View source

Returns

array – The attributes that elements can be sorted by

Signature

protected static array defineSortOptions ( )

defineSources()

Defines the sources that elements of this type may belong to.

View source

Arguments

  • $context (string, null) – The context ('index' or 'modal').

Returns

array – The sources.

Signature

protected static array defineSources ( \craft\commerce\elements\string $context = null )

defineTableAttributes()

Defines all of the available columns that can be shown in table views.

View source

Returns

array – The table attributes.

Signature

protected static array defineTableAttributes ( )

Constants

ConstantDescription
PAID_STATUS_PAID
PAID_STATUS_PARTIAL
PAID_STATUS_UNPAID
SCENARIO_DEFAULTThe 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

This event is raised when a line item is added to the order

Plugins can get notified after a line item has been added to the order

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

Event::on(Order::class, Order::EVENT_AFTER_ADD_LINEITEM_TO_ORDER, function(Event $e) {
    $lineItem = $e->lineItem;
    $isNew = $e->isNew;
    // ...
});

EVENT_AFTER_COMPLETE_ORDER

Type
yii\base\Event

This event is raised after an order is completed

Plugins can get notified 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 $e) {
    // @var Order $order
    $order = $e->sender;
    // ...
});

EVENT_AFTER_ORDER_PAID

Type
yii\base\Event

This event is raised after an order is paid and completed

Plugins can get notified 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 $e) {
    // @var Order $order
    $order = $e->sender;
    // ...
});

EVENT_BEFORE_COMPLETE_ORDER

Type
yii\base\Event

This event is raised when an order is completed

Plugins can get notified 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 $e) {
    // @var Order $order
    $order = $e->sender;
    // ...
});