diff --git a/docs/.artifacts/cms/3.x/assets.md b/docs/.artifacts/cms/3.x/assets.md new file mode 100644 index 000000000..81ebfff62 --- /dev/null +++ b/docs/.artifacts/cms/3.x/assets.md @@ -0,0 +1,1237 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only assets that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. +| [asArray](#asarray) | Causes the query to return matching assets as arrays of data, rather than [Asset](craft3:craft\elements\Asset) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#datecreated) | Narrows the query results based on the assets’ creation dates. +| [dateModified](#datemodified) | Narrows the query results based on the assets’ files’ last-modified dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the assets’ last-updated dates. +| [filename](#filename) | Narrows the query results based on the assets’ filenames. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [folderId](#folderid) | Narrows the query results based on the folders the assets belong to, per the folders’ IDs. +| [folderPath](#folderpath) | Narrows the query results based on the folders the assets belong to, per the folders’ paths. +| [height](#height) | Narrows the query results based on the assets’ image heights. +| [id](#id) | Narrows the query results based on the assets’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [includeSubfolders](#includesubfolders) | Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). +| [kind](#kind) | Narrows the query results based on the assets’ file kinds. +| [limit](#limit) | Determines the number of assets that should be returned. +| [offset](#offset) | Determines how many assets should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [relatedTo](#relatedto) | Narrows the query results to only assets that are related to certain other elements. +| [search](#search) | Narrows the query results to only assets that match a search query. +| [site](#site) | Determines which site(s) the assets should be queried in. +| [siteId](#siteid) | Determines which site(s) the assets should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the assets’ IDs in the `elements_sites` table. +| [size](#size) | Narrows the query results based on the assets’ file sizes (in bytes). +| [title](#title) | Narrows the query results based on the assets’ titles. +| [trashed](#trashed) | Narrows the query results to only assets that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the assets’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uploader](#uploader) | Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. +| [volume](#volume) | Narrows the query results based on the volume the assets belong to. +| [volumeId](#volumeid) | Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. +| [width](#width) | Narrows the query results based on the assets’ image widths. +| [with](#with) | Causes the query to return matching assets eager-loaded with related elements. +| [withTransforms](#withtransforms) | Causes the query to return matching assets eager-loaded with image transform indexes. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only assets that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all assets that are related to myCategoryA and myCategoryB #} +{% set assets = craft.assets() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all assets that are related to $myCategoryA and $myCategoryB +$assets = \craft\elements\Asset::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all assets, regardless of status #} +{% set assets = craft.assets() + .anyStatus() + .all() %} +``` + +```php +// Fetch all assets, regardless of status +$assets = \craft\elements\Asset::find() + ->anyStatus() + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching assets as arrays of data, rather than [Asset](craft3:craft\elements\Asset) objects. + + + + + +::: code +```twig +{# Fetch assets as arrays #} +{% set assets = craft.assets() + .asArray() + .all() %} +``` + +```php +// Fetch assets as arrays +$assets = \craft\elements\Asset::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `dateCreated` + +Narrows the query results based on the assets’ creation dates. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch assets created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set assets = craft.assets() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch assets created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$assets = \craft\elements\Asset::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateModified` + +Narrows the query results based on the assets’ files’ last-modified dates. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'>= 2018-04-01'` | that were modified on or after 2018-04-01. +| `'< 2018-05-01'` | that were modified before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were modified between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch assets modified in the last month #} +{% set start = date('30 days ago')|atom %} + +{% set assets = craft.assets() + .dateModified(">= #{start}") + .all() %} +``` + +```php +// Fetch assets modified in the last month +$start = (new \DateTime('30 days ago'))->format(\DateTime::ATOM); + +$assets = \craft\elements\Asset::find() + ->dateModified(">= {$start}") + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the assets’ last-updated dates. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch assets updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set assets = craft.assets() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch assets updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$assets = \craft\elements\Asset::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `filename` + +Narrows the query results based on the assets’ filenames. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'foo.jpg'` | with a filename of `foo.jpg`. +| `'foo*'` | with a filename that begins with `foo`. +| `'*.jpg'` | with a filename that ends with `.jpg`. +| `'*foo*'` | with a filename that contains `foo`. +| `'not *foo*'` | with a filename that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a filename that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a filename that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Fetch all the hi-res images #} +{% set assets = craft.assets() + .filename('*@2x*') + .all() %} +``` + +```php +// Fetch all the hi-res images +$assets = \craft\elements\Asset::find() + ->filename('*@2x*') + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch assets in a specific order #} +{% set assets = craft.assets() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch assets in a specific order +$assets = \craft\elements\Asset::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `folderId` + +Narrows the query results based on the folders the assets belong to, per the folders’ IDs. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | in a folder with an ID of 1. +| `'not 1'` | not in a folder with an ID of 1. +| `[1, 2]` | in a folder with an ID of 1 or 2. +| `['not', 1, 2]` | not in a folder with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch assets in the folder with an ID of 1 #} +{% set assets = craft.assets() + .folderId(1) + .all() %} +``` + +```php +// Fetch assets in the folder with an ID of 1 +$assets = \craft\elements\Asset::find() + ->folderId(1) + ->all(); +``` +::: + + + +::: tip +This can be combined with [includeSubfolders](#includesubfolders) if you want to include assets in all the subfolders of a certain folder. +::: +#### `folderPath` + +Narrows the query results based on the folders the assets belong to, per the folders’ paths. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `foo/` | in a `foo/` folder (excluding nested folders). +| `foo/*` | in a `foo/` folder (including nested folders). +| `'not foo/*'` | not in a `foo/` folder (including nested folders). +| `['foo/*', 'bar/*']` | in a `foo/` or `bar/` folder (including nested folders). +| `['not', 'foo/*', 'bar/*']` | not in a `foo/` or `bar/` folder (including nested folders). + + + +::: code +```twig +{# Fetch assets in the foo/ folder or its nested folders #} +{% set assets = craft.assets() + .folderPath('foo/*') + .all() %} +``` + +```php +// Fetch assets in the foo/ folder or its nested folders +$assets = \craft\elements\Asset::find() + ->folderPath('foo/*') + ->all(); +``` +::: + + +#### `height` + +Narrows the query results based on the assets’ image heights. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `100` | with a height of 100. +| `'>= 100'` | with a height of at least 100. +| `['>= 100', '<= 1000']` | with a height between 100 and 1,000. + + + +::: code +```twig +{# Fetch XL images #} +{% set assets = craft.assets() + .kind('image') + .height('>= 1000') + .all() %} +``` + +```php +// Fetch XL images +$assets = \craft\elements\Asset::find() + ->kind('image') + ->height('>= 1000') + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the assets’ IDs. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the asset by its ID #} +{% set asset = craft.assets() + .id(1) + .one() %} +``` + +```php +// Fetch the asset by its ID +$asset = \craft\elements\Asset::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch assets in reverse #} +{% set assets = craft.assets() + .inReverse() + .all() %} +``` + +```php +// Fetch assets in reverse +$assets = \craft\elements\Asset::find() + ->inReverse() + ->all(); +``` +::: + + +#### `includeSubfolders` + +Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). + + + +::: code +```twig +{# Fetch assets in the folder with an ID of 1 (including its subfolders) #} +{% set assets = craft.assets() + .folderId(1) + .includeSubfolders() + .all() %} +``` + +```php +// Fetch assets in the folder with an ID of 1 (including its subfolders) +$assets = \craft\elements\Asset::find() + ->folderId(1) + ->includeSubfolders() + ->all(); +``` +::: + + + +::: warning +This will only work if [folderId](#folderid) was set to a single folder ID. +::: +#### `kind` + +Narrows the query results based on the assets’ file kinds. + +Supported file kinds: +- `access` +- `audio` +- `compressed` +- `excel` +- `flash` +- `html` +- `illustrator` +- `image` +- `javascript` +- `json` +- `pdf` +- `photoshop` +- `php` +- `powerpoint` +- `text` +- `video` +- `word` +- `xml` +- `unknown` + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'image'` | with a file kind of `image`. +| `'not image'` | not with a file kind of `image`.. +| `['image', 'pdf']` | with a file kind of `image` or `pdf`. +| `['not', 'image', 'pdf']` | not with a file kind of `image` or `pdf`. + + + +::: code +```twig +{# Fetch all the images #} +{% set assets = craft.assets() + .kind('image') + .all() %} +``` + +```php +// Fetch all the images +$assets = \craft\elements\Asset::find() + ->kind('image') + ->all(); +``` +::: + + +#### `limit` + +Determines the number of assets that should be returned. + + + +::: code +```twig +{# Fetch up to 10 assets #} +{% set assets = craft.assets() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 assets +$assets = \craft\elements\Asset::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many assets should be skipped in the results. + + + +::: code +```twig +{# Fetch all assets except for the first 3 #} +{% set assets = craft.assets() + .offset(3) + .all() %} +``` + +```php +// Fetch all assets except for the first 3 +$assets = \craft\elements\Asset::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) + + + +::: code +```twig +{# Fetch all assets in order of date created #} +{% set assets = craft.assets() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all assets in order of date created +$assets = \craft\elements\Asset::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique assets from Site A, or Site B if they don’t exist in Site A #} +{% set assets = craft.assets() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique assets from Site A, or Site B if they don’t exist in Site A +$assets = \craft\elements\Asset::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only assets that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all assets that are related to myCategory #} +{% set assets = craft.assets() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all assets that are related to $myCategory +$assets = \craft\elements\Asset::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only assets that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all assets that match the search query #} +{% set assets = craft.assets() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all assets that match the search query +$assets = \craft\elements\Asset::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the assets should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch assets from the Foo site #} +{% set assets = craft.assets() + .site('foo') + .all() %} +``` + +```php +// Fetch assets from the Foo site +$assets = \craft\elements\Asset::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the assets should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch assets from the site with an ID of 1 #} +{% set assets = craft.assets() + .siteId(1) + .all() %} +``` + +```php +// Fetch assets from the site with an ID of 1 +$assets = \craft\elements\Asset::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the assets’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the asset by its ID in the elements_sites table #} +{% set asset = craft.assets() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the asset by its ID in the elements_sites table +$asset = \craft\elements\Asset::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `size` + +Narrows the query results based on the assets’ file sizes (in bytes). + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1000` | with a size of 1,000 bytes (1KB). +| `'< 1000000'` | with a size of less than 1,000,000 bytes (1MB). +| `['>= 1000', '< 1000000']` | with a size between 1KB and 1MB. + + + +::: code +```twig +{# Fetch assets that are smaller than 1KB #} +{% set assets = craft.assets() + .size('< 1000') + .all() %} +``` + +```php +// Fetch assets that are smaller than 1KB +$assets = \craft\elements\Asset::find() + ->size('< 1000') + ->all(); +``` +::: + + +#### `title` + +Narrows the query results based on the assets’ titles. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch assets with a title that contains "Foo" #} +{% set assets = craft.assets() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch assets with a title that contains "Foo" +$assets = \craft\elements\Asset::find() + ->title('*Foo*') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only assets that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed assets #} +{% set assets = craft.assets() + .trashed() + .all() %} +``` + +```php +// Fetch trashed assets +$assets = \craft\elements\Asset::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the assets’ UIDs. + + + + + +::: code +```twig +{# Fetch the asset by its UID #} +{% set asset = craft.assets() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the asset by its UID +$asset = \craft\elements\Asset::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique assets across all sites #} +{% set assets = craft.assets() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique assets across all sites +$assets = \craft\elements\Asset::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `uploader` + +Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | uploaded by the user with an ID of 1. +| a [craft\elements\User](craft3:craft\elements\User) object | uploaded by the user represented by the object. + + + +::: code +```twig +{# Fetch assets uploaded by the user with an ID of 1 #} +{% set assets = craft.assets() + .uploader(1) + .all() %} +``` + +```php +// Fetch assets uploaded by the user with an ID of 1 +$assets = \craft\elements\Asset::find() + ->uploader(1) + ->all(); +``` +::: + + +#### `volume` + +Narrows the query results based on the volume the assets belong to. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'foo'` | in a volume with a handle of `foo`. +| `'not foo'` | not in a volume with a handle of `foo`. +| `['foo', 'bar']` | in a volume with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a volume with a handle of `foo` or `bar`. +| a [volume](craft3:craft\base\VolumeInterface) object | in a volume represented by the object. + + + +::: code +```twig +{# Fetch assets in the Foo volume #} +{% set assets = craft.assets() + .volume('foo') + .all() %} +``` + +```php +// Fetch assets in the Foo group +$assets = \craft\elements\Asset::find() + ->volume('foo') + ->all(); +``` +::: + + +#### `volumeId` + +Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | in a volume with an ID of 1. +| `'not 1'` | not in a volume with an ID of 1. +| `[1, 2]` | in a volume with an ID of 1 or 2. +| `['not', 1, 2]` | not in a volume with an ID of 1 or 2. +| `':empty:'` | that haven’t been stored in a volume yet + + + +::: code +```twig +{# Fetch assets in the volume with an ID of 1 #} +{% set assets = craft.assets() + .volumeId(1) + .all() %} +``` + +```php +// Fetch assets in the volume with an ID of 1 +$assets = \craft\elements\Asset::find() + ->volumeId(1) + ->all(); +``` +::: + + +#### `width` + +Narrows the query results based on the assets’ image widths. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `100` | with a width of 100. +| `'>= 100'` | with a width of at least 100. +| `['>= 100', '<= 1000']` | with a width between 100 and 1,000. + + + +::: code +```twig +{# Fetch XL images #} +{% set assets = craft.assets() + .kind('image') + .width('>= 1000') + .all() %} +``` + +```php +// Fetch XL images +$assets = \craft\elements\Asset::find() + ->kind('image') + ->width('>= 1000') + ->all(); +``` +::: + + +#### `with` + +Causes the query to return matching assets eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch assets eager-loaded with the "Related" field’s relations #} +{% set assets = craft.assets() + .with(['related']) + .all() %} +``` + +```php +// Fetch assets eager-loaded with the "Related" field’s relations +$assets = \craft\elements\Asset::find() + ->with(['related']) + ->all(); +``` +::: + + +#### `withTransforms` + +Causes the query to return matching assets eager-loaded with image transform indexes. + +This can improve performance when displaying several image transforms at once, if the transforms +have already been generated. + +Transforms can be specified as their handle or an object that contains `width` and/or `height` properties. + +You can include `srcset`-style sizes (e.g. `100w` or `2x`) following a normal transform definition, for example: + +::: code + +```twig +[{width: 1000, height: 600}, '1.5x', '2x', '3x'] +``` + +```php +[['width' => 1000, 'height' => 600], '1.5x', '2x', '3x'] +``` + +::: + +When a `srcset`-style size is encountered, the preceding normal transform definition will be used as a +reference when determining the resulting transform dimensions. + + + +::: code +```twig +{# Fetch assets with the 'thumbnail' and 'hiResThumbnail' transform data preloaded #} +{% set assets = craft.assets() + .kind('image') + .withTransforms(['thumbnail', 'hiResThumbnail']) + .all() %} +``` + +```php +// Fetch assets with the 'thumbnail' and 'hiResThumbnail' transform data preloaded +$assets = \craft\elements\Asset::find() + ->kind('image') + ->withTransforms(['thumbnail', 'hiResThumbnail']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/3.x/categories.md b/docs/.artifacts/cms/3.x/categories.md new file mode 100644 index 000000000..e0c4ee1ea --- /dev/null +++ b/docs/.artifacts/cms/3.x/categories.md @@ -0,0 +1,1343 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [ancestorDist](#ancestordist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). +| [ancestorOf](#ancestorof) | Narrows the query results to only categories that are ancestors of another category in its structure. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only categories that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. +| [asArray](#asarray) | Causes the query to return matching categories as arrays of data, rather than [Category](craft3:craft\elements\Category) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#datecreated) | Narrows the query results based on the categories’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the categories’ last-updated dates. +| [descendantDist](#descendantdist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). +| [descendantOf](#descendantof) | Narrows the query results to only categories that are descendants of another category in its structure. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [group](#group) | Narrows the query results based on the category groups the categories belong to. +| [groupId](#groupid) | Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. +| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the categories have any descendants in their structure. +| [id](#id) | Narrows the query results based on the categories’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [leaves](#leaves) | Narrows the query results based on whether the categories are “leaves” (categories with no descendants). +| [level](#level) | Narrows the query results based on the categories’ level within the structure. +| [limit](#limit) | Determines the number of categories that should be returned. +| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the category that comes immediately after another category in its structure. +| [offset](#offset) | Determines how many categories should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`, or the order defined by the category group if the [group](#group) or [groupId](#groupid) params are set to a single group.) +| [positionedAfter](#positionedafter) | Narrows the query results to only categories that are positioned after another category in its structure. +| [positionedBefore](#positionedbefore) | Narrows the query results to only categories that are positioned before another category in its structure. +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the category that comes immediately before another category in its structure. +| [relatedTo](#relatedto) | Narrows the query results to only categories that are related to certain other elements. +| [search](#search) | Narrows the query results to only categories that match a search query. +| [siblingOf](#siblingof) | Narrows the query results to only categories that are siblings of another category in its structure. +| [site](#site) | Determines which site(s) the categories should be queried in. +| [siteId](#siteid) | Determines which site(s) the categories should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the categories’ IDs in the `elements_sites` table. +| [slug](#slug) | Narrows the query results based on the categories’ slugs. +| [status](#status) | Narrows the query results based on the categories’ statuses. +| [title](#title) | Narrows the query results based on the categories’ titles. +| [trashed](#trashed) | Narrows the query results to only categories that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the categories’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uri](#uri) | Narrows the query results based on the categories’ URIs. +| [with](#with) | Causes the query to return matching categories eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `ancestorDist` + +Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). + + + + + +::: code +```twig +{# Fetch categories above this one #} +{% set categories = craft.categories() + .ancestorOf(myCategory) + .ancestorDist(3) + .all() %} +``` + +```php +// Fetch categories above this one +$categories = \craft\elements\Category::find() + ->ancestorOf($myCategory) + ->ancestorDist(3) + ->all(); +``` +::: + + +#### `ancestorOf` + +Narrows the query results to only categories that are ancestors of another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | above the category with an ID of 1. +| a [Category](craft3:craft\elements\Category) object | above the category represented by the object. + + + +::: code +```twig +{# Fetch categories above this one #} +{% set categories = craft.categories() + .ancestorOf(myCategory) + .all() %} +``` + +```php +// Fetch categories above this one +$categories = \craft\elements\Category::find() + ->ancestorOf($myCategory) + ->all(); +``` +::: + + + +::: tip +This can be combined with [ancestorDist](#ancestordist) if you want to limit how far away the ancestor categories can be. +::: + + +#### `andRelatedTo` + +Narrows the query results to only categories that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all categories that are related to myCategoryA and myCategoryB #} +{% set categories = craft.categories() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all categories that are related to $myCategoryA and $myCategoryB +$categories = \craft\elements\Category::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all categories, regardless of status #} +{% set categories = craft.categories() + .anyStatus() + .all() %} +``` + +```php +// Fetch all categories, regardless of status +$categories = \craft\elements\Category::find() + ->anyStatus() + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching categories as arrays of data, rather than [Category](craft3:craft\elements\Category) objects. + + + + + +::: code +```twig +{# Fetch categories as arrays #} +{% set categories = craft.categories() + .asArray() + .all() %} +``` + +```php +// Fetch categories as arrays +$categories = \craft\elements\Category::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `dateCreated` + +Narrows the query results based on the categories’ creation dates. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch categories created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set categories = craft.categories() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch categories created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$categories = \craft\elements\Category::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the categories’ last-updated dates. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch categories updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set categories = craft.categories() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch categories updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$categories = \craft\elements\Category::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `descendantDist` + +Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). + + + + + +::: code +```twig +{# Fetch categories below this one #} +{% set categories = craft.categories() + .descendantOf(myCategory) + .descendantDist(3) + .all() %} +``` + +```php +// Fetch categories below this one +$categories = \craft\elements\Category::find() + ->descendantOf($myCategory) + ->descendantDist(3) + ->all(); +``` +::: + + +#### `descendantOf` + +Narrows the query results to only categories that are descendants of another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | below the category with an ID of 1. +| a [Category](craft3:craft\elements\Category) object | below the category represented by the object. + + + +::: code +```twig +{# Fetch categories below this one #} +{% set categories = craft.categories() + .descendantOf(myCategory) + .all() %} +``` + +```php +// Fetch categories below this one +$categories = \craft\elements\Category::find() + ->descendantOf($myCategory) + ->all(); +``` +::: + + + +::: tip +This can be combined with [descendantDist](#descendantdist) if you want to limit how far away the descendant categories can be. +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch categories in a specific order #} +{% set categories = craft.categories() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch categories in a specific order +$categories = \craft\elements\Category::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `group` + +Narrows the query results based on the category groups the categories belong to. + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'foo'` | in a group with a handle of `foo`. +| `'not foo'` | not in a group with a handle of `foo`. +| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. +| a [CategoryGroup](craft3:craft\models\CategoryGroup) object | in a group represented by the object. + + + +::: code +```twig +{# Fetch categories in the Foo group #} +{% set categories = craft.categories() + .group('foo') + .all() %} +``` + +```php +// Fetch categories in the Foo group +$categories = \craft\elements\Category::find() + ->group('foo') + ->all(); +``` +::: + + +#### `groupId` + +Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | in a group with an ID of 1. +| `'not 1'` | not in a group with an ID of 1. +| `[1, 2]` | in a group with an ID of 1 or 2. +| `['not', 1, 2]` | not in a group with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch categories in the group with an ID of 1 #} +{% set categories = craft.categories() + .groupId(1) + .all() %} +``` + +```php +// Fetch categories in the group with an ID of 1 +$categories = \craft\elements\Category::find() + ->groupId(1) + ->all(); +``` +::: + + +#### `hasDescendants` + +Narrows the query results based on whether the categories have any descendants in their structure. + + + +(This has the opposite effect of calling [leaves](#leaves).) + + + +::: code +```twig +{# Fetch categories that have descendants #} +{% set categories = craft.categories() + .hasDescendants() + .all() %} +``` + +```php +// Fetch categories that have descendants +$categories = \craft\elements\Category::find() + ->hasDescendants() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the categories’ IDs. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the category by its ID #} +{% set category = craft.categories() + .id(1) + .one() %} +``` + +```php +// Fetch the category by its ID +$category = \craft\elements\Category::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch categories in reverse #} +{% set categories = craft.categories() + .inReverse() + .all() %} +``` + +```php +// Fetch categories in reverse +$categories = \craft\elements\Category::find() + ->inReverse() + ->all(); +``` +::: + + +#### `leaves` + +Narrows the query results based on whether the categories are “leaves” (categories with no descendants). + + + +(This has the opposite effect of calling [hasDescendants](#hasdescendants).) + + + +::: code +```twig +{# Fetch categories that have no descendants #} +{% set categories = craft.categories() + .leaves() + .all() %} +``` + +```php +// Fetch categories that have no descendants +$categories = \craft\elements\Category::find() + ->leaves() + ->all(); +``` +::: + + +#### `level` + +Narrows the query results based on the categories’ level within the structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | with a level of 1. +| `'not 1'` | not with a level of 1. +| `'>= 3'` | with a level greater than or equal to 3. +| `[1, 2]` | with a level of 1 or 2 +| `['not', 1, 2]` | not with level of 1 or 2. + + + +::: code +```twig +{# Fetch categories positioned at level 3 or above #} +{% set categories = craft.categories() + .level('>= 3') + .all() %} +``` + +```php +// Fetch categories positioned at level 3 or above +$categories = \craft\elements\Category::find() + ->level('>= 3') + ->all(); +``` +::: + + +#### `limit` + +Determines the number of categories that should be returned. + + + +::: code +```twig +{# Fetch up to 10 categories #} +{% set categories = craft.categories() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 categories +$categories = \craft\elements\Category::find() + ->limit(10) + ->all(); +``` +::: + + +#### `nextSiblingOf` + +Narrows the query results to only the category that comes immediately after another category in its structure. + + + +Possible values include: + +| Value | Fetches the category… +| - | - +| `1` | after the category with an ID of 1. +| a [Category](craft3:craft\elements\Category) object | after the category represented by the object. + + + +::: code +```twig +{# Fetch the next category #} +{% set category = craft.categories() + .nextSiblingOf(myCategory) + .one() %} +``` + +```php +// Fetch the next category +$category = \craft\elements\Category::find() + ->nextSiblingOf($myCategory) + ->one(); +``` +::: + + +#### `offset` + +Determines how many categories should be skipped in the results. + + + +::: code +```twig +{# Fetch all categories except for the first 3 #} +{% set categories = craft.categories() + .offset(3) + .all() %} +``` + +```php +// Fetch all categories except for the first 3 +$categories = \craft\elements\Category::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`, or the order defined by the category group if the [group](#group) or [groupId](#groupid) params are set to a single group.) + + + +::: code +```twig +{# Fetch all categories in order of date created #} +{% set categories = craft.categories() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all categories in order of date created +$categories = \craft\elements\Category::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `positionedAfter` + +Narrows the query results to only categories that are positioned after another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | after the category with an ID of 1. +| a [Category](craft3:craft\elements\Category) object | after the category represented by the object. + + + +::: code +```twig +{# Fetch categories after this one #} +{% set categories = craft.categories() + .positionedAfter(myCategory) + .all() %} +``` + +```php +// Fetch categories after this one +$categories = \craft\elements\Category::find() + ->positionedAfter($myCategory) + ->all(); +``` +::: + + +#### `positionedBefore` + +Narrows the query results to only categories that are positioned before another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | before the category with an ID of 1. +| a [Category](craft3:craft\elements\Category) object | before the category represented by the object. + + + +::: code +```twig +{# Fetch categories before this one #} +{% set categories = craft.categories() + .positionedBefore(myCategory) + .all() %} +``` + +```php +// Fetch categories before this one +$categories = \craft\elements\Category::find() + ->positionedBefore($myCategory) + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique categories from Site A, or Site B if they don’t exist in Site A #} +{% set categories = craft.categories() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique categories from Site A, or Site B if they don’t exist in Site A +$categories = \craft\elements\Category::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prevSiblingOf` + +Narrows the query results to only the category that comes immediately before another category in its structure. + + + +Possible values include: + +| Value | Fetches the category… +| - | - +| `1` | before the category with an ID of 1. +| a [Category](craft3:craft\elements\Category) object | before the category represented by the object. + + + +::: code +```twig +{# Fetch the previous category #} +{% set category = craft.categories() + .prevSiblingOf(myCategory) + .one() %} +``` + +```php +// Fetch the previous category +$category = \craft\elements\Category::find() + ->prevSiblingOf($myCategory) + ->one(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only categories that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all categories that are related to myCategory #} +{% set categories = craft.categories() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all categories that are related to $myCategory +$categories = \craft\elements\Category::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only categories that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all categories that match the search query #} +{% set categories = craft.categories() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all categories that match the search query +$categories = \craft\elements\Category::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `siblingOf` + +Narrows the query results to only categories that are siblings of another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | beside the category with an ID of 1. +| a [Category](craft3:craft\elements\Category) object | beside the category represented by the object. + + + +::: code +```twig +{# Fetch categories beside this one #} +{% set categories = craft.categories() + .siblingOf(myCategory) + .all() %} +``` + +```php +// Fetch categories beside this one +$categories = \craft\elements\Category::find() + ->siblingOf($myCategory) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the categories should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch categories from the Foo site #} +{% set categories = craft.categories() + .site('foo') + .all() %} +``` + +```php +// Fetch categories from the Foo site +$categories = \craft\elements\Category::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the categories should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch categories from the site with an ID of 1 #} +{% set categories = craft.categories() + .siteId(1) + .all() %} +``` + +```php +// Fetch categories from the site with an ID of 1 +$categories = \craft\elements\Category::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the categories’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the category by its ID in the elements_sites table #} +{% set category = craft.categories() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the category by its ID in the elements_sites table +$category = \craft\elements\Category::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `slug` + +Narrows the query results based on the categories’ slugs. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'foo'` | with a slug of `foo`. +| `'foo*'` | with a slug that begins with `foo`. +| `'*foo'` | with a slug that ends with `foo`. +| `'*foo*'` | with a slug that contains `foo`. +| `'not *foo*'` | with a slug that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested category slug from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the category with that slug #} +{% set category = craft.categories() + .slug(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested category slug from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the category with that slug +$category = \craft\elements\Category::find() + ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the categories’ statuses. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'enabled'` _(default)_ | that are enabled. +| `'disabled'` | that are disabled. +| `['not', 'disabled']` | that are not disabled. + + + +::: code +```twig +{# Fetch disabled categories #} +{% set categories = craft.categories() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled categories +$categories = \craft\elements\Category::find() + ->status('disabled') + ->all(); +``` +::: + + +#### `title` + +Narrows the query results based on the categories’ titles. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch categories with a title that contains "Foo" #} +{% set categories = craft.categories() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch categories with a title that contains "Foo" +$categories = \craft\elements\Category::find() + ->title('*Foo*') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only categories that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed categories #} +{% set categories = craft.categories() + .trashed() + .all() %} +``` + +```php +// Fetch trashed categories +$categories = \craft\elements\Category::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the categories’ UIDs. + + + + + +::: code +```twig +{# Fetch the category by its UID #} +{% set category = craft.categories() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the category by its UID +$category = \craft\elements\Category::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique categories across all sites #} +{% set categories = craft.categories() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique categories across all sites +$categories = \craft\elements\Category::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `uri` + +Narrows the query results based on the categories’ URIs. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the category with that URI #} +{% set category = craft.categories() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the category with that URI +$category = \craft\elements\Category::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching categories eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch categories eager-loaded with the "Related" field’s relations #} +{% set categories = craft.categories() + .with(['related']) + .all() %} +``` + +```php +// Fetch categories eager-loaded with the "Related" field’s relations +$categories = \craft\elements\Category::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/3.x/config-db.md b/docs/.artifacts/cms/3.x/config-db.md new file mode 100644 index 000000000..85d91f9af --- /dev/null +++ b/docs/.artifacts/cms/3.x/config-db.md @@ -0,0 +1,379 @@ + + + + +### `attributes` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [DbConfig::$attributes](craft3:craft\config\DbConfig::$attributes) + +
+ +An array of key => value pairs of PDO attributes to pass into the PDO constructor. + +For example, when using the [MySQL PDO driver](https://php.net/manual/en/ref.pdo-mysql.php), if you wanted to enable a SSL database connection +(assuming [SSL is enabled in MySQL](https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-secure-connections.html) and `'user'` can connect via SSL, +you’d set these: + +```php +[ + PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem', + PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem', + PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem', +], +``` + + + +### `charset` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'utf8'` + +Defined by +: [DbConfig::$charset](craft3:craft\config\DbConfig::$charset) + +
+ +The charset to use when creating tables. + +::: tip +You can change the character set and collation across all existing database tables using this terminal command: + +```bash +> php craft db/convert-charset +``` +::: + + + +### `collation` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$collation](craft3:craft\config\DbConfig::$collation) + +Since +: 3.6.4 + +
+ +The collation to use when creating tables. + +This is only used by MySQL. If null, the [charset’s](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#charset) default collation will be used. + +| Charset | Default collation | +| --------- | -------------------- | +| `utf8` | `utf8_general_ci` | +| `utf8mb4` | `utf8mb4_0900_ai_ci` | + +::: tip +You can change the character set and collation across all existing database tables using this terminal command: + +```bash +> php craft db/convert-charset +``` +::: + + + +### `database` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$database](craft3:craft\config\DbConfig::$database) + +
+ +The name of the database to select. + + + +### `driver` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$driver](craft3:craft\config\DbConfig::$driver) + +
+ +The database driver to use. Either `mysql` for MySQL or `pgsql` for PostgreSQL. + + + +### `dsn` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$dsn](craft3:craft\config\DbConfig::$dsn) + +
+ +The Data Source Name (“DSN”) that tells Craft how to connect to the database. + +DSNs should begin with a driver prefix (`mysql:` or `pgsql:`), followed by driver-specific parameters. +For example, `mysql:host=127.0.0.1;port=3306;dbname=acme_corp`. + +- MySQL parameters: +- PostgreSQL parameters: + + + +### `password` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [DbConfig::$password](craft3:craft\config\DbConfig::$password) + +
+ +The database password to connect with. + + + +### `port` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$port](craft3:craft\config\DbConfig::$port) + +
+ +The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. + + + +### `schema` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'public'` + +Defined by +: [DbConfig::$schema](craft3:craft\config\DbConfig::$schema) + +
+ +The schema that Postgres is configured to use by default (PostgreSQL only). + +::: tip +To force Craft to use the specified schema regardless of PostgreSQL’s `search_path` setting, you must enable +the [setSchemaOnConnect](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#setschemaonconnect) setting. +::: + + + +### `server` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$server](craft3:craft\config\DbConfig::$server) + +
+ +The database server name or IP address. Usually `localhost` or `127.0.0.1`. + + + +### `setSchemaOnConnect` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [DbConfig::$setSchemaOnConnect](craft3:craft\config\DbConfig::$setSchemaOnConnect) + +Since +: 3.7.27 + +
+ +Whether the [schema](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#schema) should be explicitly used for database queries (PostgreSQL only). + +::: warning +This will cause an extra `SET search_path` SQL query to be executed per database connection. Ideally, +PostgreSQL’s `search_path` setting should be configured to prioritize the desired schema. +::: + + + +### `tablePrefix` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [DbConfig::$tablePrefix](craft3:craft\config\DbConfig::$tablePrefix) + +
+ +If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), +you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase. + + + +### `unixSocket` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$unixSocket](craft3:craft\config\DbConfig::$unixSocket) + +
+ +MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of +the server and port. If this is specified, then `server` and `port` settings are ignored. + + + +### `url` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$url](craft3:craft\config\DbConfig::$url) + +
+ +The database connection URL, if one was provided by your hosting environment. + +If this is set, the values for [driver](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#driver), [user](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#user), [database](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#database), [server](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#server), [port](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#port), and [database](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#database) will be extracted from it. + + + +### `useUnbufferedConnections` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [DbConfig::$useUnbufferedConnections](craft3:craft\config\DbConfig::$useUnbufferedConnections) + +Since +: 3.7.0 + +
+ +Whether batched queries should be executed on a separate, unbuffered database connection. + +This setting only applies to MySQL. It can be enabled when working with high volume content, to prevent +PHP from running out of memory when querying too much data at once. (See + for an explanation +of MySQL’s batch query limitations.) + + + +### `user` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'root'` + +Defined by +: [DbConfig::$user](craft3:craft\config\DbConfig::$user) + +
+ +The database username to connect with. + + + + + diff --git a/docs/.artifacts/cms/3.x/config-general.md b/docs/.artifacts/cms/3.x/config-general.md new file mode 100644 index 000000000..a8fd8dbf7 --- /dev/null +++ b/docs/.artifacts/cms/3.x/config-general.md @@ -0,0 +1,3467 @@ + + + + +## System + +### `accessibilityDefaults` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[ + 'alwaysShowFocusRings' => false, + 'useShapes' => false, + 'underlineLinks' => false, +]` + +Defined by +: [GeneralConfig::$accessibilityDefaults](craft3:craft\config\GeneralConfig::$accessibilityDefaults) + +Since +: 3.6.4 + +
+ +The default user accessibility preferences that should be applied to users that haven’t saved their preferences yet. + +The array can contain the following keys: + +- `alwaysShowFocusRings` - Whether focus rings should always be shown when an element has focus +- `useShapes` – Whether shapes should be used to represent statuses +- `underlineLinks` – Whether links should be underlined + + + +### `allowAdminChanges` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$allowAdminChanges](craft3:craft\config\GeneralConfig::$allowAdminChanges) + +Since +: 3.1.0 + +
+ +Whether admins should be allowed to make administrative changes to the system. + +When this is disabled, the Settings section will be hidden, the Craft edition and Craft/plugin versions will be locked, +and the project config and Plugin Store will become read-only—though Craft and plugin licenses may still be purchased. + +It’s best to disable this in production environments with a deployment workflow that runs `composer install` and +[propagates project config updates](../project-config.md#propagating-changes) on deploy. + +::: warning +Don’t disable this setting until **all** environments have been updated to Craft 3.1.0 or later. +::: + + + +### `allowSimilarTags` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$allowSimilarTags](craft3:craft\config\GeneralConfig::$allowSimilarTags) + +
+ +Whether users should be allowed to create similarly-named tags. + + + +### `allowUpdates` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$allowUpdates](craft3:craft\config\GeneralConfig::$allowUpdates) + +
+ +Whether Craft should allow system and plugin updates in the control panel, and plugin installation from the Plugin Store. + +This setting will automatically be disabled if is disabled. + + + +### `autoLoginAfterAccountActivation` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$autoLoginAfterAccountActivation](craft3:craft\config\GeneralConfig::$autoLoginAfterAccountActivation) + +
+ +Whether users should automatically be logged in after activating their account or resetting their password. + + + +### `autosaveDrafts` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$autosaveDrafts](craft3:craft\config\GeneralConfig::$autosaveDrafts) + +Since +: 3.5.6 + +
+ +Whether drafts should be saved automatically as they are edited. + +Note that drafts *will* be autosaved while Live Preview is open, regardless of this setting. + + + +### `backupOnUpdate` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$backupOnUpdate](craft3:craft\config\GeneralConfig::$backupOnUpdate) + +
+ +Whether Craft should create a database backup before applying a new system update. + + + +### `cacheDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `86400` (1 day) + +Defined by +: [GeneralConfig::$cacheDuration](craft3:craft\config\GeneralConfig::$cacheDuration) + +
+ +The default length of time Craft will store data, RSS feed, and template caches. + +If set to `0`, data and RSS feed caches will be stored indefinitely; template caches will be stored for one year. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `cpHeadTags` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$cpHeadTags](craft3:craft\config\GeneralConfig::$cpHeadTags) + +Since +: 3.5.0 + +
+ +List of additional HTML tags that should be included in the `` of control panel pages. + +Each tag can be specified as an array of the tag name and its attributes. + +For example, you can give the control panel a custom favicon (etc.) like this: + +```php +'cpHeadTags' => [ + // Traditional favicon + ['link', ['rel' => 'icon', 'href' => '/icons/favicon.ico']], + // Scalable favicon for browsers that support them + ['link', ['rel' => 'icon', 'type' => 'image/svg+xml', 'sizes' => 'any', 'href' => '/icons/favicon.svg']], + // Touch icon for mobile devices + ['link', ['rel' => 'apple-touch-icon', 'sizes' => '180x180', 'href' => '/icons/touch-icon.svg']], + // Pinned tab icon for Safari + ['link', ['rel' => 'mask-icon', 'href' => '/icons/mask-icon.svg', 'color' => '#663399']], +], +``` + + + +### `defaultCpLanguage` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$defaultCpLanguage](craft3:craft\config\GeneralConfig::$defaultCpLanguage) + +
+ +The default language the control panel should use for users who haven’t set a preferred language yet. + + + +### `defaultCpLocale` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$defaultCpLocale](craft3:craft\config\GeneralConfig::$defaultCpLocale) + +Since +: 3.5.0 + +
+ +The default locale the control panel should use for date/number formatting, for users who haven’t set +a preferred language or formatting locale. + +If this is `null`, the config setting will determine which locale is used for date/number formatting by default. + + + +### `defaultDirMode` + +
+ +Allowed types +: `mixed` + +Default value +: `0775` + +Defined by +: [GeneralConfig::$defaultDirMode](craft3:craft\config\GeneralConfig::$defaultDirMode) + +
+ +The default permission to be set for newly-generated directories. + +If set to `null`, the permission will be determined by the current environment. + + + +### `defaultFileMode` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$defaultFileMode](craft3:craft\config\GeneralConfig::$defaultFileMode) + +
+ +The default permission to be set for newly-generated files. + +If set to `null`, the permission will be determined by the current environment. + + + +### `defaultSearchTermOptions` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$defaultSearchTermOptions](craft3:craft\config\GeneralConfig::$defaultSearchTermOptions) + +
+ +The default options that should be applied to each search term. + +Options include: + +- `attribute` – The attribute that the term should apply to (e.g. `'title'`), if any. (`null` by default) +- `exact` – Whether the term must be an exact match (only applies if `attribute` is set). (`false` by default) +- `exclude` – Whether search results should *exclude* records with this term. (`false` by default) +- `subLeft` – Whether to include keywords that contain the term, with additional characters before it. (`false` by default) +- `subRight` – Whether to include keywords that contain the term, with additional characters after it. (`true` by default) + + + +### `defaultTemplateExtensions` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[ + 'html', + 'twig', +]` + +Defined by +: [GeneralConfig::$defaultTemplateExtensions](craft3:craft\config\GeneralConfig::$defaultTemplateExtensions) + +
+ +The template file extensions Craft will look for when matching a template path to a file on the front end. + + + +### `defaultWeekStartDay` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `1` (Monday) + +Defined by +: [GeneralConfig::$defaultWeekStartDay](craft3:craft\config\GeneralConfig::$defaultWeekStartDay) + +
+ +The default day new users should have set as their Week Start Day. + +This should be set to one of the following integers: + +- `0` – Sunday +- `1` – Monday +- `2` – Tuesday +- `3` – Wednesday +- `4` – Thursday +- `5` – Friday +- `6` – Saturday + + + +### `devMode` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$devMode](craft3:craft\config\GeneralConfig::$devMode) + +
+ +Whether the system should run in [Dev Mode](https://craftcms.com/support/dev-mode). + + + +### `disabledPlugins` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$disabledPlugins](craft3:craft\config\GeneralConfig::$disabledPlugins) + +Since +: 3.1.9 + +
+ +Array of plugin handles that should be disabled, regardless of what the project config says. + +```php +'dev' => [ + 'disabledPlugins' => ['webhooks'], +], +``` + +This can also be set to `'*'` to disable **all** plugins. + +```php +'dev' => [ + 'disabledPlugins' => '*', +], +``` + +::: warning +This should not be set on a per-environment basis, as it could result in plugin schema version mismatches +between environments, which will prevent project config changes from getting applied. +::: + + + +### `disallowRobots` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$disallowRobots](craft3:craft\config\GeneralConfig::$disallowRobots) + +Since +: 3.5.10 + +
+ +Whether front end requests should respond with `X-Robots-Tag: none` HTTP headers, indicating that pages should not be indexed, +and links on the page should not be followed, by web crawlers. + +::: tip +This should be set to `true` for development and staging environments. +::: + + + +### `enableTemplateCaching` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableTemplateCaching](craft3:craft\config\GeneralConfig::$enableTemplateCaching) + +
+ +Whether to enable Craft’s template `{% cache %}` tag on a global basis. + + + +### `errorTemplatePrefix` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [GeneralConfig::$errorTemplatePrefix](craft3:craft\config\GeneralConfig::$errorTemplatePrefix) + +
+ +The prefix that should be prepended to HTTP error status codes when determining the path to look for an error’s template. + +If set to `'_'` your site’s 404 template would live at `templates/_404.html`, for example. + + + +### `extraAllowedFileExtensions` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$extraAllowedFileExtensions](craft3:craft\config\GeneralConfig::$extraAllowedFileExtensions) + +
+ +List of file extensions that will be merged into the config setting. + + + +### `extraAppLocales` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$extraAppLocales](craft3:craft\config\GeneralConfig::$extraAppLocales) + +Since +: 3.0.24 + +
+ +List of extra locale IDs that the application should support, and users should be able to select as their Preferred Language. + +Only use this setting if your server has the Intl PHP extension, or if you’ve saved the corresponding +[locale data](https://github.com/craftcms/locales) into your `config/locales/` folder. + + + +### `handleCasing` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `GeneralConfig::CAMEL_CASE` + +Defined by +: [GeneralConfig::$handleCasing](craft3:craft\config\GeneralConfig::$handleCasing) + +Since +: 3.6.0 + +
+ +The casing to use for autogenerated component handles. + +This can be set to one of the following: + +- `camel` – for camelCase +- `pascal` – for PascalCase (aka UpperCamelCase) +- `snake` – for snake_case + + + +### `headlessMode` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$headlessMode](craft3:craft\config\GeneralConfig::$headlessMode) + +Since +: 3.3.0 + +
+ +Whether the system should run in Headless Mode, which optimizes the system and control panel for headless CMS implementations. + +When this is enabled, the following changes will take place: + +- Template settings for sections and category groups will be hidden. +- Template route management will be hidden. +- Front-end routing will skip checks for element and template requests. +- Front-end responses will be JSON-formatted rather than HTML by default. +- Twig will be configured to escape unsafe strings for JavaScript/JSON rather than HTML by default for front-end requests. +- The , , , and settings will be ignored. + +::: tip +With Headless Mode enabled, users may only set passwords and verify email addresses via the control panel. Be sure to grant “Access the control +panel” permission to all content editors and administrators. You’ll also need to set the config setting if the control +panel is located on a different domain than your front end. +::: + + + +### `httpProxy` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$httpProxy](craft3:craft\config\GeneralConfig::$httpProxy) + +Since +: 3.7.0 + +
+ +The proxy server that should be used for outgoing HTTP requests. + +This can be set to a URL (`http://localhost`) or a URL plus a port (`http://localhost:8125`). + + + +### `indexTemplateFilenames` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[ + 'index', +]` + +Defined by +: [GeneralConfig::$indexTemplateFilenames](craft3:craft\config\GeneralConfig::$indexTemplateFilenames) + +
+ +The template filenames Craft will look for within a directory to represent the directory’s “index” template when +matching a template path to a file on the front end. + + + +### `ipHeaders` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$ipHeaders](craft3:craft\config\GeneralConfig::$ipHeaders) + +
+ +List of headers where proxies store the real client IP. + +See [yii\web\Request::$ipHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$ipHeaders-detail) for more details. + +If not set, the default [craft\web\Request::$ipHeaders](https://docs.craftcms.com/api/v3/craft-web-request.html#ipheaders) value will be used. + + + +### `isSystemLive` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$isSystemLive](craft3:craft\config\GeneralConfig::$isSystemLive) + +
+ +Whether the site is currently live. If set to `true` or `false`, it will take precedence over the System Status setting +in Settings → General. + + + +### `limitAutoSlugsToAscii` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$limitAutoSlugsToAscii](craft3:craft\config\GeneralConfig::$limitAutoSlugsToAscii) + +
+ +Whether non-ASCII characters in auto-generated slugs should be converted to ASCII (i.e. ñ → n). + +::: tip +This only affects the JavaScript auto-generated slugs. Non-ASCII characters can still be used in slugs if entered manually. +::: + + + +### `maxBackups` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [false](https://php.net/language.types.boolean) + +Default value +: `20` + +Defined by +: [GeneralConfig::$maxBackups](craft3:craft\config\GeneralConfig::$maxBackups) + +
+ +The number of backups Craft should make before it starts deleting the oldest backups. If set to `false`, Craft will +not delete any backups. + + + +### `maxRevisions` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) + +Default value +: `50` + +Defined by +: [GeneralConfig::$maxRevisions](craft3:craft\config\GeneralConfig::$maxRevisions) + +Since +: 3.2.0 + +
+ +The maximum number of revisions that should be stored for each element. + +Set to `0` if you want to store an unlimited number of revisions. + + + +### `maxSlugIncrement` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `100` + +Defined by +: [GeneralConfig::$maxSlugIncrement](craft3:craft\config\GeneralConfig::$maxSlugIncrement) + +
+ +The highest number Craft will tack onto a slug in order to make it unique before giving up and throwing an error. + + + +### `permissionsPolicyHeader` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$permissionsPolicyHeader](craft3:craft\config\GeneralConfig::$permissionsPolicyHeader) + +Since +: 3.6.14 + +
+ +The `Permissions-Policy` header that should be sent for web responses. + + + +### `phpMaxMemoryLimit` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$phpMaxMemoryLimit](craft3:craft\config\GeneralConfig::$phpMaxMemoryLimit) + +
+ +The maximum amount of memory Craft will try to reserve during memory-intensive operations such as zipping, +unzipping and updating. Defaults to an empty string, which means it will use as much memory as it can. + +See for a list of acceptable values. + + + +### `previewIframeResizerOptions` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$previewIframeResizerOptions](craft3:craft\config\GeneralConfig::$previewIframeResizerOptions) + +Since +: 3.5.0 + +
+ +Custom [iFrame Resizer options](http://davidjbradshaw.github.io/iframe-resizer/#options) that should be used for preview iframes. + +```php +'previewIframeResizerOptions' => [ + 'autoResize' => false, +], +``` + + + +### `privateTemplateTrigger` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'_'` + +Defined by +: [GeneralConfig::$privateTemplateTrigger](craft3:craft\config\GeneralConfig::$privateTemplateTrigger) + +
+ +The template path segment prefix that should be used to identify “private” templates, which are templates that are not +directly accessible via a matching URL. + +Set to an empty value to disable public template routing. + + + +### `runQueueAutomatically` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$runQueueAutomatically](craft3:craft\config\GeneralConfig::$runQueueAutomatically) + +
+ +Whether Craft should run pending queue jobs automatically when someone visits the control panel. + +If disabled, an alternate queue worker *must* be set up separately, either as an +[always-running daemon](https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/worker.md), or a cron job that runs the +`queue/run` command every minute: + +```cron +* * * * * /path/to/project/craft queue/run +``` + +::: tip +This setting should be disabled for servers running Win32, or with Apache’s mod_deflate/mod_gzip installed, +where PHP’s [flush()](https://php.net/manual/en/function.flush.php) method won’t work. +::: + + + +### `sameSiteCookieValue` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `null` + +Defined by +: [GeneralConfig::$sameSiteCookieValue](craft3:craft\config\GeneralConfig::$sameSiteCookieValue) + +Since +: 3.1.33 + +
+ +The [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) value that should be set on Craft cookies, if any. + +This can be set to `'None'`, `'Lax'`, `'Strict'`, or `null`. + +::: tip +This setting requires PHP 7.3 or later. +::: + + + +### `sendContentLengthHeader` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$sendContentLengthHeader](craft3:craft\config\GeneralConfig::$sendContentLengthHeader) + +Since +: 3.7.3 + +
+ +Whether a `Content-Length` header should be sent with responses. + + + +### `sendPoweredByHeader` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$sendPoweredByHeader](craft3:craft\config\GeneralConfig::$sendPoweredByHeader) + +
+ +Whether an `X-Powered-By: Craft CMS` header should be sent, helping services like [BuiltWith](https://builtwith.com/) and +[Wappalyzer](https://www.wappalyzer.com/) identify that the site is running on Craft. + + + +### `slugWordSeparator` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'-'` + +Defined by +: [GeneralConfig::$slugWordSeparator](craft3:craft\config\GeneralConfig::$slugWordSeparator) + +
+ +The character(s) that should be used to separate words in slugs. + + + +### `testToEmailAddress` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [array](https://php.net/language.types.array), [false](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$testToEmailAddress](craft3:craft\config\GeneralConfig::$testToEmailAddress) + +
+ +Configures Craft to send all system emails to either a single email address or an array of email addresses +for testing purposes. + +By default, the recipient name(s) will be “Test Recipient”, but you can customize that by setting the value with the format +`['me@domain.tld' => 'Name']`. + + + +### `timezone` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$timezone](craft3:craft\config\GeneralConfig::$timezone) + +
+ +The timezone of the site. If set, it will take precedence over the Timezone setting in Settings → General. + +This can be set to one of PHP’s [supported timezones](https://php.net/manual/en/timezones.php). + + + +### `translationDebugOutput` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$translationDebugOutput](craft3:craft\config\GeneralConfig::$translationDebugOutput) + +
+ +Whether translated messages should be wrapped in special characters to help find any strings that are not being run through +`Craft::t()` or the `|translate` filter. + + + +### `useEmailAsUsername` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$useEmailAsUsername](craft3:craft\config\GeneralConfig::$useEmailAsUsername) + +
+ +Whether Craft should set users’ usernames to their email addresses, rather than let them set their username separately. + +If you enable this setting after user accounts already exist, run this terminal command to update existing usernames: + +```bash +php craft utils/update-usernames +``` + + + +### `useFileLocks` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$useFileLocks](craft3:craft\config\GeneralConfig::$useFileLocks) + +
+ +Whether to grab an exclusive lock on a file when writing to it by using the `LOCK_EX` flag. + +Some file systems, such as NFS, do not support exclusive file locking. + +If not set to `true` or `false`, Craft will try to detect if the underlying file system supports exclusive file locking and cache the results. + + + +### `useIframeResizer` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$useIframeResizer](craft3:craft\config\GeneralConfig::$useIframeResizer) + +Since +: 3.5.5 + +
+ +Whether [iFrame Resizer options](http://davidjbradshaw.github.io/iframe-resizer/#options) should be used for Live Preview. + +Using iFrame Resizer makes it possible for Craft to retain the preview’s scroll position between page loads, for cross-origin web pages. + +It works by setting the height of the iframe to match the height of the inner web page, and the iframe’s container will be scrolled rather +than the iframe document itself. This can lead to some unexpected CSS issues, however, because the previewed viewport height will be taller +than the visible portion of the iframe. + +If you have a [decoupled front end](https://craftcms.com/docs/3.x/entries.html#previewing-decoupled-front-ends), you will need to include +[iframeResizer.contentWindow.min.js](https://raw.github.com/davidjbradshaw/iframe-resizer/master/js/iframeResizer.contentWindow.min.js) on your +page as well for this to work. You can conditionally include it for only Live Preview requests by checking if the requested URL contains a +`x-craft-live-preview` query string parameter. + +::: tip +You can customize the behavior of iFrame Resizer via the config setting. +::: + + + +## Environment + +### `aliases` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$aliases](craft3:craft\config\GeneralConfig::$aliases) + +
+ +Any custom Yii [aliases](https://www.yiiframework.com/doc/guide/2.0/en/concept-aliases) that should be defined for every request. + + + +### `backupCommand` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [false](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$backupCommand](craft3:craft\config\GeneralConfig::$backupCommand) + +
+ +The shell command that Craft should execute to create a database backup. + +When set to `null` (default), Craft will run `mysqldump` or `pg_dump`, provided that those libraries are in the `$PATH` variable +for the system user running the web server. + +You may provide your own command, which can include several tokens Craft will substitute at runtime: + +- `{file}` - the target backup file path +- `{port}` - the current database port +- `{server}` - the current database hostname +- `{user}` - user that was used to connect to the database +- `{password}` - password for the specified `{user}` +- `{database}` - the current database name +- `{schema}` - the current database schema (if any) + +This can also be set to `false` to disable database backups completely. + + + +### `defaultCookieDomain` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [GeneralConfig::$defaultCookieDomain](craft3:craft\config\GeneralConfig::$defaultCookieDomain) + +
+ +The domain that cookies generated by Craft should be created for. If blank, it will be left up to the browser to determine +which domain to use (almost always the current). If you want the cookies to work for all subdomains, for example, you could +set this to `'.my-project.tld'`. + + + +### `resourceBasePath` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'@webroot/cpresources'` + +Defined by +: [GeneralConfig::$resourceBasePath](craft3:craft\config\GeneralConfig::$resourceBasePath) + +
+ +The path to the root directory that should store published control panel resources. + + + +### `resourceBaseUrl` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'@web/cpresources'` + +Defined by +: [GeneralConfig::$resourceBaseUrl](craft3:craft\config\GeneralConfig::$resourceBaseUrl) + +
+ +The URL to the root directory that should store published control panel resources. + + + +### `restoreCommand` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$restoreCommand](craft3:craft\config\GeneralConfig::$restoreCommand) + +
+ +The shell command Craft should execute to restore a database backup. + +By default Craft will run `mysql` or `psql`, provided those libraries are in the `$PATH` variable for the user the web server is running as. + +There are several tokens you can use that Craft will swap out at runtime: + +- `{path}` - the backup file path +- `{port}` - the current database port +- `{server}` - the current database hostname +- `{user}` - the user to connect to the database +- `{database}` - the current database name +- `{schema}` - the current database schema (if any) + +This can also be set to `false` to disable database restores completely. + + + +## Routing + +### `actionTrigger` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'actions'` + +Defined by +: [GeneralConfig::$actionTrigger](craft3:craft\config\GeneralConfig::$actionTrigger) + +
+ +The URI segment Craft should look for when determining if the current request should be routed to a controller action. + + + +### `activateAccountSuccessPath` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$activateAccountSuccessPath](craft3:craft\config\GeneralConfig::$activateAccountSuccessPath) + +
+ +The URI that users without access to the control panel should be redirected to after activating their account. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `addTrailingSlashesToUrls` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$addTrailingSlashesToUrls](craft3:craft\config\GeneralConfig::$addTrailingSlashesToUrls) + +
+ +Whether auto-generated URLs should have trailing slashes. + + + +### `allowUppercaseInSlug` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$allowUppercaseInSlug](craft3:craft\config\GeneralConfig::$allowUppercaseInSlug) + +
+ +Whether uppercase letters should be allowed in slugs. + + + +### `baseCpUrl` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$baseCpUrl](craft3:craft\config\GeneralConfig::$baseCpUrl) + +
+ +The base URL Craft should use when generating control panel URLs. + +It will be determined automatically if left blank. + +::: tip +The base control panel URL should **not** include the [control panel trigger word](config3:cpTrigger) (e.g. `/admin`). +::: + + + +### `cpTrigger` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `'admin'` + +Defined by +: [GeneralConfig::$cpTrigger](craft3:craft\config\GeneralConfig::$cpTrigger) + +
+ +The URI segment Craft should look for when determining if the current request should route to the control panel rather than +the front-end website. + +This can be set to `null` if you have a dedicated hostname for the control panel (e.g. `cms.my-project.tld`), or you are running Craft in +[Headless Mode](config3:headlessMode). If you do that, you will need to ensure that the control panel is being served from its own web root +directory on your server, with an `index.php` file that defines the `CRAFT_CP` PHP constant. + +```php +define('CRAFT_CP', true); +``` + +Alternatively, you can set the config setting, but then you will run the risk of losing access to portions of your +control panel due to URI conflicts with actual folders/files in your main web root. + +(For example, if you have an `assets/` folder, that would conflict with the `/assets` page in the control panel.) + + + +### `invalidUserTokenPath` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$invalidUserTokenPath](craft3:craft\config\GeneralConfig::$invalidUserTokenPath) + +
+ +The URI Craft should redirect to when user token validation fails. A token is used on things like setting and resetting user account +passwords. Note that this only affects front-end site requests. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `loginPath` + +
+ +Allowed types +: `mixed` + +Default value +: `'login'` + +Defined by +: [GeneralConfig::$loginPath](craft3:craft\config\GeneralConfig::$loginPath) + +
+ +The URI Craft should use for user login on the front end. + +This can be set to `false` to disable front-end login. + +Note that this config setting is ignored when is enabled. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `logoutPath` + +
+ +Allowed types +: `mixed` + +Default value +: `'logout'` + +Defined by +: [GeneralConfig::$logoutPath](craft3:craft\config\GeneralConfig::$logoutPath) + +
+ +The URI Craft should use for user logout on the front end. + +This can be set to `false` to disable front-end logout. + +Note that this config setting is ignored when is enabled. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `omitScriptNameInUrls` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$omitScriptNameInUrls](craft3:craft\config\GeneralConfig::$omitScriptNameInUrls) + +
+ +Whether generated URLs should omit `index.php` (e.g. `http://my-project.tld/path` instead of `http://my-project.tld/index.php/path`) + +This can only be possible if your server is configured to redirect would-be 404s to `index.php`, for example, with the redirect found +in the `.htaccess` file that came with Craft: + +``` +RewriteEngine On +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule (.+) /index.php?p= [QSA,L] +``` + +::: tip +Even when this is set to `true`, the script name could still be included in some action URLs. +If you want to ensure that `index.php` is fully omitted from **all** generated URLs, set the +config setting to `null`. +::: + + + +### `pageTrigger` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'p'` + +Defined by +: [GeneralConfig::$pageTrigger](craft3:craft\config\GeneralConfig::$pageTrigger) + +
+ +The string preceding a number which Craft will look for when determining if the current request is for a particular page in +a paginated list of pages. + +Example Value | Example URI +------------- | ----------- +`p` | `/news/p5` +`page` | `/news/page5` +`page/` | `/news/page/5` +`?page` | `/news?page=5` + +::: tip +If you want to set this to `?p` (e.g. `/news?p=5`), you’ll also need to change your setting which defaults to `p`. +If your server is running Apache, you’ll need to update the redirect code in your `.htaccess` file to match your new `pathParam` value. +::: + + + +### `pathParam` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `'p'` + +Defined by +: [GeneralConfig::$pathParam](craft3:craft\config\GeneralConfig::$pathParam) + +
+ +The query string param that Craft will check when determining the request’s path. + +This can be set to `null` if your web server is capable of directing traffic to `index.php` without a query string param. +If you’re using Apache, that means you’ll need to change the `RewriteRule` line in your `.htaccess` file to: + +``` +RewriteRule (.+) index.php [QSA,L] +``` + + + +### `postCpLoginRedirect` + +
+ +Allowed types +: `mixed` + +Default value +: `'dashboard'` + +Defined by +: [GeneralConfig::$postCpLoginRedirect](craft3:craft\config\GeneralConfig::$postCpLoginRedirect) + +
+ +The path users should be redirected to after logging into the control panel. + +This setting will also come into effect if a user visits the control panel’s login page (`/admin/login`) or the control panel’s +root URL (`/admin`) when they are already logged in. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `postLoginRedirect` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$postLoginRedirect](craft3:craft\config\GeneralConfig::$postLoginRedirect) + +
+ +The path users should be redirected to after logging in from the front-end site. + +This setting will also come into effect if the user visits the login page (as specified by the config setting) when +they are already logged in. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `postLogoutRedirect` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$postLogoutRedirect](craft3:craft\config\GeneralConfig::$postLogoutRedirect) + +
+ +The path that users should be redirected to after logging out from the front-end site. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `setPasswordPath` + +
+ +Allowed types +: `mixed` + +Default value +: `'setpassword'` + +Defined by +: [GeneralConfig::$setPasswordPath](craft3:craft\config\GeneralConfig::$setPasswordPath) + +
+ +The URI or URL that Craft should use for Set Password forms on the front end. + +Note that this config setting is ignored when is enabled, unless it’s set to an absolute URL. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: tip +You might also want to set in case a user clicks on an expired password reset link. +::: + + + +### `setPasswordRequestPath` + +
+ +Allowed types +: `mixed` + +Default value +: `null` + +Defined by +: [GeneralConfig::$setPasswordRequestPath](craft3:craft\config\GeneralConfig::$setPasswordRequestPath) + +Since +: 3.5.14 + +
+ +The URI to the page where users can request to change their password. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +If this is set, Craft will redirect [.well-known/change-password requests](https://w3c.github.io/webappsec-change-password-url/) to this URI. + +::: tip +You’ll also need to set [setPasswordPath](config3:setPasswordPath), which determines the URI and template path for the Set Password form +where the user resets their password after following the link in the Password Reset email. +::: + + + +### `setPasswordSuccessPath` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$setPasswordSuccessPath](craft3:craft\config\GeneralConfig::$setPasswordSuccessPath) + +
+ +The URI Craft should redirect users to after setting their password from the front end. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `siteToken` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'siteToken'` + +Defined by +: [GeneralConfig::$siteToken](craft3:craft\config\GeneralConfig::$siteToken) + +Since +: 3.5.0 + +
+ +The query string parameter name that site tokens should be set to. + + + +### `tokenParam` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'token'` + +Defined by +: [GeneralConfig::$tokenParam](craft3:craft\config\GeneralConfig::$tokenParam) + +
+ +The query string parameter name that Craft tokens should be set to. + + + +### `usePathInfo` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$usePathInfo](craft3:craft\config\GeneralConfig::$usePathInfo) + +
+ +Whether Craft should specify the path using `PATH_INFO` or as a query string parameter when generating URLs. + +Note that this setting only takes effect if is set to `false`. + + + +### `useSslOnTokenizedUrls` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean), [string](https://php.net/language.types.string) + +Default value +: `'auto'` + +Defined by +: [GeneralConfig::$useSslOnTokenizedUrls](craft3:craft\config\GeneralConfig::$useSslOnTokenizedUrls) + +
+ +Determines what protocol/schema Craft will use when generating tokenized URLs. If set to `'auto'`, Craft will check the +current site’s base URL and the protocol of the current request and if either of them are HTTPS will use `https` in the tokenized URL. If not, +will use `http`. + +If set to `false`, Craft will always use `http`. If set to `true`, then, Craft will always use `https`. + + + +### `verifyEmailPath` + +
+ +Allowed types +: `mixed` + +Default value +: `'verifyemail'` + +Defined by +: [GeneralConfig::$verifyEmailPath](craft3:craft\config\GeneralConfig::$verifyEmailPath) + +Since +: 3.4.0 + +
+ +The URI or URL that Craft should use for email verification links on the front end. + +Note that this config setting is ignored when is enabled, unless it’s set to an absolute URL. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +### `verifyEmailSuccessPath` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$verifyEmailSuccessPath](craft3:craft\config\GeneralConfig::$verifyEmailSuccessPath) + +Since +: 3.1.20 + +
+ +The URI that users without access to the control panel should be redirected to after verifying a new email address. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + + + +## Session + +### `phpSessionName` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'CraftSessionId'` + +Defined by +: [GeneralConfig::$phpSessionName](craft3:craft\config\GeneralConfig::$phpSessionName) + +
+ +The name of the PHP session cookie. + + + +### `rememberUsernameDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `31536000` (1 year) + +Defined by +: [GeneralConfig::$rememberUsernameDuration](craft3:craft\config\GeneralConfig::$rememberUsernameDuration) + +
+ +The amount of time Craft will remember a username and pre-populate it on the control panel’s Login page. + +Set to `0` to disable this feature altogether. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `rememberedUserSessionDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `1209600` (14 days) + +Defined by +: [GeneralConfig::$rememberedUserSessionDuration](craft3:craft\config\GeneralConfig::$rememberedUserSessionDuration) + +
+ +The amount of time a user stays logged if “Remember Me” is checked on the login page. + +Set to `0` to disable the “Remember Me” feature altogether. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `requireMatchingUserAgentForSession` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$requireMatchingUserAgentForSession](craft3:craft\config\GeneralConfig::$requireMatchingUserAgentForSession) + +
+ +Whether Craft should require a matching user agent string when restoring a user session from a cookie. + + + +### `requireUserAgentAndIpForSession` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$requireUserAgentAndIpForSession](craft3:craft\config\GeneralConfig::$requireUserAgentAndIpForSession) + +
+ +Whether Craft should require the existence of a user agent string and IP address when creating a new user session. + + + +### `userSessionDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `3600` (1 hour) + +Defined by +: [GeneralConfig::$userSessionDuration](craft3:craft\config\GeneralConfig::$userSessionDuration) + +
+ +The amount of time before a user will get logged out due to inactivity. + +Set to `0` if you want users to stay logged in as long as their browser is open rather than a predetermined amount of time. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +## Security + +### `blowfishHashCost` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `13` + +Defined by +: [GeneralConfig::$blowfishHashCost](craft3:craft\config\GeneralConfig::$blowfishHashCost) + +
+ +The higher the cost value, the longer it takes to generate a password hash and to verify against it. + +Therefore, higher cost slows down a brute-force attack. + +For best protection against brute force attacks, set it to the highest value that is tolerable on production servers. + +The time taken to compute the hash doubles for every increment by one for this value. + +For example, if the hash takes 1 second to compute when the value is 14 then the compute time varies as +2^(value - 14) seconds. + + + +### `cooldownDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `300` (5 minutes) + +Defined by +: [GeneralConfig::$cooldownDuration](craft3:craft\config\GeneralConfig::$cooldownDuration) + +
+ +The amount of time a user must wait before re-attempting to log in after their account is locked due to too many +failed login attempts. + +Set to `0` to keep the account locked indefinitely, requiring an admin to manually unlock the account. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `csrfTokenName` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'CRAFT_CSRF_TOKEN'` + +Defined by +: [GeneralConfig::$csrfTokenName](craft3:craft\config\GeneralConfig::$csrfTokenName) + +
+ +The name of CSRF token used for CSRF validation if is set to `true`. + + + +### `defaultTokenDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `86400` (1 day) + +Defined by +: [GeneralConfig::$defaultTokenDuration](craft3:craft\config\GeneralConfig::$defaultTokenDuration) + +
+ +The default amount of time tokens can be used before expiring. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `deferPublicRegistrationPassword` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$deferPublicRegistrationPassword](craft3:craft\config\GeneralConfig::$deferPublicRegistrationPassword) + +
+ +By default, Craft requires a front-end “password” field for public user registrations. Setting this to `true` +removes that requirement for the initial registration form. + +If you have email verification enabled, new users will set their password once they’ve followed the verification link in the email. +If you don’t, the only way they can set their password is to go through your “forgot password” workflow. + + + +### `elevatedSessionDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `300` (5 minutes) + +Defined by +: [GeneralConfig::$elevatedSessionDuration](craft3:craft\config\GeneralConfig::$elevatedSessionDuration) + +
+ +The amount of time a user’s elevated session will last, which is required for some sensitive actions (e.g. user group/permission assignment). + +Set to `0` to disable elevated session support. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `enableBasicHttpAuth` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$enableBasicHttpAuth](craft3:craft\config\GeneralConfig::$enableBasicHttpAuth) + +Since +: 3.5.0 + +
+ +Whether front-end web requests should support basic HTTP authentication. + + + +### `enableCsrfCookie` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableCsrfCookie](craft3:craft\config\GeneralConfig::$enableCsrfCookie) + +
+ +Whether to use a cookie to persist the CSRF token if is enabled. If false, the CSRF token will be +stored in session under the `csrfTokenName` config setting name. Note that while storing CSRF tokens in session increases security, +it requires starting a session for every page that a CSRF token is needed, which may degrade site performance. + + + +### `enableCsrfProtection` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableCsrfProtection](craft3:craft\config\GeneralConfig::$enableCsrfProtection) + +
+ +Whether to enable CSRF protection via hidden form inputs for all forms submitted via Craft. + + + +### `invalidLoginWindowDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `3600` (1 hour) + +Defined by +: [GeneralConfig::$invalidLoginWindowDuration](craft3:craft\config\GeneralConfig::$invalidLoginWindowDuration) + +
+ +The amount of time to track invalid login attempts for a user, for determining if Craft should lock an account. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `maxInvalidLogins` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `5` + +Defined by +: [GeneralConfig::$maxInvalidLogins](craft3:craft\config\GeneralConfig::$maxInvalidLogins) + +
+ +The number of invalid login attempts Craft will allow within the specified duration before the account gets locked. + + + +### `preventUserEnumeration` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$preventUserEnumeration](craft3:craft\config\GeneralConfig::$preventUserEnumeration) + +
+ +When `true`, Craft will always return a successful response in the “forgot password” flow, making it difficult to enumerate users. + +When set to `false` and you go through the “forgot password” flow from the control panel login page, you’ll get distinct messages indicating +whether the username/email exists and whether an email was sent with further instructions. This can be helpful for the user attempting to +log in but allow for username/email enumeration based on the response. + + + +### `previewTokenDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `null` (1 day) + +Defined by +: [GeneralConfig::$previewTokenDuration](craft3:craft\config\GeneralConfig::$previewTokenDuration) + +Since +: 3.7.0 + +
+ +The amount of time content preview tokens can be used before expiring. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `sanitizeCpImageUploads` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$sanitizeCpImageUploads](craft3:craft\config\GeneralConfig::$sanitizeCpImageUploads) + +Since +: 3.6.0 + +
+ +Whether images uploaded via the control panel should be sanitized. + + + +### `sanitizeSvgUploads` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$sanitizeSvgUploads](craft3:craft\config\GeneralConfig::$sanitizeSvgUploads) + +
+ +Whether Craft should sanitize uploaded SVG files and strip out potential malicious-looking content. + +This should definitely be enabled if you are accepting SVG uploads from untrusted sources. + + + +### `secureHeaders` + +
+ +Allowed types +: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$secureHeaders](craft3:craft\config\GeneralConfig::$secureHeaders) + +
+ +Lists of headers that are, by default, subject to the trusted host configuration. + +See [yii\web\Request::$secureHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureHeaders-detail) for more details. + +If not set, the default [yii\web\Request::$secureHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureHeaders-detail) value will be used. + + + +### `secureProtocolHeaders` + +
+ +Allowed types +: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$secureProtocolHeaders](craft3:craft\config\GeneralConfig::$secureProtocolHeaders) + +
+ +List of headers to check for determining whether the connection is made via HTTPS. + +See [yii\web\Request::$secureProtocolHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureProtocolHeaders-detail) for more details. + +If not set, the default [yii\web\Request::$secureProtocolHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureProtocolHeaders-detail) value will be used. + + + +### `securityKey` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `null` + +Defined by +: [GeneralConfig::$securityKey](craft3:craft\config\GeneralConfig::$securityKey) + +
+ +A private, random, cryptographically-secure key that is used for hashing and encrypting data in [craft\services\Security](craft3:craft\services\Security). + +This value should be the same across all environments. If this key ever changes, any data that was encrypted with it will be inaccessible. + + + +### `storeUserIps` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$storeUserIps](craft3:craft\config\GeneralConfig::$storeUserIps) + +Since +: 3.1.0 + +
+ +Whether user IP addresses should be stored/logged by the system. + + + +### `trustedHosts` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[ + 'any', +]` + +Defined by +: [GeneralConfig::$trustedHosts](craft3:craft\config\GeneralConfig::$trustedHosts) + +
+ +The configuration for trusted security-related headers. + +See [yii\web\Request::$trustedHosts](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$trustedHosts-detail) for more details. + +By default, all hosts are trusted. + + + +### `useSecureCookies` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean), [string](https://php.net/language.types.string) + +Default value +: `'auto'` + +Defined by +: [GeneralConfig::$useSecureCookies](craft3:craft\config\GeneralConfig::$useSecureCookies) + +
+ +Whether Craft will set the “secure” flag when saving cookies when using `Craft::cookieConfig()` to create a cookie. + +Valid values are `true`, `false`, and `'auto'`. Defaults to `'auto'`, which will set the secure flag if the page you’re currently accessing +is over `https://`. `true` will always set the flag, regardless of protocol and `false` will never automatically set the flag. + + + +### `verificationCodeDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `86400` (1 day) + +Defined by +: [GeneralConfig::$verificationCodeDuration](craft3:craft\config\GeneralConfig::$verificationCodeDuration) + +
+ +The amount of time a user verification code can be used before expiring. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +## Assets + +### `allowedFileExtensions` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[ + '7z', + 'aiff', + 'asc', + 'asf', + 'avi', + 'avif', + 'bmp', + 'cap', + 'cin', + 'csv', + 'dfxp', + 'doc', + 'docx', + 'dotm', + 'dotx', + 'fla', + 'flv', + 'gif', + 'gz', + 'gzip', + 'heic', + 'heif', + 'hevc', + 'itt', + 'jp2', + 'jpeg', + 'jpg', + 'jpx', + 'js', + 'json', + 'lrc', + 'm2t', + 'm4a', + 'm4v', + 'mcc', + 'mid', + 'mov', + 'mp3', + 'mp4', + 'mpc', + 'mpeg', + 'mpg', + 'mpsub', + 'ods', + 'odt', + 'ogg', + 'ogv', + 'pdf', + 'png', + 'potx', + 'pps', + 'ppsm', + 'ppsx', + 'ppt', + 'pptm', + 'pptx', + 'ppz', + 'pxd', + 'qt', + 'ram', + 'rar', + 'rm', + 'rmi', + 'rmvb', + 'rt', + 'rtf', + 'sami', + 'sbv', + 'scc', + 'sdc', + 'sitd', + 'smi', + 'srt', + 'stl', + 'sub', + 'svg', + 'swf', + 'sxc', + 'sxw', + 'tar', + 'tds', + 'tgz', + 'tif', + 'tiff', + 'ttml', + 'txt', + 'vob', + 'vsd', + 'vtt', + 'wav', + 'webm', + 'webp', + 'wma', + 'wmv', + 'xls', + 'xlsx', + 'zip', +]` + +Defined by +: [GeneralConfig::$allowedFileExtensions](craft3:craft\config\GeneralConfig::$allowedFileExtensions) + +
+ +The file extensions Craft should allow when a user is uploading files. + + + +### `convertFilenamesToAscii` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$convertFilenamesToAscii](craft3:craft\config\GeneralConfig::$convertFilenamesToAscii) + +
+ +Whether uploaded filenames with non-ASCII characters should be converted to ASCII (i.e. `ñ` → `n`). + +::: tip +You can run `php craft utils/ascii-filenames` in your terminal to apply ASCII filenames to all existing assets. +::: + + + +### `extraFileKinds` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$extraFileKinds](craft3:craft\config\GeneralConfig::$extraFileKinds) + +Since +: 3.0.37 + +
+ +List of additional file kinds Craft should support. This array will get merged with the one defined in +`\craft\helpers\Assets::_buildFileKinds()`. + +```php +'extraFileKinds' => [ + // merge .psb into list of Photoshop file kinds + 'photoshop' => [ + 'extensions' => ['psb'], + ], + // register new "Stylesheet" file kind + 'stylesheet' => [ + 'label' => 'Stylesheet', + 'extensions' => ['css', 'less', 'pcss', 'sass', 'scss', 'styl'], + ], +], +``` + +::: tip +File extensions listed here won’t immediately be allowed to be uploaded. You will also need to list them with +the config setting. +::: + + + +### `filenameWordSeparator` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [boolean](https://php.net/language.types.boolean) + +Default value +: `'-'` + +Defined by +: [GeneralConfig::$filenameWordSeparator](craft3:craft\config\GeneralConfig::$filenameWordSeparator) + +
+ +The string to use to separate words when uploading assets. If set to `false`, spaces will be left alone. + + + +### `maxUploadFileSize` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [string](https://php.net/language.types.string) + +Default value +: `16777216` (16MB) + +Defined by +: [GeneralConfig::$maxUploadFileSize](craft3:craft\config\GeneralConfig::$maxUploadFileSize) + +
+ +The maximum upload file size allowed. + +See [craft\helpers\ConfigHelper::sizeInBytes()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-sizeinbytes) for a list of supported value types. + + + +### `revAssetUrls` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$revAssetUrls](craft3:craft\config\GeneralConfig::$revAssetUrls) + +Since +: 3.7.0 + +
+ +Whether asset URLs should be revved so browsers don’t load cached versions when they’re modified. + + + +## Image Handling + +### `brokenImagePath` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$brokenImagePath](craft3:craft\config\GeneralConfig::$brokenImagePath) + +Since +: 3.5.0 + +
+ +The server path to an image file that should be sent when responding to an image request with a +404 status code. + +This can be set to an aliased path such as `@webroot/assets/404.svg`. + + + +### `defaultImageQuality` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `82` + +Defined by +: [GeneralConfig::$defaultImageQuality](craft3:craft\config\GeneralConfig::$defaultImageQuality) + +
+ +The quality level Craft will use when saving JPG and PNG files. Ranges from 1 (worst quality, smallest file) to +100 (best quality, biggest file). + + + +### `generateTransformsBeforePageLoad` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$generateTransformsBeforePageLoad](craft3:craft\config\GeneralConfig::$generateTransformsBeforePageLoad) + +
+ +Whether image transforms should be generated before page load. + + + +### `imageDriver` + +
+ +Allowed types +: `mixed` + +Default value +: `GeneralConfig::IMAGE_DRIVER_AUTO` + +Defined by +: [GeneralConfig::$imageDriver](craft3:craft\config\GeneralConfig::$imageDriver) + +
+ +The image driver Craft should use to cleanse and transform images. By default Craft will use ImageMagick if it’s installed +and otherwise fall back to GD. You can explicitly set either `'imagick'` or `'gd'` here to override that behavior. + + + +### `imageEditorRatios` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[ + 'Unconstrained' => 'none', + 'Original' => 'original', + 'Square' => 1, + '16:9' => 1.78, + '10:8' => 1.25, + '7:5' => 1.4, + '4:3' => 1.33, + '5:3' => 1.67, + '3:2' => 1.5, +]` + +Defined by +: [GeneralConfig::$imageEditorRatios](craft3:craft\config\GeneralConfig::$imageEditorRatios) + +
+ +An array containing the selectable image aspect ratios for the image editor. The array must be in the format +of `label` => `ratio`, where ratio must be a float or a string. For string values, only values of “none” and “original” are allowed. + + + +### `maxCachedCloudImageSize` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `2000` + +Defined by +: [GeneralConfig::$maxCachedCloudImageSize](craft3:craft\config\GeneralConfig::$maxCachedCloudImageSize) + +
+ +The maximum dimension size to use when caching images from external sources to use in transforms. Set to `0` to never cache them. + + + +### `optimizeImageFilesize` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$optimizeImageFilesize](craft3:craft\config\GeneralConfig::$optimizeImageFilesize) + +
+ +Whether Craft should optimize images for reduced file sizes without noticeably reducing image quality. (Only supported when +ImageMagick is used.) + + + +### `preserveCmykColorspace` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$preserveCmykColorspace](craft3:craft\config\GeneralConfig::$preserveCmykColorspace) + +Since +: 3.0.8 + +
+ +Whether CMYK should be preserved as the colorspace when manipulating images. + +Setting this to `true` will prevent Craft from transforming CMYK images to sRGB, but on some ImageMagick versions it can cause +image color distortion. This will only have an effect if ImageMagick is in use. + + + +### `preserveExifData` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$preserveExifData](craft3:craft\config\GeneralConfig::$preserveExifData) + +
+ +Whether the EXIF data should be preserved when manipulating and uploading images. + +Setting this to `true` will result in larger image file sizes. + +This will only have effect if ImageMagick is in use. + + + +### `preserveImageColorProfiles` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$preserveImageColorProfiles](craft3:craft\config\GeneralConfig::$preserveImageColorProfiles) + +
+ +Whether the embedded Image Color Profile (ICC) should be preserved when manipulating images. + +Setting this to `false` will reduce the image size a little bit, but on some ImageMagick versions can cause images to be saved with +an incorrect gamma value, which causes the images to become very dark. This will only have effect if ImageMagick is in use. + + + +### `rasterizeSvgThumbs` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$rasterizeSvgThumbs](craft3:craft\config\GeneralConfig::$rasterizeSvgThumbs) + +Since +: 3.6.0 + +
+ +Whether SVG thumbnails should be rasterized. + +Note this will only work if ImageMagick is installed, and is set to either `auto` or `imagick`. + + + +### `rotateImagesOnUploadByExifData` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$rotateImagesOnUploadByExifData](craft3:craft\config\GeneralConfig::$rotateImagesOnUploadByExifData) + +
+ +Whether Craft should rotate images according to their EXIF data on upload. + + + +### `transformGifs` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$transformGifs](craft3:craft\config\GeneralConfig::$transformGifs) + +Since +: 3.0.7 + +
+ +Whether GIF files should be cleansed/transformed. + + + +### `transformSvgs` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$transformSvgs](craft3:craft\config\GeneralConfig::$transformSvgs) + +Since +: 3.7.1 + +
+ +Whether SVG files should be transformed. + + + +### `upscaleImages` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$upscaleImages](craft3:craft\config\GeneralConfig::$upscaleImages) + +Since +: 3.4.0 + +
+ +Whether images should be upscaled if the provided transform size is larger than the image. + + + +## GraphQL + +### `allowedGraphqlOrigins` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [false](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$allowedGraphqlOrigins](craft3:craft\config\GeneralConfig::$allowedGraphqlOrigins) + +Since +: 3.5.0 + +
+ +The Ajax origins that should be allowed to access the GraphQL API, if enabled. + +If this is set to an array, then `graphql/api` requests will only include the current request’s [origin](https://www.yiiframework.com/doc/api/2.0/yii-web-request#getOrigin()-detail) +in the `Access-Control-Allow-Origin` response header if it’s listed here. + +If this is set to `false`, then the `Access-Control-Allow-Origin` response header will never be sent. + + + +### `disableGraphqlTransformDirective` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$disableGraphqlTransformDirective](craft3:craft\config\GeneralConfig::$disableGraphqlTransformDirective) + +Since +: 3.6.0 + +
+ +Whether the `transform` directive should be disabled for the GraphQL API. + + + +### `enableGql` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableGql](craft3:craft\config\GeneralConfig::$enableGql) + +Since +: 3.3.1 + +
+ +Whether the GraphQL API should be enabled. + +Note that the GraphQL API is only available for Craft Pro. + + + +### `enableGraphqlCaching` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableGraphqlCaching](craft3:craft\config\GeneralConfig::$enableGraphqlCaching) + +Since +: 3.3.12 + +
+ +Whether Craft should cache GraphQL queries. + +If set to `true`, Craft will cache the results for unique GraphQL queries per access token. The cache is automatically invalidated any time +an element is saved, the site structure is updated, or a GraphQL schema is saved. + +This setting will have no effect if a plugin is using the [craft\services\Gql::EVENT_BEFORE_EXECUTE_GQL_QUERY](https://docs.craftcms.com/api/v3/craft-services-gql.html#event-before-execute-gql-query) event to provide its own +caching logic and setting the `result` property. + + + +### `enableGraphqlIntrospection` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableGraphqlIntrospection](craft3:craft\config\GeneralConfig::$enableGraphqlIntrospection) + +Since +: 3.6.0 + +
+ +Whether GraphQL introspection queries are allowed. Defaults to `true` and is always allowed in the control panel. + + + +### `gqlTypePrefix` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [GeneralConfig::$gqlTypePrefix](craft3:craft\config\GeneralConfig::$gqlTypePrefix) + +
+ +Prefix to use for all type names returned by GraphQL. + + + +### `maxGraphqlComplexity` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `0` + +Defined by +: [GeneralConfig::$maxGraphqlComplexity](craft3:craft\config\GeneralConfig::$maxGraphqlComplexity) + +Since +: 3.6.0 + +
+ +The maximum allowed complexity a GraphQL query is allowed to have. Set to `0` to allow any complexity. + + + +### `maxGraphqlDepth` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `0` + +Defined by +: [GeneralConfig::$maxGraphqlDepth](craft3:craft\config\GeneralConfig::$maxGraphqlDepth) + +Since +: 3.6.0 + +
+ +The maximum allowed depth a GraphQL query is allowed to reach. Set to `0` to allow any depth. + + + +### `maxGraphqlResults` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `0` + +Defined by +: [GeneralConfig::$maxGraphqlResults](craft3:craft\config\GeneralConfig::$maxGraphqlResults) + +Since +: 3.6.0 + +
+ +The maximum allowed results for a single GraphQL query. Set to `0` to disable any limits. + + + +### `prefixGqlRootTypes` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$prefixGqlRootTypes](craft3:craft\config\GeneralConfig::$prefixGqlRootTypes) + +Since +: 3.6.6 + +
+ +Whether the config setting should have an impact on `query`, `mutation`, and `subscription` types. + + + +### `setGraphqlDatesToSystemTimeZone` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$setGraphqlDatesToSystemTimeZone](craft3:craft\config\GeneralConfig::$setGraphqlDatesToSystemTimeZone) + +Since +: 3.7.0 + +
+ +Whether dates returned by the GraphQL API should be set to the system time zone by default, rather than UTC. + + + +## Garbage Collection + +### `purgePendingUsersDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `0` + +Defined by +: [GeneralConfig::$purgePendingUsersDuration](craft3:craft\config\GeneralConfig::$purgePendingUsersDuration) + +
+ +The amount of time to wait before Craft purges pending users from the system that have not activated. + +Any content assigned to a pending user will be deleted as well when the given time interval passes. + +Set to `0` to disable this feature. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: tip +Users will only be purged when [garbage collection](https://craftcms.com/docs/3.x/gc.html) is run. +::: + + + +### `purgeStaleUserSessionDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `7776000` (90 days) + +Defined by +: [GeneralConfig::$purgeStaleUserSessionDuration](craft3:craft\config\GeneralConfig::$purgeStaleUserSessionDuration) + +Since +: 3.3.0 + +
+ +The amount of time to wait before Craft purges stale user sessions from the sessions table in the database. + +Set to `0` to disable this feature. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `purgeUnsavedDraftsDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `2592000` (30 days) + +Defined by +: [GeneralConfig::$purgeUnsavedDraftsDuration](craft3:craft\config\GeneralConfig::$purgeUnsavedDraftsDuration) + +Since +: 3.2.0 + +
+ +The amount of time to wait before Craft purges unpublished drafts that were never updated with content. + +Set to `0` to disable this feature. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + +### `softDeleteDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `2592000` (30 days) + +Defined by +: [GeneralConfig::$softDeleteDuration](craft3:craft\config\GeneralConfig::$softDeleteDuration) + +Since +: 3.1.0 + +
+ +The amount of time before a soft-deleted item will be up for hard-deletion by garbage collection. + +Set to `0` if you don’t ever want to delete soft-deleted items. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + + + + + diff --git a/docs/.artifacts/cms/3.x/console-commands.md b/docs/.artifacts/cms/3.x/console-commands.md new file mode 100644 index 000000000..7e662fea0 --- /dev/null +++ b/docs/.artifacts/cms/3.x/console-commands.md @@ -0,0 +1,2605 @@ + + + + +## `cache` + +Allows you to flush caches. + +

+ # + cache/flush +

+ + +Flushes given cache components. + +Example: + +```sh +# flushes caches by ID: “first”, “second”, “third” +php craft cache/flush first second third +``` + +

+ # + cache/flush-all +

+ + +Flushes all caches registered in the system. + +

+ # + cache/flush-schema +

+ + +Clears DB schema cache for a given connection component. + +```sh +php craft cache/flush-schema +# identical to `php craft cache/flush-schema db` +``` + +

Parameters

+ +componentId +: ID of the connection component. (Defaults to `db`.) + + + +

+ # + cache +

+ + +Lists the caches that can be flushed. + +## `clear-caches` + +Allows you to clear various Craft caches. + +

+ # + clear-caches/all +

+ + +Clear all caches. + +

+ # + clear-caches/asset +

+ + +Clears Asset caches. + +

+ # + clear-caches/asset-indexing-data +

+ + +Clears Asset indexing data. + +

+ # + clear-caches/compiled-classes +

+ + +Clears compiled classes. + +

+ # + clear-caches/compiled-templates +

+ + +Clears compiled templates. + +

+ # + clear-caches/cp-resources +

+ + +Clears control panel resources. + +

+ # + clear-caches/data +

+ + +Clears data caches. + +

+ # + clear-caches +

+ + +Lists the caches that can be cleared. + +

+ # + clear-caches/temp-files +

+ + +Clears temporary files. + +

+ # + clear-caches/transform-indexes +

+ + +Clears the Asset transform index. + +## `clear-deprecations` + + +

+ # + clear-deprecations +

+ + +Clears all deprecation warnings. + +## `db` + +Performs database operations. + +

+ # + db/backup +

+ + +Creates a new database backup. + +Example: +``` +php craft db/backup ./my-backups/ +``` + +

Parameters

+ +path +: The path the database backup should be created at. +Can be any of the following: + + - A full file path + - A folder path (backup will be saved in there with a dynamically-generated name) + - A filename (backup will be saved in the working directory with the given name) + - Blank (backup will be saved to the `storage/backups/` folder with a dynamically-generated name) + + + +

Options

+ + +--zip +: Whether the backup should be saved as a zip file. + + +--overwrite +: Whether to overwrite an existing backup file, if a specific file path is given. + + + +

+ # + db/convert-charset +

+ + +Converts tables’ character sets and collations. (MySQL only) + +Example: +``` +php craft db/convert-charset utf8 utf8_unicode_ci +``` + +

Parameters

+ +charset +: The target character set, which honors `DbConfig::$charset` + or defaults to `utf8`. + +collation +: The target collation, which honors `DbConfig::$collation` + or defaults to `utf8_unicode_ci`. + + + +

+ # + db/restore +

+ + +Restores a database backup. + +Example: +``` +php craft db/restore ./my-backup.sql +``` + +

Parameters

+ +path +: The path to the database backup file. + + + +## `fixture` + +Allows you to manage test fixtures. + +

+ # + fixture/load +

+ + +Loads the specified fixture data. + +Example: + +```sh +# load User fixture data (any existing fixture data will be removed first) +php craft fixture/load "User" + +# load all available fixtures found under 'tests\unit\fixtures' +php craft fixture/load "*" + +# load all fixtures except User +php craft fixture/load "*, -User" +``` + +

Parameters

+ +fixturesInput +: Array of fixtures to load. + + + +

Options

+ + +--global-fixtures, -g +: Array of global fixtures that should be applied when loading and unloading. Set to `InitDbFixture` by default, which disables and enables integrity check so your data can be safely loaded. + + +--namespace, -n +: Namespace to search for fixtures. Defaults to `tests\unit\fixtures`. + + + +

+ # + fixture/unload +

+ + +Unloads the specified fixtures. + +Example: + +```sh +# unload User fixture data +php craft fixture/load "User" + +# unload all fixtures found under 'tests\unit\fixtures' +php craft fixture/load "*" + +# unload all fixtures except User +php craft fixture/load "*, -User" +``` + +

Parameters

+ +fixturesInput +: Array of fixtures to unload. + + + +

Options

+ + +--global-fixtures, -g +: Array of global fixtures that should be applied when loading and unloading. Set to `InitDbFixture` by default, which disables and enables integrity check so your data can be safely loaded. + + +--namespace, -n +: Namespace to search for fixtures. Defaults to `tests\unit\fixtures`. + + + +## `gc` + + +

+ # + gc/run +

+ + +Runs garbage collection. + +

Options

+ + +--delete-all-trashed +: Whether all soft-deleted items should be deleted, rather than just +the ones that were deleted long enough ago to be ready for hard-deletion +per the `softDeleteDuration` config setting. + + +--empty-deprecated-tables +: Whether old database tables should be emptied out. + + + +## `graphql` + +Allows you to manage GraphQL schemas. + +

+ # + graphql/create-token +

+ + +Creates a new authorization token for a schema. + +

Parameters

+ +schemaUid +: The schema UUID + + + +

Options

+ + +--name +: The schema name + + +--expiry +: Expiry date + + + +

+ # + graphql/dump-schema +

+ + +Dumps a given GraphQL schema to a file. + +

Options

+ + +--schema +: The GraphQL schema UUID. + + +--token +: The token to look up to determine the appropriate GraphQL schema. + + +--full-schema +: Whether full schema should be printed or dumped. + + + +

+ # + graphql/list-schemas +

+ + +Lists all GraphQL schemas. + +

+ # + graphql/print-schema +

+ + +Prints a given GraphQL schema. + +

Options

+ + +--schema +: The GraphQL schema UUID. + + +--token +: The token to look up to determine the appropriate GraphQL schema. + + +--full-schema +: Whether full schema should be printed or dumped. + + + +## `help` + +Provides help information about console commands. + +

+ # + help +

+ + +Displays available commands or the detailed information +about a particular command. + +Example: + +``` +$ php craft help db/backup + +DESCRIPTION + +Creates a new database backup. + +Example: +php craft db/backup ./my-backups/ + + +USAGE + +craft db/backup [path] [...options...] + +- path: string + The path the database backup should be created at. + Can be any of the following: + + - A full file path + - A folder path (backup will be saved in there with a dynamically-generated name) + - A filename (backup will be saved in the working directory with the given name) + - Blank (backup will be saved to the `storage/backups/` folder with a dynamically-generated name) + + +OPTIONS + +--appconfig: string + custom application configuration file path. + If not set, default application configuration is used. + +--color: boolean, 0 or 1 + whether to enable ANSI color in the output. + If not set, ANSI color will only be enabled for terminals that support it. + +--help, -h: boolean, 0 or 1 (defaults to 0) + whether to display help information about current command. + +--interactive: boolean, 0 or 1 (defaults to 1) + whether to run the command interactively. + +--overwrite: boolean, 0 or 1 (defaults to 0) + Whether to overwrite an existing backup file, if a specific file path is given. + +--silent-exit-on-exception: boolean, 0 or 1 + if true - script finish with `ExitCode::OK` in case of exception. + false - `ExitCode::UNSPECIFIED_ERROR`. + Default: `YII_ENV_TEST` + +--zip: boolean, 0 or 1 (defaults to 0) + Whether the backup should be saved as a zip file. + +$ +``` + + +

Parameters

+ +command +: The name of the command to show help about. +If not provided, all available commands will be displayed. + + + +

Options

+ + +--as-json, -j +: Should the commands help be returned in JSON format? + + + +

+ # + help/list +

+ + +Lists all available controllers and actions in machine-readable format. + +

+ # + help/list-action-options +

+ + +List all available options for `action` in machine-readable format. + +

Parameters

+ +action +: Route to action. + + + +

+ # + help/usage +

+ + +Displays usage information for `action`. + +

Parameters

+ +action +: Route to action. + + + +## `index-assets` + +Allows you to re-index assets in volumes. + +

+ # + index-assets/all +

+ + +Re-indexes assets across all volumes. + +

Options

+ + +--cache-remote-images +: Whether remote-stored images should be locally cached in the process. + + +--create-missing-assets +: Whether to auto-create new asset records when missing. + + +--delete-missing-assets +: Whether to delete all the asset records that have their files missing. + + + +

+ # + index-assets/one +

+ + +Re-indexes assets from the given volume handle. + +

Parameters

+ +handle +: The handle of the volume to index. +You can optionally provide a volume sub-path, e.g. `php craft index-assets/one volume-handle/path/to/folder`. + +startAt +: Index of the asset to start with, which defaults to `0`. + + + +

Options

+ + +--cache-remote-images +: Whether remote-stored images should be locally cached in the process. + + +--create-missing-assets +: Whether to auto-create new asset records when missing. + + +--delete-missing-assets +: Whether to delete all the asset records that have their files missing. + + + +## `install` + +Craft CMS CLI installer. + +

+ # + install/check +

+ + +Checks whether Craft is already installed. + +

+ # + install/craft +

+ + +Runs the install migration. + +

Options

+ + +--email +: The default email address for the first user to create during install. + + +--username +: The default username for the first user to create during install. + + +--password +: The default password for the first user to create during install. + + +--site-name +: The default site name for the first site to create during install. + + +--site-url +: The default site URL for the first site to create during install. + + +--language +: The default langcode for the first site to create during install. + + + +## `invalidate-tags` + +Allows you to invalidate cache tags. + +

+ # + invalidate-tags/all +

+ + +Invalidates all cache tags. + +

+ # + invalidate-tags/graphql +

+ + +Invalidates all GraphQL query cache tags. + +

+ # + invalidate-tags +

+ + +Lists the cache tags that can be invalidated. + +

+ # + invalidate-tags/template +

+ + +Invalidates all template cache tags. + +## `mailer` + + +

+ # + mailer/test +

+ + +Tests sending an email with the current mailer settings. + +

Options

+ + +--to +: Email address that should receive the test message. + + + +## `migrate` + +Manages Craft and plugin migrations. + +

+ # + migrate/all +

+ + +Runs all pending Craft, plugin, and content migrations. + +

Options

+ + +--no-content +: Exclude pending content migrations. + + +--no-backup +: Skip backing up the database. + + + +

+ # + migrate/create +

+ + +Creates a new migration. + +This command creates a new migration using the available migration template. +After using this command, developers should modify the created migration +skeleton by filling up the actual migration logic. + +``` +craft migrate/create create_news_section +``` + +By default, the migration is created in the project’s `migrations/` +folder (as a “content migration”).\ +Use `--plugin=` to create a new plugin migration.\ +Use `--type=app` to create a new Craft CMS app migration. + +

Parameters

+ +name +: the name of the new migration. This should only contain +letters, digits, and underscores. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + +--template-file +: The template file for generating new migrations. This can be either a path alias (e.g. `@app/migrations/template.php`) or a file path. Defaults to `vendor/craftcms/cms/src/updates/migration.php.template`. + + + +

+ # + migrate/down +

+ + +Downgrades Craft by reverting old migrations. + +Example: + +```sh +php craft migrate/down # revert last migration +php craft migrate/down 3 # revert last three migrations +php craft migrate/down all # revert all migrations +``` + +

Parameters

+ +limit +: The number of migrations to be reverted. Defaults to `1`, meaning the last applied migration will be reverted. When value is `all`, all migrations will be reverted. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/history +

+ + +Shows the list of migrations that have been applied so far. + +Example: + +```sh +php craft migrate/history # displays the last ten migrations +php craft migrate/history 5 # displays the last five migrations +php craft migrate/history all # displays the entire migration history +``` + +

Parameters

+ +limit +: The maximum number of migrations to be displayed. (Defaults to `10`.) +If `all`, the whole migration history will be displayed. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/mark +

+ + +Modifies the migration history to the specified version. + +No actual migration will be performed. + +```sh +php craft migrate/mark 101129_185401 # using timestamp +php craft migrate/mark m101129_185401_create_user_table # using name +php craft migrate/mark app\migrations\M101129185401CreateUser # using namespace name +php craft migrate/mark m000000_000000_base # reset entire history +``` + +

Parameters

+ +version +: The version at which the migration history should be marked, which can be either the timestamp or the full name of the migration. + + Specify `m000000_000000_base` to set the migration history to a state where no migration has been applied. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/new +

+ + +Shows any new migrations that have not been applied. + +Example: + +```sh +php craft migrate/new # displays the first 10 new migrations +php craft migrate/new 5 # displays the first 5 new migrations +php craft migrate/new all # displays all new migrations +``` + +

Parameters

+ +limit +: The maximum number of new migrations to be displayed. (Defaults to `10`.) +If `all`, then every available new migration will be displayed. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/redo +

+ + +Reapplies previous migrations by first reverting them and then applying them again. + +Example: + +```sh +php craft migrate/redo # redo the last applied migration +php craft migrate/redo 3 # redo the last three applied migrations +php craft migrate/redo all # redo all migrations +``` + +

Parameters

+ +limit +: The number of migrations to be redone. Defaults to `1`, meaning the last applied migration will be redone. When `all`, every migration will be redone. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/to +

+ + +Upgrades or downgrades until the specified version. + +You can downgrade versions to a past apply time by providing a UNIX timestamp or a [strtotime()](https://www.php.net/manual/en/function.strtotime.php)-parseable value. All versions applied after that specified time will then be reverted. + +Example: + +```sh +php craft migrate/to 101129_185401 # migration timestamp +php craft migrate/to m101129_185401_create_user_table # full name +php craft migrate/to 1392853618 # UNIX timestamp +php craft migrate/to "2022-02-02 02:02:02" # strtotime()-parseable +php craft migrate/to app\migrations\M101129185401CreateUser # full namespace name +``` + +

Parameters

+ +version +: Either the version name or a past time value to be migrated to. This can be a timestamp, the full name of the migration, a UNIX timestamp, or a string value that can be parsed by [strotime()](https://www.php.net/manual/en/function.strtotime.php). + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/up +

+ + +Upgrades Craft by applying new migrations. + +Example: +``` +php craft migrate # apply all new migrations +php craft migrate 3 # apply the first 3 new migrations +``` + +

Parameters

+ +limit +: The number of new migrations to be applied. If `0`, every new migration +will be applied. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +## `off` + + +

+ # + off +

+ + +Disables `system.live` project config value—bypassing any `allowAdminChanges` config setting +restrictions—meant for temporary use during the deployment process. + +

Options

+ + +--retry +: Number of seconds the `Retry-After` HTTP header should be set to for 503 responses. + + The `retryDuration` config setting can be used to configure a *system-wide* `Retry-After` header. + + ::: warning + The `isSystemLive` config setting takes precedence over the `system.live` project config value, + so if `config/general.php` sets `isSystemLive` to `true` or `false` these `on`/`off` commands error out. + ::: + + **Example** + + Running the following takes the system offline and returns 503 responses until it’s switched on again: + + ``` + $ php craft off --retry=60 + The system is now offline. + The retry duration is now set to 60. + ``` + + + +## `on` + + +

+ # + on +

+ + +Turns the system on. + +Example: +``` +$ php craft on +The system is now online. +``` + +## `plugin` + +Manages plugins. + +

+ # + plugin/disable +

+ + +Disables a plugin. + +``` +$ php craft plugin/disable + +The following plugins are enabled: + + Handle Name Version + ------------- -------------- ------- + apple-news Apple News 2.0.1 + ckeditor CKEditor 1.3.0 + commerce Craft Commerce 3.4.11 + gatsby-helper Gatsby Helper 1.1.2 + +Choose a plugin handle to disable: ckeditor +*** disabling ckeditor +*** disabled ckeditor successfully (time: 0.003s) +``` + + +

Parameters

+ +handle +: The plugin handle. + + + +

+ # + plugin/enable +

+ + +Enables a plugin. + +``` +$ php craft plugin/enable + +The following plugins are disabled: + + Handle Name Version + ---------- ---------- ------- + apple-news Apple News 2.0.1 + ckeditor CKEditor 1.3.0 + +Choose a plugin handle to enable: ckeditor +*** enabling ckeditor +*** enabled ckeditor successfully (time: 0.004s) +``` + + +

Parameters

+ +handle +: The plugin handle. + + + +

+ # + plugin/install +

+ + +Installs a plugin. + +``` +$ php craft plugin/install + +The following uninstalled plugins are present: + + Handle Name Version + ------------- -------------- ------- + anchors Anchors 2.3.1 + apple-news Apple News 2.0.1 + ckeditor CKEditor 1.3.0 + commerce Craft Commerce 3.4.11 + gatsby-helper Gatsby Helper 1.1.2 + +Choose a plugin handle to install: ckeditor +*** installing ckeditor +*** installed ckeditor successfully (time: 0.496s) +``` + + +

Parameters

+ +handle +: The plugin handle. + + + +

+ # + plugin/list +

+ + +Lists all plugins. + +``` +$ php craft plugin/list + + Name Handle Package Name Version Installed Enabled + -------------- ------------- ---------------------- ------- --------- ------- + Anchors anchors craftcms/anchors 2.3.1 Yes Yes + Apple News apple-news craftcms/apple-news 2.0.1 Yes Yes + CKEditor ckeditor craftcms/ckeditor 1.3.0 Yes Yes + Craft Commerce commerce craftcms/commerce 3.4.11 Yes Yes + Gatsby Helper gatsby-helper craftcms/gatsby-helper 1.1.2 Yes Yes +``` + + +

+ # + plugin/uninstall +

+ + +Uninstalls a plugin. + +``` +$ php craft plugin/uninstall + +The following plugins plugins are installed and enabled: + + Handle Name Version + ------------- -------------- ------- + anchors Anchors 2.3.1 + apple-news Apple News 2.0.1 + ckeditor CKEditor 1.3.0 + commerce Craft Commerce 3.4.11 + gatsby-helper Gatsby Helper 1.1.2 + +Choose a plugin handle to uninstall: ckeditor +*** uninstalling ckeditor +*** uninstalled ckeditor successfully (time: 0.496s) +``` + + +

Parameters

+ +handle +: The plugin handle. + + + +

Options

+ + +--force +: Whether the plugin uninstallation should be forced. + + + +## `project-config` + +Manages the Project Config. + +

+ # + project-config/apply +

+ + +Applies project config file changes. + +

Options

+ + +--force +: Whether every entry change should be force-applied. + + + +

+ # + project-config/diff +

+ + +Prints a diff of the pending project config YAML changes. + +

Options

+ + +--invert +: Whether to treat the loaded project config as the source of truth, instead of the YAML files. + + + +

+ # + project-config/export +

+ + +Exports the entire project config to a single file. + +

Parameters

+ +path +: The path the project config should be exported to. +Can be any of the following: + + - A full file path + - A folder path (export will be saved in there with a dynamically-generated name) + - A filename (export will be saved in the working directory with the given name) + - Blank (export will be saved in the working directly with a dynamically-generated name) + + + +

Options

+ + +--external +: Whether to export the external project config data, from the `config/project/` folder + + +--overwrite +: Whether to overwrite an existing export file, if a specific file path is given. + + + +

+ # + project-config/rebuild +

+ + +Rebuilds the project config. + +

+ # + project-config/touch +

+ + +Updates the `dateModified` value in `config/project/project.yaml`, attempting to resolve a Git conflict for it. + +

+ # + project-config/write +

+ + +Writes out the currently-loaded project config as YAML files to the `config/project/` folder, discarding any pending YAML changes. + +## `queue` + +Manages the queue. + +

+ # + queue/exec +

+ + +Executes a job. +The command is internal, and used to isolate a job execution. Manual usage is not provided. + +

Parameters

+ +id +: of a message + +ttr +: time to reserve + +attempt +: number + +pid +: of a worker + + + +

Options

+ + +--verbose, -v +: verbose mode of a job execute. If enabled, execute result of each job +will be printed. + + + +

+ # + queue/info +

+ + +Info about queue status. + +

+ # + queue/listen +

+ + +Listens for new jobs added to the queue and runs them. + +

Parameters

+ +timeout +: The number of seconds to wait between cycles. + + + +

Options

+ + +--verbose, -v +: verbose mode of a job execute. If enabled, execute result of each job +will be printed. + + +--isolate +: isolate mode. It executes a job in a child process. + + +--php-binary +: path to php interpreter that uses to run child processes. +If it is undefined, PHP_BINARY will be used. + + + +

+ # + queue/release +

+ + +Releases job(s) from the queue. + +Example: + +``` +php craft queue/release all +``` + +

Parameters

+ +job +: The job ID to release. Pass `all` to release all jobs. + + + +

+ # + queue/retry +

+ + +Re-adds failed job(s) to the queue. + +

Parameters

+ +job +: The job ID that should be retried, or `all` to retry all failed jobs. + + + +

+ # + queue/run +

+ + +Runs all jobs in the queue. + +

Options

+ + +--verbose, -v +: verbose mode of a job execute. If enabled, execute result of each job +will be printed. + + +--isolate +: isolate mode. It executes a job in a child process. + + +--php-binary +: path to php interpreter that uses to run child processes. +If it is undefined, PHP_BINARY will be used. + + + +## `resave` + +Allows you to bulk-save elements. + +

+ # + resave/assets +

+ + +Re-saves assets. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to save elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--volume +: The volume handle(s) to save assets from. Can be set to multiple comma-separated volumes. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/categories +

+ + +Re-saves categories. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to save elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--group +: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/entries +

+ + +Re-saves entries. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--drafts +: Whether to resave element drafts. + + +--provisional-drafts +: Whether to resave provisional element drafts. + + +--revisions +: Whether to resave element revisions. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to save elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--section +: The section handle(s) to save entries from. Can be set to multiple comma-separated sections. + + +--type +: The type handle(s) of the elements to resave. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/matrix-blocks +

+ + +Re-saves Matrix blocks. + +You must supply the `--field` or `--element-id` argument for this to work properly. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to save elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--type +: The type handle(s) of the elements to resave. + + +--field +: The field handle to save Matrix blocks for. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/tags +

+ + +Re-saves tags. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to save elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--group +: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/users +

+ + +Re-saves users. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to save elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--group +: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +## `serve` + + +

+ # + serve +

+ + +Runs PHP built-in web server. + +

Parameters

+ +address +: address to serve on. Either "host" or "host:port". + + + +

Options

+ + +--docroot, -t +: path or [path alias](https://craftcms.com/docs/3.x/config/#aliases) of the directory to serve. + + +--port, -p +: port to serve on. + + +--router, -r +: path or [path alias](guide:concept-aliases) to router script. +See https://www.php.net/manual/en/features.commandline.webserver.php + + + +## `setup` + +Craft CMS setup installer. + +

+ # + setup/app-id +

+ + +Generates a new application ID and saves it in the `.env` file. + +

+ # + setup/db +

+ + +Alias for [setup/db-creds](#setup-db-creds). + +

Options

+ + +--driver +: The database driver to use. Either `'mysql'` for MySQL or `'pgsql'` for PostgreSQL. + + +--server +: The database server name or IP address. Usually `'localhost'` or `'127.0.0.1'`. + + +--port +: The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. + + +--user +: The database username to connect with. + + +--password +: The database password to connect with. + + +--database +: The name of the database to select. + + +--schema +: The schema that Postgres is configured to use by default (PostgreSQL only). + + +--table-prefix +: The table prefix to add to all database tables. This can +be no more than 5 characters, and must be all lowercase. + + + +

+ # + setup/db-cache-table +

+ + +Creates a database table for storing DB caches. + +

+ # + setup/db-creds +

+ + +Stores new DB connection settings to the `.env` file. + +

Options

+ + +--driver +: The database driver to use. Either `'mysql'` for MySQL or `'pgsql'` for PostgreSQL. + + +--server +: The database server name or IP address. Usually `'localhost'` or `'127.0.0.1'`. + + +--port +: The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. + + +--user +: The database username to connect with. + + +--password +: The database password to connect with. + + +--database +: The name of the database to select. + + +--schema +: The schema that Postgres is configured to use by default (PostgreSQL only). + + +--table-prefix +: The table prefix to add to all database tables. This can +be no more than 5 characters, and must be all lowercase. + + + +

+ # + setup +

+ + +Sets up all the things. + +

+ # + setup/php-session-table +

+ + +Creates a database table for storing PHP session information. + +

+ # + setup/security-key +

+ + +Generates a new security key and saves it in the `.env` file. + +

+ # + setup/welcome +

+ + +Called from the `post-create-project-cmd` Composer hook. + +## `shell` + + +

+ # + shell +

+ + +Runs an interactive shell. + +::: tip +This command requires the [`yiisoft/yii2-shell`](https://github.com/yiisoft/yii2-shell) package, which you may need to add to your project: + +``` +composer require --dev yiisoft/yii2-shell +``` +::: + +``` +$ php craft shell +Psy Shell v0.10.4 (PHP 7.4.3 — cli) by Justin Hileman +>>> help + help Show a list of commands. Type `help [foo]` for information about [foo]. Alias + ls List local, instance or class variables, methods and constants. Alias + dump Dump an object or primitive. + doc Read the documentation for an object, class, constant, method or property. Alias + show Show the code for an object, class, constant, method or property. + wtf Show the backtrace of the most recent exception. Alias + whereami Show where you are in the code. + throw-up Throw an exception or error out of the Psy Shell. + timeit Profiles with a timer. + trace Show the current call stack. + buffer Show (or clear) the contents of the code input buffer. Alias + clear Clear the Psy Shell screen. + edit Open an external editor. Afterwards, get produced code in input buffer. + sudo Evaluate PHP code, bypassing visibility restrictions. + history Show the Psy Shell history. Alias + exit End the current session and return to caller. Alias +``` + + +

Options

+ + +--include +: Include file(s) before starting tinker shell. + + + +## `tests` + + +

+ # + tests/setup +

+ + +Sets up a test suite for the current project. + +

Parameters

+ +dst +: The folder that the test suite should be generated in. + Defaults to the current working directory. + + + +## `up` + + +

+ # + up +

+ + +Runs pending migrations and applies pending project config changes. + +

Options

+ + +--force +: Whether to perform the action even if a mutex lock could not be acquired. + + + +## `update` + +Updates Craft and plugins. + +

+ # + update/composer-install +

+ + +Installs dependencies based on the current `composer.json` & `composer.lock`. + +

+ # + update/info +

+ + +Displays info about available updates. + +

+ # + update/update +

+ + +Updates Craft and/or plugins. + +

Parameters

+ +handle +: The update handle (`all`, `craft`, or a plugin handle). +You can pass multiple handles separated by spaces, and you can update to a specific +version using the syntax `:`. + + + +

Options

+ + +--force, -f +: Force the update if allowUpdates is disabled + + +--backup +: Backup the database before updating + + +--migrate +: Run new database migrations after completing the update + + + +## `users` + +Manages user accounts. + +

+ # + users/activation-url +

+ + +Generates an activation URL for a pending user. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

+ # + users/create +

+ + +Creates a user. + +

Options

+ + +--email +: The user’s email address. + + +--username +: The user’s username. + + +--password +: The user’s new password. + + +--admin +: Whether the user should be an admin. + + +--groups +: The group handles to assign the created user to. + + +--group-ids +: The group IDs to assign the user to the created user to. + + + +

+ # + users/delete +

+ + +Deletes a user. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

Options

+ + +--inheritor +: The email or username of the user to inherit content when deleting a user. + + +--delete-content +: Whether to delete the user’s content if no inheritor is specified. + + +--hard +: Whether the user should be hard-deleted immediately, instead of soft-deleted. + + + +

+ # + users/impersonate +

+ + +Generates a URL to impersonate a user. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

+ # + users/list-admins +

+ + +Lists admin users. + +

+ # + users/logout-all +

+ + +Logs all users out of the system. + +

+ # + users/password-reset-url +

+ + +Generates a password reset URL for a user. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

+ # + users/set-password +

+ + +Changes a user’s password. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

Options

+ + +--password +: The user’s new password. + + + +

+ # + users/unlock +

+ + +Unlocks a user's account. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +## `utils/ascii-filenames` + + +

+ # + utils/ascii-filenames +

+ + +Converts all non-ASCII asset filenames to ASCII. + +## `utils/fix-element-uids` + + +

+ # + utils/fix-element-uids +

+ + +Ensures all elements UIDs are unique. + +## `utils/prune-provisional-drafts` + + +

+ # + utils/prune-provisional-drafts +

+ + +Prunes provisional drafts for elements that have more than one per user. + +

Options

+ + +--dry-run +: Whether this is a dry run. + + + +## `utils/prune-revisions` + + +

+ # + utils/prune-revisions +

+ + +Prunes excess element revisions. + +

Options

+ + +--section +: The section handle(s) to prune revisions from. Can be set to multiple comma-separated sections. + + +--max-revisions +: The maximum number of revisions an element can have. + + +--dry-run +: Whether this is a dry run. + + + +## `utils/repair` + +Repairs data. + +

+ # + utils/repair/category-group-structure +

+ + +Repairs structure data for a category group. + +

Parameters

+ +handle +: The category group handle. + + + +

Options

+ + +--dry-run +: Whether to only do a dry run of the repair process. + + + +

+ # + utils/repair/project-config +

+ + +Repairs double-packed associative arrays in the project config. + +

Options

+ + +--dry-run +: Whether to only do a dry run of the repair process. + + + +

+ # + utils/repair/section-structure +

+ + +Repairs structure data for a section. + +

Parameters

+ +handle +: The section handle. + + + +

Options

+ + +--dry-run +: Whether to only do a dry run of the repair process. + + + +## `utils/update-usernames` + + +

+ # + utils/update-usernames +

+ + +Updates all users’ usernames to ensure they match their email address. + + diff --git a/docs/.artifacts/cms/3.x/entries.md b/docs/.artifacts/cms/3.x/entries.md new file mode 100644 index 000000000..15d63ed38 --- /dev/null +++ b/docs/.artifacts/cms/3.x/entries.md @@ -0,0 +1,1969 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [after](#after) | Narrows the query results to only entries that were posted on or after a certain date. +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [ancestorDist](#ancestordist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). +| [ancestorOf](#ancestorof) | Narrows the query results to only entries that are ancestors of another entry in its structure. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only entries that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. +| [asArray](#asarray) | Causes the query to return matching entries as arrays of data, rather than [Entry](craft3:craft\elements\Entry) objects. +| [authorGroup](#authorgroup) | Narrows the query results based on the user group the entries’ authors belong to. +| [authorGroupId](#authorgroupid) | Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. +| [authorId](#authorid) | Narrows the query results based on the entries’ authors. +| [before](#before) | Narrows the query results to only entries that were posted before a certain date. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#datecreated) | Narrows the query results based on the entries’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the entries’ last-updated dates. +| [descendantDist](#descendantdist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). +| [descendantOf](#descendantof) | Narrows the query results to only entries that are descendants of another entry in its structure. +| [draftCreator](#draftcreator) | Narrows the query results to only drafts created by a given user. +| [draftId](#draftid) | Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). +| [draftOf](#draftof) | Narrows the query results to only drafts of a given entry. +| [drafts](#drafts) | Narrows the query results to only drafts entries. +| [expiryDate](#expirydate) | Narrows the query results based on the entries’ expiry dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the entries have any descendants in their structure. +| [id](#id) | Narrows the query results based on the entries’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [leaves](#leaves) | Narrows the query results based on whether the entries are “leaves” (entries with no descendants). +| [level](#level) | Narrows the query results based on the entries’ level within the structure. +| [limit](#limit) | Determines the number of entries that should be returned. +| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the entry that comes immediately after another entry in its structure. +| [offset](#offset) | Determines how many entries should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`, or the order defined by the section if the [section](#section) or [sectionId](#sectionid) params are set to a single Structure section.) +| [positionedAfter](#positionedafter) | Narrows the query results to only entries that are positioned after another entry in its structure. +| [positionedBefore](#positionedbefore) | Narrows the query results to only entries that are positioned before another entry in its structure. +| [postDate](#postdate) | Narrows the query results based on the entries’ post dates. +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the entry that comes immediately before another entry in its structure. +| [provisionalDrafts](#provisionaldrafts) | Narrows the query results to only provisional drafts. +| [relatedTo](#relatedto) | Narrows the query results to only entries that are related to certain other elements. +| [revisionCreator](#revisioncreator) | Narrows the query results to only revisions created by a given user. +| [revisionId](#revisionid) | Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). +| [revisionOf](#revisionof) | Narrows the query results to only revisions of a given entry. +| [revisions](#revisions) | Narrows the query results to only revision entries. +| [savedDraftsOnly](#saveddraftsonly) | Narrows the query results to only unpublished drafts which have been saved after initial creation. +| [search](#search) | Narrows the query results to only entries that match a search query. +| [section](#section) | Narrows the query results based on the sections the entries belong to. +| [sectionId](#sectionid) | Narrows the query results based on the sections the entries belong to, per the sections’ IDs. +| [siblingOf](#siblingof) | Narrows the query results to only entries that are siblings of another entry in its structure. +| [site](#site) | Determines which site(s) the entries should be queried in. +| [siteId](#siteid) | Determines which site(s) the entries should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the entries’ IDs in the `elements_sites` table. +| [slug](#slug) | Narrows the query results based on the entries’ slugs. +| [status](#status) | Narrows the query results based on the entries’ statuses. +| [title](#title) | Narrows the query results based on the entries’ titles. +| [trashed](#trashed) | Narrows the query results to only entries that have been soft-deleted. +| [type](#type) | Narrows the query results based on the entries’ entry types. +| [typeId](#typeid) | Narrows the query results based on the entries’ entry types, per the types’ IDs. +| [uid](#uid) | Narrows the query results based on the entries’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uri](#uri) | Narrows the query results based on the entries’ URIs. +| [with](#with) | Causes the query to return matching entries eager-loaded with related elements. + + + + + +#### `after` + +Narrows the query results to only entries that were posted on or after a certain date. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'2018-04-01'` | that were posted after 2018-04-01. +| a [DateTime](https://php.net/class.datetime) object | that were posted after the date represented by the object. + + + +::: code +```twig +{# Fetch entries posted this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set entries = craft.entries() + .after(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch entries posted this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$entries = \craft\elements\Entry::find() + ->after($firstDayOfMonth) + ->all(); +``` +::: + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `ancestorDist` + +Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). + + + + + +::: code +```twig +{# Fetch entries above this one #} +{% set entries = craft.entries() + .ancestorOf(myEntry) + .ancestorDist(3) + .all() %} +``` + +```php +// Fetch entries above this one +$entries = \craft\elements\Entry::find() + ->ancestorOf($myEntry) + ->ancestorDist(3) + ->all(); +``` +::: + + +#### `ancestorOf` + +Narrows the query results to only entries that are ancestors of another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | above the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | above the entry represented by the object. + + + +::: code +```twig +{# Fetch entries above this one #} +{% set entries = craft.entries() + .ancestorOf(myEntry) + .all() %} +``` + +```php +// Fetch entries above this one +$entries = \craft\elements\Entry::find() + ->ancestorOf($myEntry) + ->all(); +``` +::: + + + +::: tip +This can be combined with [ancestorDist](#ancestordist) if you want to limit how far away the ancestor entries can be. +::: + + +#### `andRelatedTo` + +Narrows the query results to only entries that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all entries that are related to myCategoryA and myCategoryB #} +{% set entries = craft.entries() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all entries that are related to $myCategoryA and $myCategoryB +$entries = \craft\elements\Entry::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all entries, regardless of status #} +{% set entries = craft.entries() + .anyStatus() + .all() %} +``` + +```php +// Fetch all entries, regardless of status +$entries = \craft\elements\Entry::find() + ->anyStatus() + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching entries as arrays of data, rather than [Entry](craft3:craft\elements\Entry) objects. + + + + + +::: code +```twig +{# Fetch entries as arrays #} +{% set entries = craft.entries() + .asArray() + .all() %} +``` + +```php +// Fetch entries as arrays +$entries = \craft\elements\Entry::find() + ->asArray() + ->all(); +``` +::: + + +#### `authorGroup` + +Narrows the query results based on the user group the entries’ authors belong to. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | with an author in a group with a handle of `foo`. +| `'not foo'` | not with an author in a group with a handle of `foo`. +| `['foo', 'bar']` | with an author in a group with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not with an author in a group with a handle of `foo` or `bar`. +| a [UserGroup](craft3:craft\models\UserGroup) object | with an author in a group represented by the object. + + + +::: code +```twig +{# Fetch entries with an author in the Foo user group #} +{% set entries = craft.entries() + .authorGroup('foo') + .all() %} +``` + +```php +// Fetch entries with an author in the Foo user group +$entries = \craft\elements\Entry::find() + ->authorGroup('foo') + ->all(); +``` +::: + + +#### `authorGroupId` + +Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with an author in a group with an ID of 1. +| `'not 1'` | not with an author in a group with an ID of 1. +| `[1, 2]` | with an author in a group with an ID of 1 or 2. +| `['not', 1, 2]` | not with an author in a group with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch entries with an author in a group with an ID of 1 #} +{% set entries = craft.entries() + .authorGroupId(1) + .all() %} +``` + +```php +// Fetch entries with an author in a group with an ID of 1 +$entries = \craft\elements\Entry::find() + ->authorGroupId(1) + ->all(); +``` +::: + + +#### `authorId` + +Narrows the query results based on the entries’ authors. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with an author with an ID of 1. +| `'not 1'` | not with an author with an ID of 1. +| `[1, 2]` | with an author with an ID of 1 or 2. +| `['not', 1, 2]` | not with an author with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch entries with an author with an ID of 1 #} +{% set entries = craft.entries() + .authorId(1) + .all() %} +``` + +```php +// Fetch entries with an author with an ID of 1 +$entries = \craft\elements\Entry::find() + ->authorId(1) + ->all(); +``` +::: + + +#### `before` + +Narrows the query results to only entries that were posted before a certain date. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'2018-04-01'` | that were posted before 2018-04-01. +| a [DateTime](https://php.net/class.datetime) object | that were posted before the date represented by the object. + + + +::: code +```twig +{# Fetch entries posted before this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set entries = craft.entries() + .before(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch entries posted before this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$entries = \craft\elements\Entry::find() + ->before($firstDayOfMonth) + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `dateCreated` + +Narrows the query results based on the entries’ creation dates. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch entries created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set entries = craft.entries() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch entries created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$entries = \craft\elements\Entry::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the entries’ last-updated dates. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch entries updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set entries = craft.entries() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch entries updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$entries = \craft\elements\Entry::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `descendantDist` + +Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). + + + + + +::: code +```twig +{# Fetch entries below this one #} +{% set entries = craft.entries() + .descendantOf(myEntry) + .descendantDist(3) + .all() %} +``` + +```php +// Fetch entries below this one +$entries = \craft\elements\Entry::find() + ->descendantOf($myEntry) + ->descendantDist(3) + ->all(); +``` +::: + + +#### `descendantOf` + +Narrows the query results to only entries that are descendants of another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | below the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | below the entry represented by the object. + + + +::: code +```twig +{# Fetch entries below this one #} +{% set entries = craft.entries() + .descendantOf(myEntry) + .all() %} +``` + +```php +// Fetch entries below this one +$entries = \craft\elements\Entry::find() + ->descendantOf($myEntry) + ->all(); +``` +::: + + + +::: tip +This can be combined with [descendantDist](#descendantdist) if you want to limit how far away the descendant entries can be. +::: + + +#### `draftCreator` + +Narrows the query results to only drafts created by a given user. + + + +Possible values include: + +| Value | Fetches drafts… +| - | - +| `1` | created by the user with an ID of 1. +| a [craft\elements\User](craft3:craft\elements\User) object | created by the user represented by the object. + + + +::: code +```twig +{# Fetch drafts by the current user #} +{% set entries = craft.entries() + .draftCreator(currentUser) + .all() %} +``` + +```php +// Fetch drafts by the current user +$entries = \craft\elements\Entry::find() + ->draftCreator(Craft::$app->user->identity) + ->all(); +``` +::: + + +#### `draftId` + +Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). + + + +Possible values include: + +| Value | Fetches drafts… +| - | - +| `1` | for the draft with an ID of 1. + + + +::: code +```twig +{# Fetch a draft #} +{% set entries = craft.entries() + .draftId(10) + .all() %} +``` + +```php +// Fetch a draft +$entries = \craft\elements\Entry::find() + ->draftId(10) + ->all(); +``` +::: + + +#### `draftOf` + +Narrows the query results to only drafts of a given entry. + + + +Possible values include: + +| Value | Fetches drafts… +| - | - +| `1` | for the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | for the entry represented by the object. +| `'*'` | for any entry +| `false` | that aren’t associated with a published entry + + + +::: code +```twig +{# Fetch drafts of the entry #} +{% set entries = craft.entries() + .draftOf(myEntry) + .all() %} +``` + +```php +// Fetch drafts of the entry +$entries = \craft\elements\Entry::find() + ->draftOf($myEntry) + ->all(); +``` +::: + + +#### `drafts` + +Narrows the query results to only drafts entries. + + + + + +::: code +```twig +{# Fetch a draft entry #} +{% set entries = craft.entries() + .drafts() + .id(123) + .one() %} +``` + +```php +// Fetch a draft entry +$entries = \craft\elements\Entry::find() + ->drafts() + ->id(123) + ->one(); +``` +::: + + +#### `expiryDate` + +Narrows the query results based on the entries’ expiry dates. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `':empty:'` | that don’t have an expiry date. +| `':notempty:'` | that have an expiry date. +| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. +| `'< 2020-05-01'` | that will expire before 2020-05-01 +| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. + + + +::: code +```twig +{# Fetch entries expiring this month #} +{% set nextMonth = date('first day of next month')|atom %} + +{% set entries = craft.entries() + .expiryDate("< #{nextMonth}") + .all() %} +``` + +```php +// Fetch entries expiring this month +$nextMonth = (new \DateTime('first day of next month'))->format(\DateTime::ATOM); + +$entries = \craft\elements\Entry::find() + ->expiryDate("< {$nextMonth}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch entries in a specific order #} +{% set entries = craft.entries() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch entries in a specific order +$entries = \craft\elements\Entry::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `hasDescendants` + +Narrows the query results based on whether the entries have any descendants in their structure. + + + +(This has the opposite effect of calling [leaves](#leaves).) + + + +::: code +```twig +{# Fetch entries that have descendants #} +{% set entries = craft.entries() + .hasDescendants() + .all() %} +``` + +```php +// Fetch entries that have descendants +$entries = \craft\elements\Entry::find() + ->hasDescendants() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the entries’ IDs. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the entry by its ID #} +{% set entry = craft.entries() + .id(1) + .one() %} +``` + +```php +// Fetch the entry by its ID +$entry = \craft\elements\Entry::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch entries in reverse #} +{% set entries = craft.entries() + .inReverse() + .all() %} +``` + +```php +// Fetch entries in reverse +$entries = \craft\elements\Entry::find() + ->inReverse() + ->all(); +``` +::: + + +#### `leaves` + +Narrows the query results based on whether the entries are “leaves” (entries with no descendants). + + + +(This has the opposite effect of calling [hasDescendants](#hasdescendants).) + + + +::: code +```twig +{# Fetch entries that have no descendants #} +{% set entries = craft.entries() + .leaves() + .all() %} +``` + +```php +// Fetch entries that have no descendants +$entries = \craft\elements\Entry::find() + ->leaves() + ->all(); +``` +::: + + +#### `level` + +Narrows the query results based on the entries’ level within the structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with a level of 1. +| `'not 1'` | not with a level of 1. +| `'>= 3'` | with a level greater than or equal to 3. +| `[1, 2]` | with a level of 1 or 2 +| `['not', 1, 2]` | not with level of 1 or 2. + + + +::: code +```twig +{# Fetch entries positioned at level 3 or above #} +{% set entries = craft.entries() + .level('>= 3') + .all() %} +``` + +```php +// Fetch entries positioned at level 3 or above +$entries = \craft\elements\Entry::find() + ->level('>= 3') + ->all(); +``` +::: + + +#### `limit` + +Determines the number of entries that should be returned. + + + +::: code +```twig +{# Fetch up to 10 entries #} +{% set entries = craft.entries() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 entries +$entries = \craft\elements\Entry::find() + ->limit(10) + ->all(); +``` +::: + + +#### `nextSiblingOf` + +Narrows the query results to only the entry that comes immediately after another entry in its structure. + + + +Possible values include: + +| Value | Fetches the entry… +| - | - +| `1` | after the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | after the entry represented by the object. + + + +::: code +```twig +{# Fetch the next entry #} +{% set entry = craft.entries() + .nextSiblingOf(myEntry) + .one() %} +``` + +```php +// Fetch the next entry +$entry = \craft\elements\Entry::find() + ->nextSiblingOf($myEntry) + ->one(); +``` +::: + + +#### `offset` + +Determines how many entries should be skipped in the results. + + + +::: code +```twig +{# Fetch all entries except for the first 3 #} +{% set entries = craft.entries() + .offset(3) + .all() %} +``` + +```php +// Fetch all entries except for the first 3 +$entries = \craft\elements\Entry::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`, or the order defined by the section if the [section](#section) or [sectionId](#sectionid) params are set to a single Structure section.) + + + +::: code +```twig +{# Fetch all entries in order of date created #} +{% set entries = craft.entries() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all entries in order of date created +$entries = \craft\elements\Entry::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `positionedAfter` + +Narrows the query results to only entries that are positioned after another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | after the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | after the entry represented by the object. + + + +::: code +```twig +{# Fetch entries after this one #} +{% set entries = craft.entries() + .positionedAfter(myEntry) + .all() %} +``` + +```php +// Fetch entries after this one +$entries = \craft\elements\Entry::find() + ->positionedAfter($myEntry) + ->all(); +``` +::: + + +#### `positionedBefore` + +Narrows the query results to only entries that are positioned before another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | before the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | before the entry represented by the object. + + + +::: code +```twig +{# Fetch entries before this one #} +{% set entries = craft.entries() + .positionedBefore(myEntry) + .all() %} +``` + +```php +// Fetch entries before this one +$entries = \craft\elements\Entry::find() + ->positionedBefore($myEntry) + ->all(); +``` +::: + + +#### `postDate` + +Narrows the query results based on the entries’ post dates. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. +| `'< 2018-05-01'` | that were posted before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch entries posted last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set entries = craft.entries() + .postDate(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch entries posted last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$entries = \craft\elements\Entry::find() + ->postDate(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique entries from Site A, or Site B if they don’t exist in Site A #} +{% set entries = craft.entries() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique entries from Site A, or Site B if they don’t exist in Site A +$entries = \craft\elements\Entry::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prevSiblingOf` + +Narrows the query results to only the entry that comes immediately before another entry in its structure. + + + +Possible values include: + +| Value | Fetches the entry… +| - | - +| `1` | before the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | before the entry represented by the object. + + + +::: code +```twig +{# Fetch the previous entry #} +{% set entry = craft.entries() + .prevSiblingOf(myEntry) + .one() %} +``` + +```php +// Fetch the previous entry +$entry = \craft\elements\Entry::find() + ->prevSiblingOf($myEntry) + ->one(); +``` +::: + + +#### `provisionalDrafts` + +Narrows the query results to only provisional drafts. + + + + + +::: code +```twig +{# Fetch provisional drafts created by the current user #} +{% set entries = craft.entries() + .provisionalDrafts() + .draftCreator(currentUser) + .all() %} +``` + +```php +// Fetch provisional drafts created by the current user +$entries = \craft\elements\Entry::find() + ->provisionalDrafts() + ->draftCreator(Craft::$app->user->identity) + ->all(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only entries that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all entries that are related to myCategory #} +{% set entries = craft.entries() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all entries that are related to $myCategory +$entries = \craft\elements\Entry::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `revisionCreator` + +Narrows the query results to only revisions created by a given user. + + + +Possible values include: + +| Value | Fetches revisions… +| - | - +| `1` | created by the user with an ID of 1. +| a [craft\elements\User](craft3:craft\elements\User) object | created by the user represented by the object. + + + +::: code +```twig +{# Fetch revisions by the current user #} +{% set entries = craft.entries() + .revisionCreator(currentUser) + .all() %} +``` + +```php +// Fetch revisions by the current user +$entries = \craft\elements\Entry::find() + ->revisionCreator(Craft::$app->user->identity) + ->all(); +``` +::: + + +#### `revisionId` + +Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). + + + +Possible values include: + +| Value | Fetches revisions… +| - | - +| `1` | for the revision with an ID of 1. + + + +::: code +```twig +{# Fetch a revision #} +{% set entries = craft.entries() + .revisionId(10) + .all() %} +``` + +```php +// Fetch a revision +$entries = \craft\elements\Entry::find() + ->revisionIf(10) + ->all(); +``` +::: + + +#### `revisionOf` + +Narrows the query results to only revisions of a given entry. + + + +Possible values include: + +| Value | Fetches revisions… +| - | - +| `1` | for the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | for the entry represented by the object. + + + +::: code +```twig +{# Fetch revisions of the entry #} +{% set entries = craft.entries() + .revisionOf(myEntry) + .all() %} +``` + +```php +// Fetch revisions of the entry +$entries = \craft\elements\Entry::find() + ->revisionOf($myEntry) + ->all(); +``` +::: + + +#### `revisions` + +Narrows the query results to only revision entries. + + + + + +::: code +```twig +{# Fetch a revision entry #} +{% set entries = craft.entries() + .revisions() + .id(123) + .one() %} +``` + +```php +// Fetch a revision entry +$entries = \craft\elements\Entry::find() + ->revisions() + ->id(123) + ->one(); +``` +::: + + +#### `savedDraftsOnly` + +Narrows the query results to only unpublished drafts which have been saved after initial creation. + + + + + +::: code +```twig +{# Fetch saved, unpublished draft entries #} +{% set entries = craft.entries() + .draftOf(false) + .savedDraftsOnly() + .all() %} +``` + +```php +// Fetch saved, unpublished draft entries +$entries = \craft\elements\Entry::find() + ->draftOf(false) + ->savedDraftsOnly() + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only entries that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all entries that match the search query #} +{% set entries = craft.entries() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all entries that match the search query +$entries = \craft\elements\Entry::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `section` + +Narrows the query results based on the sections the entries belong to. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | in a section with a handle of `foo`. +| `'not foo'` | not in a section with a handle of `foo`. +| `['foo', 'bar']` | in a section with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a section with a handle of `foo` or `bar`. +| a [Section](craft3:craft\models\Section) object | in a section represented by the object. + + + +::: code +```twig +{# Fetch entries in the Foo section #} +{% set entries = craft.entries() + .section('foo') + .all() %} +``` + +```php +// Fetch entries in the Foo section +$entries = \craft\elements\Entry::find() + ->section('foo') + ->all(); +``` +::: + + +#### `sectionId` + +Narrows the query results based on the sections the entries belong to, per the sections’ IDs. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | in a section with an ID of 1. +| `'not 1'` | not in a section with an ID of 1. +| `[1, 2]` | in a section with an ID of 1 or 2. +| `['not', 1, 2]` | not in a section with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch entries in the section with an ID of 1 #} +{% set entries = craft.entries() + .sectionId(1) + .all() %} +``` + +```php +// Fetch entries in the section with an ID of 1 +$entries = \craft\elements\Entry::find() + ->sectionId(1) + ->all(); +``` +::: + + +#### `siblingOf` + +Narrows the query results to only entries that are siblings of another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | beside the entry with an ID of 1. +| a [Entry](craft3:craft\elements\Entry) object | beside the entry represented by the object. + + + +::: code +```twig +{# Fetch entries beside this one #} +{% set entries = craft.entries() + .siblingOf(myEntry) + .all() %} +``` + +```php +// Fetch entries beside this one +$entries = \craft\elements\Entry::find() + ->siblingOf($myEntry) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the entries should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch entries from the Foo site #} +{% set entries = craft.entries() + .site('foo') + .all() %} +``` + +```php +// Fetch entries from the Foo site +$entries = \craft\elements\Entry::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the entries should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch entries from the site with an ID of 1 #} +{% set entries = craft.entries() + .siteId(1) + .all() %} +``` + +```php +// Fetch entries from the site with an ID of 1 +$entries = \craft\elements\Entry::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the entries’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the entry by its ID in the elements_sites table #} +{% set entry = craft.entries() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the entry by its ID in the elements_sites table +$entry = \craft\elements\Entry::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `slug` + +Narrows the query results based on the entries’ slugs. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | with a slug of `foo`. +| `'foo*'` | with a slug that begins with `foo`. +| `'*foo'` | with a slug that ends with `foo`. +| `'*foo*'` | with a slug that contains `foo`. +| `'not *foo*'` | with a slug that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested entry slug from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the entry with that slug #} +{% set entry = craft.entries() + .slug(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested entry slug from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the entry with that slug +$entry = \craft\elements\Entry::find() + ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the entries’ statuses. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'live'` _(default)_ | that are live. +| `'pending'` | that are pending (enabled with a Post Date in the future). +| `'expired'` | that are expired (enabled with an Expiry Date in the past). +| `'disabled'` | that are disabled. +| `['live', 'pending']` | that are live or pending. +| `['not', 'live', 'pending']` | that are not live or pending. + + + +::: code +```twig +{# Fetch disabled entries #} +{% set entries = craft.entries() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled entries +$entries = \craft\elements\Entry::find() + ->status('disabled') + ->all(); +``` +::: + + +#### `title` + +Narrows the query results based on the entries’ titles. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch entries with a title that contains "Foo" #} +{% set entries = craft.entries() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch entries with a title that contains "Foo" +$entries = \craft\elements\Entry::find() + ->title('*Foo*') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only entries that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed entries #} +{% set entries = craft.entries() + .trashed() + .all() %} +``` + +```php +// Fetch trashed entries +$entries = \craft\elements\Entry::find() + ->trashed() + ->all(); +``` +::: + + +#### `type` + +Narrows the query results based on the entries’ entry types. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | of a type with a handle of `foo`. +| `'not foo'` | not of a type with a handle of `foo`. +| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. +| an [EntryType](craft3:craft\models\EntryType) object | of a type represented by the object. + + + +::: code +```twig +{# Fetch entries in the Foo section with a Bar entry type #} +{% set entries = craft.entries() + .section('foo') + .type('bar') + .all() %} +``` + +```php +// Fetch entries in the Foo section with a Bar entry type +$entries = \craft\elements\Entry::find() + ->section('foo') + ->type('bar') + ->all(); +``` +::: + + +#### `typeId` + +Narrows the query results based on the entries’ entry types, per the types’ IDs. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | of a type with an ID of 1. +| `'not 1'` | not of a type with an ID of 1. +| `[1, 2]` | of a type with an ID of 1 or 2. +| `['not', 1, 2]` | not of a type with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch entries of the entry type with an ID of 1 #} +{% set entries = craft.entries() + .typeId(1) + .all() %} +``` + +```php +// Fetch entries of the entry type with an ID of 1 +$entries = \craft\elements\Entry::find() + ->typeId(1) + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the entries’ UIDs. + + + + + +::: code +```twig +{# Fetch the entry by its UID #} +{% set entry = craft.entries() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the entry by its UID +$entry = \craft\elements\Entry::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique entries across all sites #} +{% set entries = craft.entries() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique entries across all sites +$entries = \craft\elements\Entry::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `uri` + +Narrows the query results based on the entries’ URIs. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the entry with that URI #} +{% set entry = craft.entries() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the entry with that URI +$entry = \craft\elements\Entry::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching entries eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch entries eager-loaded with the "Related" field’s relations #} +{% set entries = craft.entries() + .with(['related']) + .all() %} +``` + +```php +// Fetch entries eager-loaded with the "Related" field’s relations +$entries = \craft\elements\Entry::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/3.x/event-data/events.json b/docs/.artifacts/cms/3.x/events.json similarity index 99% rename from docs/3.x/event-data/events.json rename to docs/.artifacts/cms/3.x/events.json index ee009bf5d..69a8c63b8 100644 --- a/docs/3.x/event-data/events.json +++ b/docs/.artifacts/cms/3.x/events.json @@ -2588,6 +2588,12 @@ "type": "craft\\events\\ExceptionEvent", "desc": "The event that is triggered before handling an exception." }, + { + "class": "craft\\console\\ErrorHandler", + "name": "EVENT_SHUTDOWN", + "type": "yii\\base\\Event", + "desc": "an event that is triggered when the handler is called by shutdown function via `handleFatalError()`." + }, { "class": "craft\\console\\controllers\\BackupController", "name": "EVENT_DEFINE_ACTIONS", @@ -17180,6 +17186,54 @@ "type": "yii\\base\\Event", "desc": "an event raised at the end of `validate()`" }, + { + "class": "craft\\elements\\actions\\MoveAssets", + "name": "EVENT_DEFINE_SETTINGS_ATTRIBUTES", + "type": "craft\\events\\DefineValueEvent", + "desc": "The event that is triggered when defining the component’s settings attributes, as returned by `settingsAttributes()`." + }, + { + "class": "craft\\elements\\actions\\MoveAssets", + "name": "EVENT_INIT", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the model's init cycle" + }, + { + "class": "craft\\elements\\actions\\MoveAssets", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, + { + "class": "craft\\elements\\actions\\MoveAssets", + "name": "EVENT_DEFINE_RULES", + "type": "craft\\events\\DefineRulesEvent", + "desc": "The event that is triggered when defining the model rules" + }, + { + "class": "craft\\elements\\actions\\MoveAssets", + "name": "EVENT_DEFINE_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the arrayable fields" + }, + { + "class": "craft\\elements\\actions\\MoveAssets", + "name": "EVENT_DEFINE_EXTRA_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the extra arrayable fields" + }, + { + "class": "craft\\elements\\actions\\MoveAssets", + "name": "EVENT_BEFORE_VALIDATE", + "type": "yii\\base\\ModelEvent", + "desc": "an event raised at the beginning of `validate()`. You may set `ModelEvent::isValid` to be false to stop the validation." + }, + { + "class": "craft\\elements\\actions\\MoveAssets", + "name": "EVENT_AFTER_VALIDATE", + "type": "yii\\base\\Event", + "desc": "an event raised at the end of `validate()`" + }, { "class": "craft\\elements\\actions\\NewChild", "name": "EVENT_DEFINE_SETTINGS_ATTRIBUTES", @@ -17711,13 +17765,13 @@ { "class": "craft\\elements\\db\\AssetQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\elements\\db\\AssetQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -17741,13 +17795,13 @@ { "class": "craft\\elements\\db\\CategoryQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\elements\\db\\CategoryQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -17771,13 +17825,13 @@ { "class": "craft\\elements\\db\\ElementQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\elements\\db\\ElementQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -17801,13 +17855,13 @@ { "class": "craft\\elements\\db\\EntryQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\elements\\db\\EntryQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -17831,13 +17885,13 @@ { "class": "craft\\elements\\db\\GlobalSetQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\elements\\db\\GlobalSetQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -17861,13 +17915,13 @@ { "class": "craft\\elements\\db\\MatrixBlockQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\elements\\db\\MatrixBlockQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -17891,13 +17945,13 @@ { "class": "craft\\elements\\db\\TagQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\elements\\db\\TagQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -17921,13 +17975,13 @@ { "class": "craft\\elements\\db\\UserQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\elements\\db\\UserQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -19517,8 +19571,8 @@ { "class": "craft\\fields\\Matrix", "name": "EVENT_SET_FIELD_BLOCK_TYPES", - "type": "craft\\fields\\SectionEvent", - "desc": "The event that is triggered before a section is saved." + "type": "craft\\events\\BlockTypesEvent", + "desc": "The event that is triggered when setting the field’s block types" }, { "class": "craft\\fields\\Matrix", @@ -31195,7 +31249,7 @@ "class": "craft\\services\\AssetTransforms", "name": "EVENT_GENERATE_TRANSFORM", "type": "craft\\events\\GenerateTransformEvent", - "desc": "The event that is triggered when a transform is being generated for an Asset." + "desc": "The event that is triggered when a transform is being generated for an asset." }, { "class": "craft\\services\\AssetTransforms", @@ -31231,13 +31285,13 @@ "class": "craft\\services\\Assets", "name": "EVENT_GET_ASSET_URL", "type": "craft\\events\\GetAssetUrlEvent", - "desc": "The event that is triggered when a transform is being generated for an Asset." + "desc": "The event that is triggered when a transform is being generated for an asset." }, { "class": "craft\\services\\Assets", "name": "EVENT_GET_ASSET_THUMB_URL", "type": "craft\\events\\GetAssetThumbUrlEvent", - "desc": "The event that is triggered when a thumbnail is being generated for an Asset." + "desc": "The event that is triggered when a thumbnail is being generated for an asset." }, { "class": "craft\\services\\Assets", @@ -32142,25 +32196,25 @@ { "class": "craft\\services\\Revisions", "name": "EVENT_BEFORE_CREATE_REVISION", - "type": "craft\\services\\DraftEvent", + "type": "craft\\events\\RevisionEvent", "desc": "The event that is triggered before a revision is created." }, { "class": "craft\\services\\Revisions", "name": "EVENT_AFTER_CREATE_REVISION", - "type": "craft\\services\\DraftEvent", + "type": "craft\\events\\RevisionEvent", "desc": "The event that is triggered after a revision is created." }, { "class": "craft\\services\\Revisions", "name": "EVENT_BEFORE_REVERT_TO_REVISION", - "type": "craft\\services\\DraftEvent", + "type": "craft\\events\\RevisionEvent", "desc": "The event that is triggered before an element is reverted to a revision." }, { "class": "craft\\services\\Revisions", "name": "EVENT_AFTER_REVERT_TO_REVISION", - "type": "craft\\services\\DraftEvent", + "type": "craft\\events\\RevisionEvent", "desc": "The event that is triggered after an element is reverted to a revision." }, { @@ -32539,19 +32593,19 @@ "class": "craft\\services\\Volumes", "name": "EVENT_BEFORE_SAVE_VOLUME", "type": "craft\\events\\VolumeEvent", - "desc": "The event that is triggered before an Asset volume is saved." + "desc": "The event that is triggered before a volume is saved." }, { "class": "craft\\services\\Volumes", "name": "EVENT_AFTER_SAVE_VOLUME", "type": "craft\\events\\VolumeEvent", - "desc": "The event that is triggered after an Asset volume is saved." + "desc": "The event that is triggered after a volume is saved." }, { "class": "craft\\services\\Volumes", "name": "EVENT_BEFORE_DELETE_VOLUME", "type": "craft\\events\\VolumeEvent", - "desc": "The event that is triggered before an Asset volume is deleted." + "desc": "The event that is triggered before a volume is deleted." }, { "class": "craft\\services\\Volumes", @@ -32563,7 +32617,7 @@ "class": "craft\\services\\Volumes", "name": "EVENT_AFTER_DELETE_VOLUME", "type": "craft\\events\\VolumeEvent", - "desc": "The event that is triggered after a Asset volume is deleted." + "desc": "The event that is triggered after a volume is deleted." }, { "class": "craft\\utilities\\AssetIndexes", @@ -33411,6 +33465,12 @@ "type": "craft\\events\\ExceptionEvent", "desc": "The event that is triggered before handling an exception." }, + { + "class": "craft\\web\\ErrorHandler", + "name": "EVENT_SHUTDOWN", + "type": "yii\\base\\Event", + "desc": "an event that is triggered when the handler is called by shutdown function via `handleFatalError()`." + }, { "class": "craft\\web\\Response", "name": "EVENT_BEFORE_SEND", @@ -34221,6 +34281,12 @@ "type": "yii\\base\\Event", "desc": "an event raised at the end of `validate()`" }, + { + "class": "yii\\base\\ErrorHandler", + "name": "EVENT_SHUTDOWN", + "type": "yii\\base\\Event", + "desc": "an event that is triggered when the handler is called by shutdown function via `handleFatalError()`." + }, { "class": "yii\\base\\Model", "name": "EVENT_BEFORE_VALIDATE", diff --git a/docs/.artifacts/cms/3.x/globals.md b/docs/.artifacts/cms/3.x/globals.md new file mode 100644 index 000000000..4f8d692b8 --- /dev/null +++ b/docs/.artifacts/cms/3.x/globals.md @@ -0,0 +1,758 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only global sets that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. +| [asArray](#asarray) | Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](craft3:craft\elements\GlobalSet) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#datecreated) | Narrows the query results based on the global sets’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the global sets’ last-updated dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [handle](#handle) | Narrows the query results based on the global sets’ handles. +| [id](#id) | Narrows the query results based on the global sets’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [limit](#limit) | Determines the number of global sets that should be returned. +| [offset](#offset) | Determines how many global sets should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the global sets should be returned in. (If empty, defaults to `name ASC`.) +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [relatedTo](#relatedto) | Narrows the query results to only global sets that are related to certain other elements. +| [search](#search) | Narrows the query results to only global sets that match a search query. +| [site](#site) | Determines which site(s) the global sets should be queried in. +| [siteId](#siteid) | Determines which site(s) the global sets should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the global sets’ IDs in the `elements_sites` table. +| [trashed](#trashed) | Narrows the query results to only global sets that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the global sets’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [with](#with) | Causes the query to return matching global sets eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only global sets that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all global sets that are related to myCategoryA and myCategoryB #} +{% set globalSets = craft.globalSets() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all global sets that are related to $myCategoryA and $myCategoryB +$globalSets = \craft\elements\GlobalSet::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all global sets, regardless of status #} +{% set globalSets = craft.globalSets() + .anyStatus() + .all() %} +``` + +```php +// Fetch all global sets, regardless of status +$globalSets = \craft\elements\GlobalSet::find() + ->anyStatus() + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](craft3:craft\elements\GlobalSet) objects. + + + + + +::: code +```twig +{# Fetch global sets as arrays #} +{% set globalSets = craft.globalSets() + .asArray() + .all() %} +``` + +```php +// Fetch global sets as arrays +$globalSets = \craft\elements\GlobalSet::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `dateCreated` + +Narrows the query results based on the global sets’ creation dates. + + + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch global sets created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set globalSets = craft.globalSets() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch global sets created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$globalSets = \craft\elements\GlobalSet::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the global sets’ last-updated dates. + + + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch global sets updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set globalSets = craft.globalSets() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch global sets updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$globalSets = \craft\elements\GlobalSet::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch global sets in a specific order #} +{% set globalSets = craft.globalSets() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch global sets in a specific order +$globalSets = \craft\elements\GlobalSet::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `handle` + +Narrows the query results based on the global sets’ handles. + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `'foo'` | with a handle of `foo`. +| `'not foo'` | not with a handle of `foo`. +| `['foo', 'bar']` | with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not with a handle of `foo` or `bar`. + + + +::: code +```twig +{# Fetch the global set with a handle of 'foo' #} +{% set globalSet = craft.globalSets() + .handle('foo') + .one() %} +``` + +```php +// Fetch the global set with a handle of 'foo' +$globalSet = \craft\elements\GlobalSet::find() + ->handle('foo') + ->one(); +``` +::: + + +#### `id` + +Narrows the query results based on the global sets’ IDs. + + + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the global set by its ID #} +{% set globalSet = craft.globalSets() + .id(1) + .one() %} +``` + +```php +// Fetch the global set by its ID +$globalSet = \craft\elements\GlobalSet::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch global sets in reverse #} +{% set globalSets = craft.globalSets() + .inReverse() + .all() %} +``` + +```php +// Fetch global sets in reverse +$globalSets = \craft\elements\GlobalSet::find() + ->inReverse() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of global sets that should be returned. + + + +::: code +```twig +{# Fetch up to 10 global sets #} +{% set globalSets = craft.globalSets() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 global sets +$globalSets = \craft\elements\GlobalSet::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many global sets should be skipped in the results. + + + +::: code +```twig +{# Fetch all global sets except for the first 3 #} +{% set globalSets = craft.globalSets() + .offset(3) + .all() %} +``` + +```php +// Fetch all global sets except for the first 3 +$globalSets = \craft\elements\GlobalSet::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the global sets should be returned in. (If empty, defaults to `name ASC`.) + + + +::: code +```twig +{# Fetch all global sets in order of date created #} +{% set globalSets = craft.globalSets() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all global sets in order of date created +$globalSets = \craft\elements\GlobalSet::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique global sets from Site A, or Site B if they don’t exist in Site A #} +{% set globalSets = craft.globalSets() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique global sets from Site A, or Site B if they don’t exist in Site A +$globalSets = \craft\elements\GlobalSet::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only global sets that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all global sets that are related to myCategory #} +{% set globalSets = craft.globalSets() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all global sets that are related to $myCategory +$globalSets = \craft\elements\GlobalSet::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only global sets that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all global sets that match the search query #} +{% set globalSets = craft.globalSets() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all global sets that match the search query +$globalSets = \craft\elements\GlobalSet::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the global sets should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch global sets from the Foo site #} +{% set globalSets = craft.globalSets() + .site('foo') + .all() %} +``` + +```php +// Fetch global sets from the Foo site +$globalSets = \craft\elements\GlobalSet::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the global sets should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch global sets from the site with an ID of 1 #} +{% set globalSets = craft.globalSets() + .siteId(1) + .all() %} +``` + +```php +// Fetch global sets from the site with an ID of 1 +$globalSets = \craft\elements\GlobalSet::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the global sets’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the global set by its ID in the elements_sites table #} +{% set globalSet = craft.globalSets() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the global set by its ID in the elements_sites table +$globalSet = \craft\elements\GlobalSet::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `trashed` + +Narrows the query results to only global sets that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed global sets #} +{% set globalSets = craft.globalSets() + .trashed() + .all() %} +``` + +```php +// Fetch trashed global sets +$globalSets = \craft\elements\GlobalSet::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the global sets’ UIDs. + + + + + +::: code +```twig +{# Fetch the global set by its UID #} +{% set globalSet = craft.globalSets() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the global set by its UID +$globalSet = \craft\elements\GlobalSet::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique global sets across all sites #} +{% set globalSets = craft.globalSets() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique global sets across all sites +$globalSets = \craft\elements\GlobalSet::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `with` + +Causes the query to return matching global sets eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch global sets eager-loaded with the "Related" field’s relations #} +{% set globalSets = craft.globalSets() + .with(['related']) + .all() %} +``` + +```php +// Fetch global sets eager-loaded with the "Related" field’s relations +$globalSets = \craft\elements\GlobalSet::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/3.x/matrix-blocks.md b/docs/.artifacts/cms/3.x/matrix-blocks.md new file mode 100644 index 000000000..7cc013866 --- /dev/null +++ b/docs/.artifacts/cms/3.x/matrix-blocks.md @@ -0,0 +1,980 @@ + + + + + + + + +| Param | Description +| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [allowOwnerDrafts](#allowownerdrafts) | Narrows the query results based on whether the Matrix blocks’ owners are drafts. +| [allowOwnerRevisions](#allowownerrevisions) | Narrows the query results based on whether the Matrix blocks’ owners are revisions. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. +| [asArray](#asarray) | Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](craft3:craft\elements\MatrixBlock) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#datecreated) | Narrows the query results based on the Matrix blocks’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the Matrix blocks’ last-updated dates. +| [field](#field) | Narrows the query results based on the field the Matrix blocks belong to. +| [fieldId](#fieldid) | Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [id](#id) | Narrows the query results based on the Matrix blocks’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [limit](#limit) | Determines the number of Matrix blocks that should be returned. +| [offset](#offset) | Determines how many Matrix blocks should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) +| [owner](#owner) | Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. +| [ownerId](#ownerid) | Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [relatedTo](#relatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. +| [search](#search) | Narrows the query results to only Matrix blocks that match a search query. +| [site](#site) | Determines which site(s) the Matrix blocks should be queried in. +| [siteId](#siteid) | Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the Matrix blocks’ IDs in the `elements_sites` table. +| [status](#status) | Narrows the query results based on the Matrix blocks’ statuses. +| [trashed](#trashed) | Narrows the query results to only Matrix blocks that have been soft-deleted. +| [type](#type) | Narrows the query results based on the Matrix blocks’ block types. +| [typeId](#typeid) | Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. +| [uid](#uid) | Narrows the query results based on the Matrix blocks’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [with](#with) | Causes the query to return matching Matrix blocks eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `allowOwnerDrafts` + +Narrows the query results based on whether the Matrix blocks’ owners are drafts. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `true` | which can belong to a draft. +| `false` | which cannot belong to a draft. + + + + +#### `allowOwnerRevisions` + +Narrows the query results based on whether the Matrix blocks’ owners are revisions. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `true` | which can belong to a revision. +| `false` | which cannot belong to a revision. + + + + +#### `andRelatedTo` + +Narrows the query results to only Matrix blocks that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all Matrix blocks that are related to myCategoryA and myCategoryB #} +{% set MatrixBlocks = craft.matrixBlocks() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all Matrix blocks that are related to $myCategoryA and $myCategoryB +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all Matrix blocks, regardless of status #} +{% set MatrixBlocks = craft.matrixBlocks() + .anyStatus() + .all() %} +``` + +```php +// Fetch all Matrix blocks, regardless of status +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->anyStatus() + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](craft3:craft\elements\MatrixBlock) objects. + + + + + +::: code +```twig +{# Fetch Matrix blocks as arrays #} +{% set MatrixBlocks = craft.matrixBlocks() + .asArray() + .all() %} +``` + +```php +// Fetch Matrix blocks as arrays +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `dateCreated` + +Narrows the query results based on the Matrix blocks’ creation dates. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch Matrix blocks created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set MatrixBlocks = craft.matrixBlocks() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch Matrix blocks created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the Matrix blocks’ last-updated dates. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch Matrix blocks updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set MatrixBlocks = craft.matrixBlocks() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch Matrix blocks updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `field` + +Narrows the query results based on the field the Matrix blocks belong to. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'foo'` | in a field with a handle of `foo`. +| `'not foo'` | not in a field with a handle of `foo`. +| `['foo', 'bar']` | in a field with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a field with a handle of `foo` or `bar`. +| a [craft\fields\Matrix](craft3:craft\fields\Matrix) object | in a field represented by the object. + + + +::: code +```twig +{# Fetch Matrix blocks in the Foo field #} +{% set MatrixBlocks = craft.matrixBlocks() + .field('foo') + .all() %} +``` + +```php +// Fetch Matrix blocks in the Foo field +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->field('foo') + ->all(); +``` +::: + + +#### `fieldId` + +Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | in a field with an ID of 1. +| `'not 1'` | not in a field with an ID of 1. +| `[1, 2]` | in a field with an ID of 1 or 2. +| `['not', 1, 2]` | not in a field with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch Matrix blocks in the field with an ID of 1 #} +{% set MatrixBlocks = craft.matrixBlocks() + .fieldId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks in the field with an ID of 1 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->fieldId(1) + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch Matrix blocks in a specific order #} +{% set MatrixBlocks = craft.matrixBlocks() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch Matrix blocks in a specific order +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the Matrix blocks’ IDs. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the Matrix block by its ID #} +{% set MatrixBlock = craft.matrixBlocks() + .id(1) + .one() %} +``` + +```php +// Fetch the Matrix block by its ID +$MatrixBlock = \craft\elements\MatrixBlock::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch Matrix blocks in reverse #} +{% set MatrixBlocks = craft.matrixBlocks() + .inReverse() + .all() %} +``` + +```php +// Fetch Matrix blocks in reverse +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->inReverse() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of Matrix blocks that should be returned. + + + +::: code +```twig +{# Fetch up to 10 Matrix blocks #} +{% set MatrixBlocks = craft.matrixBlocks() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 Matrix blocks +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many Matrix blocks should be skipped in the results. + + + +::: code +```twig +{# Fetch all Matrix blocks except for the first 3 #} +{% set MatrixBlocks = craft.matrixBlocks() + .offset(3) + .all() %} +``` + +```php +// Fetch all Matrix blocks except for the first 3 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) + + + +::: code +```twig +{# Fetch all Matrix blocks in order of date created #} +{% set MatrixBlocks = craft.matrixBlocks() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all Matrix blocks in order of date created +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `owner` + +Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. + + + +::: code +```twig +{# Fetch Matrix blocks created for this entry #} +{% set MatrixBlocks = craft.matrixBlocks() + .owner(myEntry) + .all() %} +``` + +```php +// Fetch Matrix blocks created for this entry +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->owner($myEntry) + ->all(); +``` +::: + + +#### `ownerId` + +Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | created for an element with an ID of 1. +| `'not 1'` | not created for an element with an ID of 1. +| `[1, 2]` | created for an element with an ID of 1 or 2. +| `['not', 1, 2]` | not created for an element with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch Matrix blocks created for an element with an ID of 1 #} +{% set MatrixBlocks = craft.matrixBlocks() + .ownerId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks created for an element with an ID of 1 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->ownerId(1) + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique Matrix blocks from Site A, or Site B if they don’t exist in Site A #} +{% set MatrixBlocks = craft.matrixBlocks() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique Matrix blocks from Site A, or Site B if they don’t exist in Site A +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only Matrix blocks that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all Matrix blocks that are related to myCategory #} +{% set MatrixBlocks = craft.matrixBlocks() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all Matrix blocks that are related to $myCategory +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only Matrix blocks that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all Matrix blocks that match the search query #} +{% set MatrixBlocks = craft.matrixBlocks() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all Matrix blocks that match the search query +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the Matrix blocks should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch Matrix blocks from the Foo site #} +{% set MatrixBlocks = craft.matrixBlocks() + .site('foo') + .all() %} +``` + +```php +// Fetch Matrix blocks from the Foo site +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch Matrix blocks from the site with an ID of 1 #} +{% set MatrixBlocks = craft.matrixBlocks() + .siteId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks from the site with an ID of 1 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the Matrix blocks’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the Matrix block by its ID in the elements_sites table #} +{% set MatrixBlock = craft.matrixBlocks() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the Matrix block by its ID in the elements_sites table +$MatrixBlock = \craft\elements\MatrixBlock::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the Matrix blocks’ statuses. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'enabled'` _(default)_ | that are enabled. +| `'disabled'` | that are disabled. +| `['not', 'disabled']` | that are not disabled. + + + +::: code +```twig +{# Fetch disabled Matrix blocks #} +{% set MatrixBlocks = craft.matrixBlocks() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled Matrix blocks +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->status('disabled') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only Matrix blocks that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed Matrix blocks #} +{% set MatrixBlocks = craft.matrixBlocks() + .trashed() + .all() %} +``` + +```php +// Fetch trashed Matrix blocks +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->trashed() + ->all(); +``` +::: + + +#### `type` + +Narrows the query results based on the Matrix blocks’ block types. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'foo'` | of a type with a handle of `foo`. +| `'not foo'` | not of a type with a handle of `foo`. +| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. +| an [MatrixBlockType](craft3:craft\models\MatrixBlockType) object | of a type represented by the object. + + + +::: code +```twig +{# Fetch Matrix blocks with a Foo block type #} +{% set MatrixBlocks = myEntry.myMatrixField + .type('foo') + .all() %} +``` + +```php +// Fetch Matrix blocks with a Foo block type +$MatrixBlocks = $myEntry->myMatrixField + ->type('foo') + ->all(); +``` +::: + + +#### `typeId` + +Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | of a type with an ID of 1. +| `'not 1'` | not of a type with an ID of 1. +| `[1, 2]` | of a type with an ID of 1 or 2. +| `['not', 1, 2]` | not of a type with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch Matrix blocks of the block type with an ID of 1 #} +{% set MatrixBlocks = myEntry.myMatrixField + .typeId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks of the block type with an ID of 1 +$MatrixBlocks = $myEntry->myMatrixField + ->typeId(1) + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the Matrix blocks’ UIDs. + + + + + +::: code +```twig +{# Fetch the Matrix block by its UID #} +{% set MatrixBlock = craft.matrixBlocks() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the Matrix block by its UID +$MatrixBlock = \craft\elements\MatrixBlock::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique Matrix blocks across all sites #} +{% set MatrixBlocks = craft.matrixBlocks() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique Matrix blocks across all sites +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `with` + +Causes the query to return matching Matrix blocks eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch Matrix blocks eager-loaded with the "Related" field’s relations #} +{% set MatrixBlocks = craft.matrixBlocks() + .with(['related']) + .all() %} +``` + +```php +// Fetch Matrix blocks eager-loaded with the "Related" field’s relations +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/3.x/tags.md b/docs/.artifacts/cms/3.x/tags.md new file mode 100644 index 000000000..7c8c67c4c --- /dev/null +++ b/docs/.artifacts/cms/3.x/tags.md @@ -0,0 +1,874 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only tags that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. +| [asArray](#asarray) | Causes the query to return matching tags as arrays of data, rather than [Tag](craft3:craft\elements\Tag) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#datecreated) | Narrows the query results based on the tags’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the tags’ last-updated dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [group](#group) | Narrows the query results based on the tag groups the tags belong to. +| [groupId](#groupid) | Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. +| [id](#id) | Narrows the query results based on the tags’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [limit](#limit) | Determines the number of tags that should be returned. +| [offset](#offset) | Determines how many tags should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [relatedTo](#relatedto) | Narrows the query results to only tags that are related to certain other elements. +| [search](#search) | Narrows the query results to only tags that match a search query. +| [site](#site) | Determines which site(s) the tags should be queried in. +| [siteId](#siteid) | Determines which site(s) the tags should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the tags’ IDs in the `elements_sites` table. +| [title](#title) | Narrows the query results based on the tags’ titles. +| [trashed](#trashed) | Narrows the query results to only tags that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the tags’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uri](#uri) | Narrows the query results based on the tags’ URIs. +| [with](#with) | Causes the query to return matching tags eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only tags that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all tags that are related to myCategoryA and myCategoryB #} +{% set tags = craft.tags() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all tags that are related to $myCategoryA and $myCategoryB +$tags = \craft\elements\Tag::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all tags, regardless of status #} +{% set tags = craft.tags() + .anyStatus() + .all() %} +``` + +```php +// Fetch all tags, regardless of status +$tags = \craft\elements\Tag::find() + ->anyStatus() + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching tags as arrays of data, rather than [Tag](craft3:craft\elements\Tag) objects. + + + + + +::: code +```twig +{# Fetch tags as arrays #} +{% set tags = craft.tags() + .asArray() + .all() %} +``` + +```php +// Fetch tags as arrays +$tags = \craft\elements\Tag::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `dateCreated` + +Narrows the query results based on the tags’ creation dates. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch tags created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set tags = craft.tags() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch tags created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$tags = \craft\elements\Tag::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the tags’ last-updated dates. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch tags updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set tags = craft.tags() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch tags updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$tags = \craft\elements\Tag::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch tags in a specific order #} +{% set tags = craft.tags() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch tags in a specific order +$tags = \craft\elements\Tag::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `group` + +Narrows the query results based on the tag groups the tags belong to. + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'foo'` | in a group with a handle of `foo`. +| `'not foo'` | not in a group with a handle of `foo`. +| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. +| a [TagGroup](craft3:craft\models\TagGroup) object | in a group represented by the object. + + + +::: code +```twig +{# Fetch tags in the Foo group #} +{% set tags = craft.tags() + .group('foo') + .all() %} +``` + +```php +// Fetch tags in the Foo group +$tags = \craft\elements\Tag::find() + ->group('foo') + ->all(); +``` +::: + + +#### `groupId` + +Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. + +Possible values include: + +| Value | Fetches tags… +| - | - +| `1` | in a group with an ID of 1. +| `'not 1'` | not in a group with an ID of 1. +| `[1, 2]` | in a group with an ID of 1 or 2. +| `['not', 1, 2]` | not in a group with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch tags in the group with an ID of 1 #} +{% set tags = craft.tags() + .groupId(1) + .all() %} +``` + +```php +// Fetch tags in the group with an ID of 1 +$tags = \craft\elements\Tag::find() + ->groupId(1) + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the tags’ IDs. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the tag by its ID #} +{% set tag = craft.tags() + .id(1) + .one() %} +``` + +```php +// Fetch the tag by its ID +$tag = \craft\elements\Tag::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch tags in reverse #} +{% set tags = craft.tags() + .inReverse() + .all() %} +``` + +```php +// Fetch tags in reverse +$tags = \craft\elements\Tag::find() + ->inReverse() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of tags that should be returned. + + + +::: code +```twig +{# Fetch up to 10 tags #} +{% set tags = craft.tags() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 tags +$tags = \craft\elements\Tag::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many tags should be skipped in the results. + + + +::: code +```twig +{# Fetch all tags except for the first 3 #} +{% set tags = craft.tags() + .offset(3) + .all() %} +``` + +```php +// Fetch all tags except for the first 3 +$tags = \craft\elements\Tag::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) + + + +::: code +```twig +{# Fetch all tags in order of date created #} +{% set tags = craft.tags() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all tags in order of date created +$tags = \craft\elements\Tag::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique tags from Site A, or Site B if they don’t exist in Site A #} +{% set tags = craft.tags() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique tags from Site A, or Site B if they don’t exist in Site A +$tags = \craft\elements\Tag::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only tags that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all tags that are related to myCategory #} +{% set tags = craft.tags() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all tags that are related to $myCategory +$tags = \craft\elements\Tag::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only tags that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all tags that match the search query #} +{% set tags = craft.tags() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all tags that match the search query +$tags = \craft\elements\Tag::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the tags should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch tags from the Foo site #} +{% set tags = craft.tags() + .site('foo') + .all() %} +``` + +```php +// Fetch tags from the Foo site +$tags = \craft\elements\Tag::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the tags should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches tags… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch tags from the site with an ID of 1 #} +{% set tags = craft.tags() + .siteId(1) + .all() %} +``` + +```php +// Fetch tags from the site with an ID of 1 +$tags = \craft\elements\Tag::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the tags’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the tag by its ID in the elements_sites table #} +{% set tag = craft.tags() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the tag by its ID in the elements_sites table +$tag = \craft\elements\Tag::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `title` + +Narrows the query results based on the tags’ titles. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch tags with a title that contains "Foo" #} +{% set tags = craft.tags() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch tags with a title that contains "Foo" +$tags = \craft\elements\Tag::find() + ->title('*Foo*') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only tags that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed tags #} +{% set tags = craft.tags() + .trashed() + .all() %} +``` + +```php +// Fetch trashed tags +$tags = \craft\elements\Tag::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the tags’ UIDs. + + + + + +::: code +```twig +{# Fetch the tag by its UID #} +{% set tag = craft.tags() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the tag by its UID +$tag = \craft\elements\Tag::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique tags across all sites #} +{% set tags = craft.tags() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique tags across all sites +$tags = \craft\elements\Tag::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `uri` + +Narrows the query results based on the tags’ URIs. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the tag with that URI #} +{% set tag = craft.tags() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the tag with that URI +$tag = \craft\elements\Tag::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching tags eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch tags eager-loaded with the "Related" field’s relations #} +{% set tags = craft.tags() + .with(['related']) + .all() %} +``` + +```php +// Fetch tags eager-loaded with the "Related" field’s relations +$tags = \craft\elements\Tag::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/3.x/users.md b/docs/.artifacts/cms/3.x/users.md new file mode 100644 index 000000000..61494e5d7 --- /dev/null +++ b/docs/.artifacts/cms/3.x/users.md @@ -0,0 +1,991 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [admin](#admin) | Narrows the query results to only users that have admin accounts. +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only users that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. +| [asArray](#asarray) | Causes the query to return matching users as arrays of data, rather than [User](craft3:craft\elements\User) objects. +| [cache](#cache) | Enables query cache for this Query. +| [can](#can) | Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#datecreated) | Narrows the query results based on the users’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the users’ last-updated dates. +| [email](#email) | Narrows the query results based on the users’ email addresses. +| [firstName](#firstname) | Narrows the query results based on the users’ first names. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [group](#group) | Narrows the query results based on the user group the users belong to. +| [groupId](#groupid) | Narrows the query results based on the user group the users belong to, per the groups’ IDs. +| [hasPhoto](#hasphoto) | Narrows the query results to only users that have (or don’t have) a user photo. +| [id](#id) | Narrows the query results based on the users’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching users as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [lastLoginDate](#lastlogindate) | Narrows the query results based on the users’ last login dates. +| [lastName](#lastname) | Narrows the query results based on the users’ last names. +| [limit](#limit) | Determines the number of users that should be returned. +| [offset](#offset) | Determines how many users should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) +| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. +| [relatedTo](#relatedto) | Narrows the query results to only users that are related to certain other elements. +| [search](#search) | Narrows the query results to only users that match a search query. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the users’ IDs in the `elements_sites` table. +| [status](#status) | Narrows the query results based on the users’ statuses. +| [trashed](#trashed) | Narrows the query results to only users that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the users’ UIDs. +| [username](#username) | Narrows the query results based on the users’ usernames. +| [with](#with) | Causes the query to return matching users eager-loaded with related elements. +| [withGroups](#withgroups) | Causes the query to return matching users eager-loaded with their user groups. + + + + + +#### `admin` + +Narrows the query results to only users that have admin accounts. + + + +::: code +```twig +{# Fetch admins #} +{% set users = craft.users() + .admin() + .all() %} +``` + +```php +// Fetch admins +$users = \craft\elements\User::find() + ->admin() + ->all(); +``` +::: + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only users that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all users that are related to myCategoryA and myCategoryB #} +{% set users = craft.users() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all users that are related to $myCategoryA and $myCategoryB +$users = \craft\elements\User::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all users, regardless of status #} +{% set users = craft.users() + .anyStatus() + .all() %} +``` + +```php +// Fetch all users, regardless of status +$users = \craft\elements\User::find() + ->anyStatus() + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching users as arrays of data, rather than [User](craft3:craft\elements\User) objects. + + + + + +::: code +```twig +{# Fetch users as arrays #} +{% set users = craft.users() + .asArray() + .all() %} +``` + +```php +// Fetch users as arrays +$users = \craft\elements\User::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `can` + +Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. + +See [User Management](https://craftcms.com/docs/3.x/user-management.html) for a full list of available user permissions defined by Craft. + + + +::: code +```twig +{# Fetch users that can access the control panel #} +{% set users = craft.users() + .can('accessCp') + .all() %} +``` + +```php +// Fetch users that can access the control panel +$users = \craft\elements\User::find() + ->can('accessCp') + ->all(); +``` +::: + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `dateCreated` + +Narrows the query results based on the users’ creation dates. + + + +Possible values include: + +| Value | Fetches users… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch users created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set users = craft.users() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch users created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$users = \craft\elements\User::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the users’ last-updated dates. + + + +Possible values include: + +| Value | Fetches users… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch users updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set users = craft.users() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch users updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$users = \craft\elements\User::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `email` + +Narrows the query results based on the users’ email addresses. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'me@domain.tld'` | with an email of `me@domain.tld`. +| `'not me@domain.tld'` | not with an email of `me@domain.tld`. +| `'*@domain.tld'` | with an email that ends with `@domain.tld`. + + + +::: code +```twig +{# Fetch users with a .co.uk domain on their email address #} +{% set users = craft.users() + .email('*.co.uk') + .all() %} +``` + +```php +// Fetch users with a .co.uk domain on their email address +$users = \craft\elements\User::find() + ->email('*.co.uk') + ->all(); +``` +::: + + +#### `firstName` + +Narrows the query results based on the users’ first names. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'Jane'` | with a first name of `Jane`. +| `'not Jane'` | not with a first name of `Jane`. + + + +::: code +```twig +{# Fetch all the Jane's #} +{% set users = craft.users() + .firstName('Jane') + .all() %} +``` + +```php +// Fetch all the Jane's +$users = \craft\elements\User::find() + ->firstName('Jane') + ->one(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch users in a specific order #} +{% set users = craft.users() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch users in a specific order +$users = \craft\elements\User::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `group` + +Narrows the query results based on the user group the users belong to. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'foo'` | in a group with a handle of `foo`. +| `'not foo'` | not in a group with a handle of `foo`. +| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. +| `['and', 'foo', 'bar']` | in both groups with handles of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. +| a [UserGroup](craft3:craft\models\UserGroup) object | in a group represented by the object. + + + +::: code +```twig +{# Fetch users in the Foo user group #} +{% set users = craft.users() + .group('foo') + .all() %} +``` + +```php +// Fetch users in the Foo user group +$users = \craft\elements\User::find() + ->group('foo') + ->all(); +``` +::: + + +#### `groupId` + +Narrows the query results based on the user group the users belong to, per the groups’ IDs. + +Possible values include: + +| Value | Fetches users… +| - | - +| `1` | in a group with an ID of 1. +| `'not 1'` | not in a group with an ID of 1. +| `[1, 2]` | in a group with an ID of 1 or 2. +| `['and', 1, 2]` | in both groups with IDs of 1 or 2. +| `['not', 1, 2]` | not in a group with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch users in a group with an ID of 1 #} +{% set users = craft.users() + .groupId(1) + .all() %} +``` + +```php +// Fetch users in a group with an ID of 1 +$users = \craft\elements\User::find() + ->groupId(1) + ->all(); +``` +::: + + +#### `hasPhoto` + +Narrows the query results to only users that have (or don’t have) a user photo. + + + +::: code +```twig +{# Fetch users with photos #} +{% set users = craft.users() + .hasPhoto() + .all() %} +``` + +```php +// Fetch users without photos +$users = \craft\elements\User::find() + ->hasPhoto() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the users’ IDs. + + + +Possible values include: + +| Value | Fetches users… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the user by its ID #} +{% set user = craft.users() + .id(1) + .one() %} +``` + +```php +// Fetch the user by its ID +$user = \craft\elements\User::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching users as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch users in reverse #} +{% set users = craft.users() + .inReverse() + .all() %} +``` + +```php +// Fetch users in reverse +$users = \craft\elements\User::find() + ->inReverse() + ->all(); +``` +::: + + +#### `lastLoginDate` + +Narrows the query results based on the users’ last login dates. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'>= 2018-04-01'` | that last logged-in on or after 2018-04-01. +| `'< 2018-05-01'` | that last logged-in before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that last logged-in between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch users that logged in recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set users = craft.users() + .lastLoginDate(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch users that logged in recently +$aWeekAgo = (new \DateTime('7 days ago'))->format(\DateTime::ATOM); + +$users = \craft\elements\User::find() + ->lastLoginDate(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `lastName` + +Narrows the query results based on the users’ last names. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'Doe'` | with a last name of `Doe`. +| `'not Doe'` | not with a last name of `Doe`. + + + +::: code +```twig +{# Fetch all the Doe's #} +{% set users = craft.users() + .lastName('Doe') + .all() %} +``` + +```php +// Fetch all the Doe's +$users = \craft\elements\User::find() + ->lastName('Doe') + ->one(); +``` +::: + + +#### `limit` + +Determines the number of users that should be returned. + + + +::: code +```twig +{# Fetch up to 10 users #} +{% set users = craft.users() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 users +$users = \craft\elements\User::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many users should be skipped in the results. + + + +::: code +```twig +{# Fetch all users except for the first 3 #} +{% set users = craft.users() + .offset(3) + .all() %} +``` + +```php +// Fetch all users except for the first 3 +$users = \craft\elements\User::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) + + + +::: code +```twig +{# Fetch all users in order of date created #} +{% set users = craft.users() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all users in order of date created +$users = \craft\elements\User::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique users from Site A, or Site B if they don’t exist in Site A #} +{% set users = craft.users() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique users from Site A, or Site B if they don’t exist in Site A +$users = \craft\elements\User::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only users that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all users that are related to myCategory #} +{% set users = craft.users() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all users that are related to $myCategory +$users = \craft\elements\User::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only users that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all users that match the search query #} +{% set users = craft.users() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all users that match the search query +$users = \craft\elements\User::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the users’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches users… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the user by its ID in the elements_sites table #} +{% set user = craft.users() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the user by its ID in the elements_sites table +$user = \craft\elements\User::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the users’ statuses. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'active'` _(default)_ | with active accounts. +| `'suspended'` | with suspended accounts. +| `'pending'` | with accounts that are still pending activation. +| `'locked'` | with locked accounts (regardless of whether they’re active or suspended). +| `['active', 'suspended']` | with active or suspended accounts. +| `['not', 'active', 'suspended']` | without active or suspended accounts. + + + +::: code +```twig +{# Fetch active and locked users #} +{% set users = craft.users() + .status(['active', 'locked']) + .all() %} +``` + +```php +// Fetch active and locked users +$users = \craft\elements\User::find() + ->status(['active', 'locked']) + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only users that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed users #} +{% set users = craft.users() + .trashed() + .all() %} +``` + +```php +// Fetch trashed users +$users = \craft\elements\User::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the users’ UIDs. + + + + + +::: code +```twig +{# Fetch the user by its UID #} +{% set user = craft.users() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the user by its UID +$user = \craft\elements\User::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `username` + +Narrows the query results based on the users’ usernames. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'foo'` | with a username of `foo`. +| `'not foo'` | not with a username of `foo`. + + + +::: code +```twig +{# Get the requested username #} +{% set requestedUsername = craft.app.request.getSegment(2) %} + +{# Fetch that user #} +{% set user = craft.users() + .username(requestedUsername|literal) + .one() %} +``` + +```php +// Get the requested username +$requestedUsername = \Craft::$app->request->getSegment(2); + +// Fetch that user +$user = \craft\elements\User::find() + ->username(\craft\helpers\Db::escapeParam($requestedUsername)) + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching users eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch users eager-loaded with the "Related" field’s relations #} +{% set users = craft.users() + .with(['related']) + .all() %} +``` + +```php +// Fetch users eager-loaded with the "Related" field’s relations +$users = \craft\elements\User::find() + ->with(['related']) + ->all(); +``` +::: + + +#### `withGroups` + +Causes the query to return matching users eager-loaded with their user groups. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'>= 2018-04-01'` | that last logged-in on or after 2018-04-01. +| `'< 2018-05-01'` | that last logged-in before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that last logged-in between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# fetch users with their user groups #} +{% set users = craft.users() + .withGroups() + .all() %} +``` + +```php +// fetch users with their user groups +$users = \craft\elements\User::find() + ->withGroups() + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/4.x/addresses.md b/docs/.artifacts/cms/4.x/addresses.md new file mode 100644 index 000000000..3a444ff14 --- /dev/null +++ b/docs/.artifacts/cms/4.x/addresses.md @@ -0,0 +1,731 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [administrativeArea](#administrativearea) | Narrows the query results based on the administrative area the assets belong to. +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only addresses that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching addresses as arrays of data, rather than [Address](craft4:craft\elements\Address) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [collect](#collect) | +| [countryCode](#countrycode) | Narrows the query results based on the country the assets belong to. +| [dateCreated](#datecreated) | Narrows the query results based on the addresses’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the addresses’ last-updated dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [id](#id) | Narrows the query results based on the addresses’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching addresses as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [limit](#limit) | Determines the number of addresses that should be returned. +| [offset](#offset) | Determines how many addresses should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the addresses should be returned in. (If empty, defaults to `dateCreated DESC`.) +| [owner](#owner) | Sets the [ownerId](#ownerid) parameter based on a given owner element. +| [ownerId](#ownerid) | Narrows the query results based on the addresses’ owner elements, per their IDs. +| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [relatedTo](#relatedto) | Narrows the query results to only addresses that are related to certain other elements. +| [search](#search) | Narrows the query results to only addresses that match a search query. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the addresses’ IDs in the `elements_sites` table. +| [trashed](#trashed) | Narrows the query results to only addresses that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the addresses’ UIDs. +| [with](#with) | Causes the query to return matching addresses eager-loaded with related elements. + + + + + +#### `administrativeArea` + +Narrows the query results based on the administrative area the assets belong to. + +Possible values include: + +| Value | Fetches addresses… +| - | - +| `'AU'` | with a administrativeArea of `AU`. +| `'not US'` | not in a administrativeArea of `US`. +| `['AU', 'US']` | in a administrativeArea of `AU` or `US`. +| `['not', 'AU', 'US']` | not in a administrativeArea of `AU` or `US`. + + + +::: code +```twig +{# Fetch addresses in the AU #} +{% set addresses = craft.addresses() + .administrativeArea('AU') + .all() %} +``` + +```php +// Fetch addresses in the AU +$addresses = \craft\elements\Address::find() + ->administrativeArea('AU') + ->all(); +``` +::: + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only addresses that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all addresses that are related to myCategoryA and myCategoryB #} +{% set addresses = craft.addresses() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all addresses that are related to $myCategoryA and $myCategoryB +$addresses = \craft\elements\Address::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching addresses as arrays of data, rather than [Address](craft4:craft\elements\Address) objects. + + + + + +::: code +```twig +{# Fetch addresses as arrays #} +{% set addresses = craft.addresses() + .asArray() + .all() %} +``` + +```php +// Fetch addresses as arrays +$addresses = \craft\elements\Address::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `collect` + + + + + + + + +#### `countryCode` + +Narrows the query results based on the country the assets belong to. + +Possible values include: + +| Value | Fetches addresses… +| - | - +| `'AU'` | with a countryCode of `AU`. +| `'not US'` | not in a countryCode of `US`. +| `['AU', 'US']` | in a countryCode of `AU` or `US`. +| `['not', 'AU', 'US']` | not in a countryCode of `AU` or `US`. + + + +::: code +```twig +{# Fetch addresses in the AU #} +{% set addresses = craft.addresses() + .countryCode('AU') + .all() %} +``` + +```php +// Fetch addresses in the AU +$addresses = \craft\elements\Address::find() + ->countryCode('AU') + ->all(); +``` +::: + + +#### `dateCreated` + +Narrows the query results based on the addresses’ creation dates. + + + +Possible values include: + +| Value | Fetches addresses… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch addresses created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set addresses = craft.addresses() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch addresses created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$addresses = \craft\elements\Address::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the addresses’ last-updated dates. + + + +Possible values include: + +| Value | Fetches addresses… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch addresses updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set addresses = craft.addresses() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch addresses updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$addresses = \craft\elements\Address::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch addresses in a specific order #} +{% set addresses = craft.addresses() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch addresses in a specific order +$addresses = \craft\elements\Address::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the addresses’ IDs. + + + +Possible values include: + +| Value | Fetches addresses… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the address by its ID #} +{% set address = craft.addresses() + .id(1) + .one() %} +``` + +```php +// Fetch the address by its ID +$address = \craft\elements\Address::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching addresses as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch addresses in reverse #} +{% set addresses = craft.addresses() + .inReverse() + .all() %} +``` + +```php +// Fetch addresses in reverse +$addresses = \craft\elements\Address::find() + ->inReverse() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of addresses that should be returned. + + + +::: code +```twig +{# Fetch up to 10 addresses #} +{% set addresses = craft.addresses() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 addresses +$addresses = \craft\elements\Address::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many addresses should be skipped in the results. + + + +::: code +```twig +{# Fetch all addresses except for the first 3 #} +{% set addresses = craft.addresses() + .offset(3) + .all() %} +``` + +```php +// Fetch all addresses except for the first 3 +$addresses = \craft\elements\Address::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the addresses should be returned in. (If empty, defaults to `dateCreated DESC`.) + + + +::: code +```twig +{# Fetch all addresses in order of date created #} +{% set addresses = craft.addresses() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all addresses in order of date created +$addresses = \craft\elements\Address::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `owner` + +Sets the [ownerId](#ownerid) parameter based on a given owner element. + + + +::: code +```twig +{# Fetch addresses for the current user #} +{% set addresses = craft.addresses() + .owner(currentUser) + .all() %} +``` + +```php +// Fetch addresses created for the current user +$addresses = \craft\elements\Address::find() + ->owner(Craft::$app->user->identity) + ->all(); +``` +::: + + +#### `ownerId` + +Narrows the query results based on the addresses’ owner elements, per their IDs. + +Possible values include: + +| Value | Fetches addresses… +| - | - +| `1` | created for an element with an ID of 1. +| `[1, 2]` | created for an element with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch addresses created for an element with an ID of 1 #} +{% set addresses = craft.addresses() + .ownerId(1) + .all() %} +``` + +```php +// Fetch addresses created for an element with an ID of 1 +$addresses = \craft\elements\Address::find() + ->ownerId(1) + ->all(); +``` +::: + + +#### `preferSites` + +If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique addresses from Site A, or Site B if they don’t exist in Site A #} +{% set addresses = craft.addresses() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique addresses from Site A, or Site B if they don’t exist in Site A +$addresses = \craft\elements\Address::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `relatedTo` + +Narrows the query results to only addresses that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all addresses that are related to myCategory #} +{% set addresses = craft.addresses() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all addresses that are related to $myCategory +$addresses = \craft\elements\Address::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only addresses that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all addresses that match the search query #} +{% set addresses = craft.addresses() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all addresses that match the search query +$addresses = \craft\elements\Address::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the addresses’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches addresses… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the address by its ID in the elements_sites table #} +{% set address = craft.addresses() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the address by its ID in the elements_sites table +$address = \craft\elements\Address::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `trashed` + +Narrows the query results to only addresses that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed addresses #} +{% set addresses = craft.addresses() + .trashed() + .all() %} +``` + +```php +// Fetch trashed addresses +$addresses = \craft\elements\Address::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the addresses’ UIDs. + + + + + +::: code +```twig +{# Fetch the address by its UID #} +{% set address = craft.addresses() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the address by its UID +$address = \craft\elements\Address::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching addresses eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch addresses eager-loaded with the "Related" field’s relations #} +{% set addresses = craft.addresses() + .with(['related']) + .all() %} +``` + +```php +// Fetch addresses eager-loaded with the "Related" field’s relations +$addresses = \craft\elements\Address::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/4.x/assets.md b/docs/.artifacts/cms/4.x/assets.md new file mode 100644 index 000000000..a7ec05115 --- /dev/null +++ b/docs/.artifacts/cms/4.x/assets.md @@ -0,0 +1,1254 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only assets that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching assets as arrays of data, rather than [Asset](craft4:craft\elements\Asset) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [collect](#collect) | +| [dateCreated](#datecreated) | Narrows the query results based on the assets’ creation dates. +| [dateModified](#datemodified) | Narrows the query results based on the assets’ files’ last-modified dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the assets’ last-updated dates. +| [filename](#filename) | Narrows the query results based on the assets’ filenames. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [folderId](#folderid) | Narrows the query results based on the folders the assets belong to, per the folders’ IDs. +| [folderPath](#folderpath) | Narrows the query results based on the folders the assets belong to, per the folders’ paths. +| [hasAlt](#hasalt) | Narrows the query results based on whether the assets have alternative text. +| [height](#height) | Narrows the query results based on the assets’ image heights. +| [id](#id) | Narrows the query results based on the assets’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [includeSubfolders](#includesubfolders) | Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). +| [kind](#kind) | Narrows the query results based on the assets’ file kinds. +| [limit](#limit) | Determines the number of assets that should be returned. +| [offset](#offset) | Determines how many assets should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [relatedTo](#relatedto) | Narrows the query results to only assets that are related to certain other elements. +| [savable](#savable) | Sets the [savable](https://docs.craftcms.com/api/v3/craft-elements-db-assetquery.html#savable) property. +| [search](#search) | Narrows the query results to only assets that match a search query. +| [site](#site) | Determines which site(s) the assets should be queried in. +| [siteId](#siteid) | Determines which site(s) the assets should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the assets’ IDs in the `elements_sites` table. +| [size](#size) | Narrows the query results based on the assets’ file sizes (in bytes). +| [title](#title) | Narrows the query results based on the assets’ titles. +| [trashed](#trashed) | Narrows the query results to only assets that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the assets’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uploader](#uploader) | Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. +| [volume](#volume) | Narrows the query results based on the volume the assets belong to. +| [volumeId](#volumeid) | Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. +| [width](#width) | Narrows the query results based on the assets’ image widths. +| [with](#with) | Causes the query to return matching assets eager-loaded with related elements. +| [withTransforms](#withtransforms) | Causes the query to return matching assets eager-loaded with image transform indexes. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only assets that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all assets that are related to myCategoryA and myCategoryB #} +{% set assets = craft.assets() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all assets that are related to $myCategoryA and $myCategoryB +$assets = \craft\elements\Asset::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching assets as arrays of data, rather than [Asset](craft4:craft\elements\Asset) objects. + + + + + +::: code +```twig +{# Fetch assets as arrays #} +{% set assets = craft.assets() + .asArray() + .all() %} +``` + +```php +// Fetch assets as arrays +$assets = \craft\elements\Asset::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `collect` + + + + + + + + +#### `dateCreated` + +Narrows the query results based on the assets’ creation dates. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch assets created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set assets = craft.assets() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch assets created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$assets = \craft\elements\Asset::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateModified` + +Narrows the query results based on the assets’ files’ last-modified dates. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'>= 2018-04-01'` | that were modified on or after 2018-04-01. +| `'< 2018-05-01'` | that were modified before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were modified between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were modified at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch assets modified in the last month #} +{% set start = date('30 days ago')|atom %} + +{% set assets = craft.assets() + .dateModified(">= #{start}") + .all() %} +``` + +```php +// Fetch assets modified in the last month +$start = (new \DateTime('30 days ago'))->format(\DateTime::ATOM); + +$assets = \craft\elements\Asset::find() + ->dateModified(">= {$start}") + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the assets’ last-updated dates. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch assets updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set assets = craft.assets() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch assets updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$assets = \craft\elements\Asset::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `filename` + +Narrows the query results based on the assets’ filenames. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'foo.jpg'` | with a filename of `foo.jpg`. +| `'foo*'` | with a filename that begins with `foo`. +| `'*.jpg'` | with a filename that ends with `.jpg`. +| `'*foo*'` | with a filename that contains `foo`. +| `'not *foo*'` | with a filename that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a filename that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a filename that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Fetch all the hi-res images #} +{% set assets = craft.assets() + .filename('*@2x*') + .all() %} +``` + +```php +// Fetch all the hi-res images +$assets = \craft\elements\Asset::find() + ->filename('*@2x*') + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch assets in a specific order #} +{% set assets = craft.assets() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch assets in a specific order +$assets = \craft\elements\Asset::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `folderId` + +Narrows the query results based on the folders the assets belong to, per the folders’ IDs. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | in a folder with an ID of 1. +| `'not 1'` | not in a folder with an ID of 1. +| `[1, 2]` | in a folder with an ID of 1 or 2. +| `['not', 1, 2]` | not in a folder with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch assets in the folder with an ID of 1 #} +{% set assets = craft.assets() + .folderId(1) + .all() %} +``` + +```php +// Fetch assets in the folder with an ID of 1 +$assets = \craft\elements\Asset::find() + ->folderId(1) + ->all(); +``` +::: + + + +::: tip +This can be combined with [includeSubfolders](#includesubfolders) if you want to include assets in all the subfolders of a certain folder. +::: +#### `folderPath` + +Narrows the query results based on the folders the assets belong to, per the folders’ paths. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `foo/` | in a `foo/` folder (excluding nested folders). +| `foo/*` | in a `foo/` folder (including nested folders). +| `'not foo/*'` | not in a `foo/` folder (including nested folders). +| `['foo/*', 'bar/*']` | in a `foo/` or `bar/` folder (including nested folders). +| `['not', 'foo/*', 'bar/*']` | not in a `foo/` or `bar/` folder (including nested folders). + + + +::: code +```twig +{# Fetch assets in the foo/ folder or its nested folders #} +{% set assets = craft.assets() + .folderPath('foo/*') + .all() %} +``` + +```php +// Fetch assets in the foo/ folder or its nested folders +$assets = \craft\elements\Asset::find() + ->folderPath('foo/*') + ->all(); +``` +::: + + +#### `hasAlt` + +Narrows the query results based on whether the assets have alternative text. + + + + + + +#### `height` + +Narrows the query results based on the assets’ image heights. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `100` | with a height of 100. +| `'>= 100'` | with a height of at least 100. +| `['>= 100', '<= 1000']` | with a height between 100 and 1,000. + + + +::: code +```twig +{# Fetch XL images #} +{% set assets = craft.assets() + .kind('image') + .height('>= 1000') + .all() %} +``` + +```php +// Fetch XL images +$assets = \craft\elements\Asset::find() + ->kind('image') + ->height('>= 1000') + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the assets’ IDs. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the asset by its ID #} +{% set asset = craft.assets() + .id(1) + .one() %} +``` + +```php +// Fetch the asset by its ID +$asset = \craft\elements\Asset::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch assets in reverse #} +{% set assets = craft.assets() + .inReverse() + .all() %} +``` + +```php +// Fetch assets in reverse +$assets = \craft\elements\Asset::find() + ->inReverse() + ->all(); +``` +::: + + +#### `includeSubfolders` + +Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). + + + +::: code +```twig +{# Fetch assets in the folder with an ID of 1 (including its subfolders) #} +{% set assets = craft.assets() + .folderId(1) + .includeSubfolders() + .all() %} +``` + +```php +// Fetch assets in the folder with an ID of 1 (including its subfolders) +$assets = \craft\elements\Asset::find() + ->folderId(1) + ->includeSubfolders() + ->all(); +``` +::: + + + +::: warning +This will only work if [folderId](#folderid) was set to a single folder ID. +::: +#### `kind` + +Narrows the query results based on the assets’ file kinds. + +Supported file kinds: +- `access` +- `audio` +- `compressed` +- `excel` +- `flash` +- `html` +- `illustrator` +- `image` +- `javascript` +- `json` +- `pdf` +- `photoshop` +- `php` +- `powerpoint` +- `text` +- `video` +- `word` +- `xml` +- `unknown` + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'image'` | with a file kind of `image`. +| `'not image'` | not with a file kind of `image`.. +| `['image', 'pdf']` | with a file kind of `image` or `pdf`. +| `['not', 'image', 'pdf']` | not with a file kind of `image` or `pdf`. + + + +::: code +```twig +{# Fetch all the images #} +{% set assets = craft.assets() + .kind('image') + .all() %} +``` + +```php +// Fetch all the images +$assets = \craft\elements\Asset::find() + ->kind('image') + ->all(); +``` +::: + + +#### `limit` + +Determines the number of assets that should be returned. + + + +::: code +```twig +{# Fetch up to 10 assets #} +{% set assets = craft.assets() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 assets +$assets = \craft\elements\Asset::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many assets should be skipped in the results. + + + +::: code +```twig +{# Fetch all assets except for the first 3 #} +{% set assets = craft.assets() + .offset(3) + .all() %} +``` + +```php +// Fetch all assets except for the first 3 +$assets = \craft\elements\Asset::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) + + + +::: code +```twig +{# Fetch all assets in order of date created #} +{% set assets = craft.assets() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all assets in order of date created +$assets = \craft\elements\Asset::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique assets from Site A, or Site B if they don’t exist in Site A #} +{% set assets = craft.assets() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique assets from Site A, or Site B if they don’t exist in Site A +$assets = \craft\elements\Asset::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `relatedTo` + +Narrows the query results to only assets that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all assets that are related to myCategory #} +{% set assets = craft.assets() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all assets that are related to $myCategory +$assets = \craft\elements\Asset::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `savable` + +Sets the [savable](https://docs.craftcms.com/api/v3/craft-elements-db-assetquery.html#savable) property. + + + + + + +#### `search` + +Narrows the query results to only assets that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all assets that match the search query #} +{% set assets = craft.assets() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all assets that match the search query +$assets = \craft\elements\Asset::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the assets should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch assets from the Foo site #} +{% set assets = craft.assets() + .site('foo') + .all() %} +``` + +```php +// Fetch assets from the Foo site +$assets = \craft\elements\Asset::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the assets should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch assets from the site with an ID of 1 #} +{% set assets = craft.assets() + .siteId(1) + .all() %} +``` + +```php +// Fetch assets from the site with an ID of 1 +$assets = \craft\elements\Asset::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the assets’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the asset by its ID in the elements_sites table #} +{% set asset = craft.assets() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the asset by its ID in the elements_sites table +$asset = \craft\elements\Asset::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `size` + +Narrows the query results based on the assets’ file sizes (in bytes). + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1000` | with a size of 1,000 bytes (1KB). +| `'< 1000000'` | with a size of less than 1,000,000 bytes (1MB). +| `['>= 1000', '< 1000000']` | with a size between 1KB and 1MB. + + + +::: code +```twig +{# Fetch assets that are smaller than 1KB #} +{% set assets = craft.assets() + .size('< 1000') + .all() %} +``` + +```php +// Fetch assets that are smaller than 1KB +$assets = \craft\elements\Asset::find() + ->size('< 1000') + ->all(); +``` +::: + + +#### `title` + +Narrows the query results based on the assets’ titles. + + + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch assets with a title that contains "Foo" #} +{% set assets = craft.assets() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch assets with a title that contains "Foo" +$assets = \craft\elements\Asset::find() + ->title('*Foo*') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only assets that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed assets #} +{% set assets = craft.assets() + .trashed() + .all() %} +``` + +```php +// Fetch trashed assets +$assets = \craft\elements\Asset::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the assets’ UIDs. + + + + + +::: code +```twig +{# Fetch the asset by its UID #} +{% set asset = craft.assets() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the asset by its UID +$asset = \craft\elements\Asset::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique assets across all sites #} +{% set assets = craft.assets() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique assets across all sites +$assets = \craft\elements\Asset::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `uploader` + +Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | uploaded by the user with an ID of 1. +| a [craft\elements\User](craft4:craft\elements\User) object | uploaded by the user represented by the object. + + + +::: code +```twig +{# Fetch assets uploaded by the user with an ID of 1 #} +{% set assets = craft.assets() + .uploader(1) + .all() %} +``` + +```php +// Fetch assets uploaded by the user with an ID of 1 +$assets = \craft\elements\Asset::find() + ->uploader(1) + ->all(); +``` +::: + + +#### `volume` + +Narrows the query results based on the volume the assets belong to. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `'foo'` | in a volume with a handle of `foo`. +| `'not foo'` | not in a volume with a handle of `foo`. +| `['foo', 'bar']` | in a volume with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a volume with a handle of `foo` or `bar`. +| a [craft\models\Volume](craft4:craft\models\Volume) object | in a volume represented by the object. + + + +::: code +```twig +{# Fetch assets in the Foo volume #} +{% set assets = craft.assets() + .volume('foo') + .all() %} +``` + +```php +// Fetch assets in the Foo group +$assets = \craft\elements\Asset::find() + ->volume('foo') + ->all(); +``` +::: + + +#### `volumeId` + +Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `1` | in a volume with an ID of 1. +| `'not 1'` | not in a volume with an ID of 1. +| `[1, 2]` | in a volume with an ID of 1 or 2. +| `['not', 1, 2]` | not in a volume with an ID of 1 or 2. +| `':empty:'` | that haven’t been stored in a volume yet + + + +::: code +```twig +{# Fetch assets in the volume with an ID of 1 #} +{% set assets = craft.assets() + .volumeId(1) + .all() %} +``` + +```php +// Fetch assets in the volume with an ID of 1 +$assets = \craft\elements\Asset::find() + ->volumeId(1) + ->all(); +``` +::: + + +#### `width` + +Narrows the query results based on the assets’ image widths. + +Possible values include: + +| Value | Fetches assets… +| - | - +| `100` | with a width of 100. +| `'>= 100'` | with a width of at least 100. +| `['>= 100', '<= 1000']` | with a width between 100 and 1,000. + + + +::: code +```twig +{# Fetch XL images #} +{% set assets = craft.assets() + .kind('image') + .width('>= 1000') + .all() %} +``` + +```php +// Fetch XL images +$assets = \craft\elements\Asset::find() + ->kind('image') + ->width('>= 1000') + ->all(); +``` +::: + + +#### `with` + +Causes the query to return matching assets eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch assets eager-loaded with the "Related" field’s relations #} +{% set assets = craft.assets() + .with(['related']) + .all() %} +``` + +```php +// Fetch assets eager-loaded with the "Related" field’s relations +$assets = \craft\elements\Asset::find() + ->with(['related']) + ->all(); +``` +::: + + +#### `withTransforms` + +Causes the query to return matching assets eager-loaded with image transform indexes. + +This can improve performance when displaying several image transforms at once, if the transforms +have already been generated. + +Transforms can be specified as their handle or an object that contains `width` and/or `height` properties. + +You can include `srcset`-style sizes (e.g. `100w` or `2x`) following a normal transform definition, for example: + +::: code + +```twig +[{width: 1000, height: 600}, '1.5x', '2x', '3x'] +``` + +```php +[['width' => 1000, 'height' => 600], '1.5x', '2x', '3x'] +``` + +::: + +When a `srcset`-style size is encountered, the preceding normal transform definition will be used as a +reference when determining the resulting transform dimensions. + + + +::: code +```twig +{# Fetch assets with the 'thumbnail' and 'hiResThumbnail' transform data preloaded #} +{% set assets = craft.assets() + .kind('image') + .withTransforms(['thumbnail', 'hiResThumbnail']) + .all() %} +``` + +```php +// Fetch assets with the 'thumbnail' and 'hiResThumbnail' transform data preloaded +$assets = \craft\elements\Asset::find() + ->kind('image') + ->withTransforms(['thumbnail', 'hiResThumbnail']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/4.x/categories.md b/docs/.artifacts/cms/4.x/categories.md new file mode 100644 index 000000000..0bb4118b5 --- /dev/null +++ b/docs/.artifacts/cms/4.x/categories.md @@ -0,0 +1,1339 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [ancestorDist](#ancestordist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). +| [ancestorOf](#ancestorof) | Narrows the query results to only categories that are ancestors of another category in its structure. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only categories that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching categories as arrays of data, rather than [Category](craft4:craft\elements\Category) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [collect](#collect) | +| [dateCreated](#datecreated) | Narrows the query results based on the categories’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the categories’ last-updated dates. +| [descendantDist](#descendantdist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). +| [descendantOf](#descendantof) | Narrows the query results to only categories that are descendants of another category in its structure. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [group](#group) | Narrows the query results based on the category groups the categories belong to. +| [groupId](#groupid) | Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. +| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the categories have any descendants in their structure. +| [id](#id) | Narrows the query results based on the categories’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [leaves](#leaves) | Narrows the query results based on whether the categories are “leaves” (categories with no descendants). +| [level](#level) | Narrows the query results based on the categories’ level within the structure. +| [limit](#limit) | Determines the number of categories that should be returned. +| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the category that comes immediately after another category in its structure. +| [offset](#offset) | Determines how many categories should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`, or the order defined by the category group if the [group](#group) or [groupId](#groupid) params are set to a single group.) +| [positionedAfter](#positionedafter) | Narrows the query results to only categories that are positioned after another category in its structure. +| [positionedBefore](#positionedbefore) | Narrows the query results to only categories that are positioned before another category in its structure. +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the category that comes immediately before another category in its structure. +| [relatedTo](#relatedto) | Narrows the query results to only categories that are related to certain other elements. +| [search](#search) | Narrows the query results to only categories that match a search query. +| [siblingOf](#siblingof) | Narrows the query results to only categories that are siblings of another category in its structure. +| [site](#site) | Determines which site(s) the categories should be queried in. +| [siteId](#siteid) | Determines which site(s) the categories should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the categories’ IDs in the `elements_sites` table. +| [slug](#slug) | Narrows the query results based on the categories’ slugs. +| [status](#status) | Narrows the query results based on the categories’ statuses. +| [title](#title) | Narrows the query results based on the categories’ titles. +| [trashed](#trashed) | Narrows the query results to only categories that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the categories’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uri](#uri) | Narrows the query results based on the categories’ URIs. +| [with](#with) | Causes the query to return matching categories eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `ancestorDist` + +Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). + + + + + +::: code +```twig +{# Fetch categories above this one #} +{% set categories = craft.categories() + .ancestorOf(myCategory) + .ancestorDist(3) + .all() %} +``` + +```php +// Fetch categories above this one +$categories = \craft\elements\Category::find() + ->ancestorOf($myCategory) + ->ancestorDist(3) + ->all(); +``` +::: + + +#### `ancestorOf` + +Narrows the query results to only categories that are ancestors of another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | above the category with an ID of 1. +| a [Category](craft4:craft\elements\Category) object | above the category represented by the object. + + + +::: code +```twig +{# Fetch categories above this one #} +{% set categories = craft.categories() + .ancestorOf(myCategory) + .all() %} +``` + +```php +// Fetch categories above this one +$categories = \craft\elements\Category::find() + ->ancestorOf($myCategory) + ->all(); +``` +::: + + + +::: tip +This can be combined with [ancestorDist](#ancestordist) if you want to limit how far away the ancestor categories can be. +::: + + +#### `andRelatedTo` + +Narrows the query results to only categories that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all categories that are related to myCategoryA and myCategoryB #} +{% set categories = craft.categories() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all categories that are related to $myCategoryA and $myCategoryB +$categories = \craft\elements\Category::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching categories as arrays of data, rather than [Category](craft4:craft\elements\Category) objects. + + + + + +::: code +```twig +{# Fetch categories as arrays #} +{% set categories = craft.categories() + .asArray() + .all() %} +``` + +```php +// Fetch categories as arrays +$categories = \craft\elements\Category::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `collect` + + + + + + + + +#### `dateCreated` + +Narrows the query results based on the categories’ creation dates. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch categories created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set categories = craft.categories() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch categories created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$categories = \craft\elements\Category::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the categories’ last-updated dates. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch categories updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set categories = craft.categories() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch categories updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$categories = \craft\elements\Category::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `descendantDist` + +Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). + + + + + +::: code +```twig +{# Fetch categories below this one #} +{% set categories = craft.categories() + .descendantOf(myCategory) + .descendantDist(3) + .all() %} +``` + +```php +// Fetch categories below this one +$categories = \craft\elements\Category::find() + ->descendantOf($myCategory) + ->descendantDist(3) + ->all(); +``` +::: + + +#### `descendantOf` + +Narrows the query results to only categories that are descendants of another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | below the category with an ID of 1. +| a [Category](craft4:craft\elements\Category) object | below the category represented by the object. + + + +::: code +```twig +{# Fetch categories below this one #} +{% set categories = craft.categories() + .descendantOf(myCategory) + .all() %} +``` + +```php +// Fetch categories below this one +$categories = \craft\elements\Category::find() + ->descendantOf($myCategory) + ->all(); +``` +::: + + + +::: tip +This can be combined with [descendantDist](#descendantdist) if you want to limit how far away the descendant categories can be. +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch categories in a specific order #} +{% set categories = craft.categories() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch categories in a specific order +$categories = \craft\elements\Category::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `group` + +Narrows the query results based on the category groups the categories belong to. + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'foo'` | in a group with a handle of `foo`. +| `'not foo'` | not in a group with a handle of `foo`. +| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. +| a [CategoryGroup](craft4:craft\models\CategoryGroup) object | in a group represented by the object. + + + +::: code +```twig +{# Fetch categories in the Foo group #} +{% set categories = craft.categories() + .group('foo') + .all() %} +``` + +```php +// Fetch categories in the Foo group +$categories = \craft\elements\Category::find() + ->group('foo') + ->all(); +``` +::: + + +#### `groupId` + +Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | in a group with an ID of 1. +| `'not 1'` | not in a group with an ID of 1. +| `[1, 2]` | in a group with an ID of 1 or 2. +| `['not', 1, 2]` | not in a group with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch categories in the group with an ID of 1 #} +{% set categories = craft.categories() + .groupId(1) + .all() %} +``` + +```php +// Fetch categories in the group with an ID of 1 +$categories = \craft\elements\Category::find() + ->groupId(1) + ->all(); +``` +::: + + +#### `hasDescendants` + +Narrows the query results based on whether the categories have any descendants in their structure. + + + +(This has the opposite effect of calling [leaves](#leaves).) + + + +::: code +```twig +{# Fetch categories that have descendants #} +{% set categories = craft.categories() + .hasDescendants() + .all() %} +``` + +```php +// Fetch categories that have descendants +$categories = \craft\elements\Category::find() + ->hasDescendants() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the categories’ IDs. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the category by its ID #} +{% set category = craft.categories() + .id(1) + .one() %} +``` + +```php +// Fetch the category by its ID +$category = \craft\elements\Category::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch categories in reverse #} +{% set categories = craft.categories() + .inReverse() + .all() %} +``` + +```php +// Fetch categories in reverse +$categories = \craft\elements\Category::find() + ->inReverse() + ->all(); +``` +::: + + +#### `leaves` + +Narrows the query results based on whether the categories are “leaves” (categories with no descendants). + + + +(This has the opposite effect of calling [hasDescendants](#hasdescendants).) + + + +::: code +```twig +{# Fetch categories that have no descendants #} +{% set categories = craft.categories() + .leaves() + .all() %} +``` + +```php +// Fetch categories that have no descendants +$categories = \craft\elements\Category::find() + ->leaves() + ->all(); +``` +::: + + +#### `level` + +Narrows the query results based on the categories’ level within the structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | with a level of 1. +| `'not 1'` | not with a level of 1. +| `'>= 3'` | with a level greater than or equal to 3. +| `[1, 2]` | with a level of 1 or 2 +| `['not', 1, 2]` | not with level of 1 or 2. + + + +::: code +```twig +{# Fetch categories positioned at level 3 or above #} +{% set categories = craft.categories() + .level('>= 3') + .all() %} +``` + +```php +// Fetch categories positioned at level 3 or above +$categories = \craft\elements\Category::find() + ->level('>= 3') + ->all(); +``` +::: + + +#### `limit` + +Determines the number of categories that should be returned. + + + +::: code +```twig +{# Fetch up to 10 categories #} +{% set categories = craft.categories() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 categories +$categories = \craft\elements\Category::find() + ->limit(10) + ->all(); +``` +::: + + +#### `nextSiblingOf` + +Narrows the query results to only the category that comes immediately after another category in its structure. + + + +Possible values include: + +| Value | Fetches the category… +| - | - +| `1` | after the category with an ID of 1. +| a [Category](craft4:craft\elements\Category) object | after the category represented by the object. + + + +::: code +```twig +{# Fetch the next category #} +{% set category = craft.categories() + .nextSiblingOf(myCategory) + .one() %} +``` + +```php +// Fetch the next category +$category = \craft\elements\Category::find() + ->nextSiblingOf($myCategory) + ->one(); +``` +::: + + +#### `offset` + +Determines how many categories should be skipped in the results. + + + +::: code +```twig +{# Fetch all categories except for the first 3 #} +{% set categories = craft.categories() + .offset(3) + .all() %} +``` + +```php +// Fetch all categories except for the first 3 +$categories = \craft\elements\Category::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`, or the order defined by the category group if the [group](#group) or [groupId](#groupid) params are set to a single group.) + + + +::: code +```twig +{# Fetch all categories in order of date created #} +{% set categories = craft.categories() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all categories in order of date created +$categories = \craft\elements\Category::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `positionedAfter` + +Narrows the query results to only categories that are positioned after another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | after the category with an ID of 1. +| a [Category](craft4:craft\elements\Category) object | after the category represented by the object. + + + +::: code +```twig +{# Fetch categories after this one #} +{% set categories = craft.categories() + .positionedAfter(myCategory) + .all() %} +``` + +```php +// Fetch categories after this one +$categories = \craft\elements\Category::find() + ->positionedAfter($myCategory) + ->all(); +``` +::: + + +#### `positionedBefore` + +Narrows the query results to only categories that are positioned before another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | before the category with an ID of 1. +| a [Category](craft4:craft\elements\Category) object | before the category represented by the object. + + + +::: code +```twig +{# Fetch categories before this one #} +{% set categories = craft.categories() + .positionedBefore(myCategory) + .all() %} +``` + +```php +// Fetch categories before this one +$categories = \craft\elements\Category::find() + ->positionedBefore($myCategory) + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique categories from Site A, or Site B if they don’t exist in Site A #} +{% set categories = craft.categories() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique categories from Site A, or Site B if they don’t exist in Site A +$categories = \craft\elements\Category::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `prevSiblingOf` + +Narrows the query results to only the category that comes immediately before another category in its structure. + + + +Possible values include: + +| Value | Fetches the category… +| - | - +| `1` | before the category with an ID of 1. +| a [Category](craft4:craft\elements\Category) object | before the category represented by the object. + + + +::: code +```twig +{# Fetch the previous category #} +{% set category = craft.categories() + .prevSiblingOf(myCategory) + .one() %} +``` + +```php +// Fetch the previous category +$category = \craft\elements\Category::find() + ->prevSiblingOf($myCategory) + ->one(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only categories that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all categories that are related to myCategory #} +{% set categories = craft.categories() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all categories that are related to $myCategory +$categories = \craft\elements\Category::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only categories that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all categories that match the search query #} +{% set categories = craft.categories() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all categories that match the search query +$categories = \craft\elements\Category::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `siblingOf` + +Narrows the query results to only categories that are siblings of another category in its structure. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | beside the category with an ID of 1. +| a [Category](craft4:craft\elements\Category) object | beside the category represented by the object. + + + +::: code +```twig +{# Fetch categories beside this one #} +{% set categories = craft.categories() + .siblingOf(myCategory) + .all() %} +``` + +```php +// Fetch categories beside this one +$categories = \craft\elements\Category::find() + ->siblingOf($myCategory) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the categories should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch categories from the Foo site #} +{% set categories = craft.categories() + .site('foo') + .all() %} +``` + +```php +// Fetch categories from the Foo site +$categories = \craft\elements\Category::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the categories should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch categories from the site with an ID of 1 #} +{% set categories = craft.categories() + .siteId(1) + .all() %} +``` + +```php +// Fetch categories from the site with an ID of 1 +$categories = \craft\elements\Category::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the categories’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the category by its ID in the elements_sites table #} +{% set category = craft.categories() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the category by its ID in the elements_sites table +$category = \craft\elements\Category::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `slug` + +Narrows the query results based on the categories’ slugs. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'foo'` | with a slug of `foo`. +| `'foo*'` | with a slug that begins with `foo`. +| `'*foo'` | with a slug that ends with `foo`. +| `'*foo*'` | with a slug that contains `foo`. +| `'not *foo*'` | with a slug that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested category slug from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the category with that slug #} +{% set category = craft.categories() + .slug(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested category slug from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the category with that slug +$category = \craft\elements\Category::find() + ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the categories’ statuses. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'enabled'` _(default)_ | that are enabled. +| `'disabled'` | that are disabled. +| `['not', 'disabled']` | that are not disabled. + + + +::: code +```twig +{# Fetch disabled categories #} +{% set categories = craft.categories() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled categories +$categories = \craft\elements\Category::find() + ->status('disabled') + ->all(); +``` +::: + + +#### `title` + +Narrows the query results based on the categories’ titles. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch categories with a title that contains "Foo" #} +{% set categories = craft.categories() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch categories with a title that contains "Foo" +$categories = \craft\elements\Category::find() + ->title('*Foo*') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only categories that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed categories #} +{% set categories = craft.categories() + .trashed() + .all() %} +``` + +```php +// Fetch trashed categories +$categories = \craft\elements\Category::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the categories’ UIDs. + + + + + +::: code +```twig +{# Fetch the category by its UID #} +{% set category = craft.categories() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the category by its UID +$category = \craft\elements\Category::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique categories across all sites #} +{% set categories = craft.categories() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique categories across all sites +$categories = \craft\elements\Category::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `uri` + +Narrows the query results based on the categories’ URIs. + + + +Possible values include: + +| Value | Fetches categories… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the category with that URI #} +{% set category = craft.categories() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the category with that URI +$category = \craft\elements\Category::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching categories eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch categories eager-loaded with the "Related" field’s relations #} +{% set categories = craft.categories() + .with(['related']) + .all() %} +``` + +```php +// Fetch categories eager-loaded with the "Related" field’s relations +$categories = \craft\elements\Category::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/4.x/config-db.md b/docs/.artifacts/cms/4.x/config-db.md new file mode 100644 index 000000000..7603209b7 --- /dev/null +++ b/docs/.artifacts/cms/4.x/config-db.md @@ -0,0 +1,516 @@ + + + + +### `attributes` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [DbConfig::$attributes](craft4:craft\config\DbConfig::$attributes) + +
+ +An array of key-value pairs of PDO attributes to pass into the PDO constructor. + +For example, when using the [MySQL PDO driver](https://php.net/manual/en/ref.pdo-mysql.php), if you wanted to enable a SSL database connection +(assuming [SSL is enabled in MySQL](https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-secure-connections.html) and `'user'` can connect via SSL, +you’d set these: + +```php +->attributes([ + PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem', + PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem', + PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem', +]) +``` + + + +### `charset` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'utf8'` + +Defined by +: [DbConfig::$charset](craft4:craft\config\DbConfig::$charset) + +
+ +The charset to use when creating tables. + +::: tip +You can change the character set and collation across all existing database tables using this terminal command: + +```bash +php craft db/convert-charset +``` +::: + +::: code +```php Static Config +->charset('utf8mb4') +``` +```shell Environment Override +CRAFT_DB_CHARSET=utf8mb4 +``` +::: + + + +### `collation` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$collation](craft4:craft\config\DbConfig::$collation) + +Since +: 3.6.4 + +
+ +The collation to use when creating tables. + +This is only used by MySQL. If null, the [charset’s](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#charset) default collation will be used. + +| Charset | Default collation | +| --------- | -------------------- | +| `utf8` | `utf8_general_ci` | +| `utf8mb4` | `utf8mb4_0900_ai_ci` | + +::: tip +You can change the character set and collation across all existing database tables using this terminal command: + +```bash +php craft db/convert-charset +``` +::: + +::: code +```php Static Config +->collation('utf8mb4_0900_ai_ci') +``` +```shell Environment Override +CRAFT_DB_COLLATION=utf8mb4_0900_ai_ci +``` +::: + + + +### `database` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$database](craft4:craft\config\DbConfig::$database) + +
+ +The name of the database to select. + +::: code +```php Static Config +->database('mydatabase') +``` +```shell Environment Override +CRAFT_DB_DATABASE=mydatabase +``` +::: + + + +### `driver` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$driver](craft4:craft\config\DbConfig::$driver) + +
+ +The database driver to use. Either `mysql` for MySQL or `pgsql` for PostgreSQL. + +::: code +```php Static Config +->driver('mysql') +``` +```shell Environment Override +CRAFT_DB_DRIVER=mysql +``` +::: + + + +### `dsn` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$dsn](craft4:craft\config\DbConfig::$dsn) + +
+ +The Data Source Name (“DSN”) that tells Craft how to connect to the database. + +DSNs should begin with a driver prefix (`mysql:` or `pgsql:`), followed by driver-specific parameters. +For example, `mysql:host=127.0.0.1;port=3306;dbname=acme_corp`. + +- MySQL parameters: +- PostgreSQL parameters: + +::: code +```php Static Config +->dsn('mysql:host=127.0.0.1;port=3306;dbname=acme_corp') +``` +```shell Environment Override +CRAFT_DB_DSN=mysql:host=127.0.0.1;port=3306;dbname=acme_corp +``` +::: + + + +### `password` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [DbConfig::$password](craft4:craft\config\DbConfig::$password) + +
+ +The database password to connect with. + +::: code +```php Static Config +->password('super-secret') +``` +```shell Environment Override +CRAFT_DB_PASSWORD=super-secret +``` +::: + + + +### `port` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$port](craft4:craft\config\DbConfig::$port) + +
+ +The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. + +::: code +```php Static Config +->port(3306) +``` +```shell Environment Override +CRAFT_DB_PORT=3306 +``` +::: + + + +### `schema` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `'public'` + +Defined by +: [DbConfig::$schema](craft4:craft\config\DbConfig::$schema) + +
+ +The schema that Postgres is configured to use by default (PostgreSQL only). + +::: tip +To force Craft to use the specified schema regardless of PostgreSQL’s `search_path` setting, you must enable +the [setSchemaOnConnect()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-setschemaonconnect) setting. +::: + +::: code +```php Static Config +->schema('myschema,public') +``` +```shell Environment Override +CRAFT_DB_SCHEMA=myschema,public +``` +::: + + + +### `server` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$server](craft4:craft\config\DbConfig::$server) + +
+ +The database server name or IP address. Usually `localhost` or `127.0.0.1`. + +::: code +```php Static Config +->server('localhost') +``` +```shell Environment Override +CRAFT_DB_SERVER=localhost +``` +::: + + + +### `setSchemaOnConnect` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [DbConfig::$setSchemaOnConnect](craft4:craft\config\DbConfig::$setSchemaOnConnect) + +Since +: 3.7.27 + +
+ +Whether the [schema()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-schema) should be explicitly used for database queries (PostgreSQL only). + +::: warning +This will cause an extra `SET search_path` SQL query to be executed per database connection. Ideally, +PostgreSQL’s `search_path` setting should be configured to prioritize the desired schema. +::: + +::: code +```php Static Config +->setSchemaOnConnect(true) +``` +```shell Environment Override +CRAFT_DB_SET_SCHEMA_ON_CONNECT=true +``` +::: + + + +### `tablePrefix` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$tablePrefix](craft4:craft\config\DbConfig::$tablePrefix) + +
+ +If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), +you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase. + +::: code +```php Static Config +->tablePrefix('craft_') +``` +```shell Environment Override +CRAFT_DB_TABLE_PREFIX=craft_ +``` +::: + + + +### `unixSocket` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$unixSocket](craft4:craft\config\DbConfig::$unixSocket) + +
+ +MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of +the server and port. If this is specified, then `server` and `port` settings are ignored. + +::: code +```php Static Config +->unixSocket('/Applications/MAMP/tmp/mysql/mysql.sock') +``` +```shell Environment Override +CRAFT_DB_UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock +``` +::: + + + +### `url` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [DbConfig::$url](craft4:craft\config\DbConfig::$url) + +
+ +The database connection URL, if one was provided by your hosting environment. + +If this is set, the values for [driver()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-driver), [user()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-user), [database()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-database), [server()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-server), [port()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-port), and [database()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-database) will be extracted from it. + +::: code +```php Static Config +->url('jdbc:mysql://database.foo:3306/mydb') +``` +```shell Environment Override +CRAFT_DB_URL=jdbc:mysql://database.foo:3306/mydb +``` +::: + + + +### `useUnbufferedConnections` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [DbConfig::$useUnbufferedConnections](craft4:craft\config\DbConfig::$useUnbufferedConnections) + +Since +: 3.7.0 + +
+ +Whether batched queries should be executed on a separate, unbuffered database connection. + +This setting only applies to MySQL. It can be enabled when working with high volume content, to prevent +PHP from running out of memory when querying too much data at once. (See + for an explanation +of MySQL’s batch query limitations.) + +For more on Craft batch queries, see . + +::: code +```php Static Config +->useUnbufferedConnections(true) +``` +```shell Environment Override +CRAFT_DB_USE_UNBUFFERED_CONNECTIONS=true +``` +::: + + + +### `user` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'root'` + +Defined by +: [DbConfig::$user](craft4:craft\config\DbConfig::$user) + +
+ +The database username to connect with. + +::: code +```php Static Config +->user('db') +``` +```shell Environment Override +CRAFT_DB_USER=db +``` +::: + + + + + diff --git a/docs/.artifacts/cms/4.x/config-general.md b/docs/.artifacts/cms/4.x/config-general.md new file mode 100644 index 000000000..0702c1db1 --- /dev/null +++ b/docs/.artifacts/cms/4.x/config-general.md @@ -0,0 +1,5001 @@ + + + + +## System + +### `accessibilityDefaults` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[ + 'alwaysShowFocusRings' => false, + 'useShapes' => false, + 'underlineLinks' => false, + 'notificationDuration' => 5000, +]` + +Defined by +: [GeneralConfig::$accessibilityDefaults](craft4:craft\config\GeneralConfig::$accessibilityDefaults) + +Since +: 3.6.4 + +
+ +The default user accessibility preferences that should be applied to users that haven’t saved their preferences yet. + +The array can contain the following keys: + +- `alwaysShowFocusRings` - Whether focus rings should always be shown when an element has focus. +- `useShapes` – Whether shapes should be used to represent statuses. +- `underlineLinks` – Whether links should be underlined. +- `notificationDuration` – How long notifications should be shown before they disappear automatically (in + milliseconds). Set to `0` to show them indefinitely. + +```php +->accessibilityDefaults([ + 'useShapes' => true, +]) +``` + + + +### `allowAdminChanges` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$allowAdminChanges](craft4:craft\config\GeneralConfig::$allowAdminChanges) + +Since +: 3.1.0 + +
+ +Whether admins should be allowed to make administrative changes to the system. + +When this is disabled, the Settings section will be hidden, the Craft edition and Craft/plugin versions will be locked, +and the project config and Plugin Store will become read-only—though Craft and plugin licenses may still be purchased. + +It’s best to disable this in production environments with a deployment workflow that runs `composer install` and +[propagates project config updates](../project-config.md#propagating-changes) on deploy. + +::: warning +Don’t disable this setting until **all** environments have been updated to Craft 3.1.0 or later. +::: + +::: code +```php Static Config +->allowAdminChanges(false) +``` +```shell Environment Override +CRAFT_ALLOW_ADMIN_CHANGES=false +``` +::: + + + +### `allowSimilarTags` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$allowSimilarTags](craft4:craft\config\GeneralConfig::$allowSimilarTags) + +
+ +Whether users should be allowed to create similarly-named tags. + +::: code +```php Static Config +->allowSimilarTags(true) +``` +```shell Environment Override +CRAFT_ALLOW_SIMILAR_TAGS=1 +``` +::: + + + +### `allowUpdates` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$allowUpdates](craft4:craft\config\GeneralConfig::$allowUpdates) + +
+ +Whether Craft should allow system and plugin updates in the control panel, and plugin installation from the Plugin Store. + +This setting will automatically be disabled if is disabled. + +::: code +```php Static Config +->allowUpdates(false) +``` +```shell Environment Override +CRAFT_ALLOW_UPDATES=false +``` +::: + + + +### `autoLoginAfterAccountActivation` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$autoLoginAfterAccountActivation](craft4:craft\config\GeneralConfig::$autoLoginAfterAccountActivation) + +
+ +Whether users should automatically be logged in after activating their account or resetting their password. + +::: code +```php Static Config +->autoLoginAfterAccountActivation(true) +``` +```shell Environment Override +CRAFT_ALLOW_AUTO_LOGIN_AFTER_ACCOUNT_ACTIVATION=true +``` +::: + + + +### `autosaveDrafts` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$autosaveDrafts](craft4:craft\config\GeneralConfig::$autosaveDrafts) + +Since +: 3.5.6 + +Deprecated +: in 4.0.0 + +
+ +Whether drafts should be saved automatically as they are edited. + +Note that drafts *will* be autosaved while Live Preview is open, regardless of this setting. + +::: code +```shell Environment Override +CRAFT_AUTOSAVE_DRAFTS=false +``` +::: + + + +### `backupOnUpdate` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$backupOnUpdate](craft4:craft\config\GeneralConfig::$backupOnUpdate) + +
+ +Whether Craft should create a database backup before applying a new system update. + +::: code +```php Static Config +->backupOnUpdate(false) +``` +```shell Environment Override +CRAFT_BACKUP_ON_UPDATE=false +``` +::: + + + +### `cacheDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `86400` (1 day) + +Defined by +: [GeneralConfig::$cacheDuration](craft4:craft\config\GeneralConfig::$cacheDuration) + +
+ +The default length of time Craft will store data, RSS feed, and template caches. + +If set to `0`, data and RSS feed caches will be stored indefinitely; template caches will be stored for one year. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +->cacheDuration(0) +``` +```shell Environment Override +CRAFT_CACHE_DURATION=0 +``` +::: + + + +### `cpHeadTags` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$cpHeadTags](craft4:craft\config\GeneralConfig::$cpHeadTags) + +Since +: 3.5.0 + +
+ +List of additional HTML tags that should be included in the `` of control panel pages. + +Each tag can be specified as an array of the tag name and its attributes. + +For example, you can give the control panel a custom favicon (etc.) like this: + +```php Static Config +->cpHeadTags([ + // Traditional favicon + ['link', ['rel' => 'icon', 'href' => '/icons/favicon.ico']], + // Scalable favicon for browsers that support them + ['link', ['rel' => 'icon', 'type' => 'image/svg+xml', 'sizes' => 'any', 'href' => '/icons/favicon.svg']], + // Touch icon for mobile devices + ['link', ['rel' => 'apple-touch-icon', 'sizes' => '180x180', 'href' => '/icons/touch-icon.svg']], + // Pinned tab icon for Safari + ['link', ['rel' => 'mask-icon', 'href' => '/icons/mask-icon.svg', 'color' => '#663399']], +]) +``` + + + +### `defaultCountryCode` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'US'` + +Defined by +: [GeneralConfig::$defaultCountryCode](craft4:craft\config\GeneralConfig::$defaultCountryCode) + +Since +: 4.5.0 + +
+ +The two-letter country code that addresses will be set to by default. + +See for a list of acceptable country codes. + +::: code +```php Static Config +->defaultCountryCode('GB') +``` +```shell Environment Override +CRAFT_DEFAULT_COUNTRY_CODE=GB +``` +::: + + + +### `defaultCpLanguage` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$defaultCpLanguage](craft4:craft\config\GeneralConfig::$defaultCpLanguage) + +
+ +The default language the control panel should use for users who haven’t set a preferred language yet. + +::: code +```php Static Config +->defaultCpLanguage('en-US') +``` +```shell Environment Override +CRAFT_DEFAULT_CP_LANGUAGE=en-US +``` +::: + + + +### `defaultCpLocale` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$defaultCpLocale](craft4:craft\config\GeneralConfig::$defaultCpLocale) + +Since +: 3.5.0 + +
+ +The default locale the control panel should use for date/number formatting, for users who haven’t set +a preferred language or formatting locale. + +If this is `null`, the config setting will determine which locale is used for date/number formatting by default. + +::: code +```php Static Config +->defaultCpLocale('en-US') +``` +```shell Environment Override +CRAFT_DEFAULT_CP_LOCALE=en-US +``` +::: + + + +### `defaultDirMode` + +
+ +Allowed types +: `mixed` + +Default value +: `0775` + +Defined by +: [GeneralConfig::$defaultDirMode](craft4:craft\config\GeneralConfig::$defaultDirMode) + +
+ +The default permission to be set for newly-generated directories. + +If set to `null`, the permission will be determined by the current environment. + +::: code +```php Static Config +->defaultDirMode(0744) +``` +```shell Environment Override +CRAFT_DEFAULT_DIR_MODE=0744 +``` +::: + + + +### `defaultFileMode` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$defaultFileMode](craft4:craft\config\GeneralConfig::$defaultFileMode) + +
+ +The default permission to be set for newly-generated files. + +If set to `null`, the permission will be determined by the current environment. + +::: code +```php Static Config +->defaultFileMode(0744) +``` +```shell Environment Override +CRAFT_DEFAULT_FILE_MODE=0744 +``` +::: + + + +### `defaultSearchTermOptions` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$defaultSearchTermOptions](craft4:craft\config\GeneralConfig::$defaultSearchTermOptions) + +
+ +The default options that should be applied to each search term. + +Options include: + +- `subLeft` – Whether to include keywords that contain the term, with additional characters before it. (`false` by default) +- `subRight` – Whether to include keywords that contain the term, with additional characters after it. (`true` by default) +- `exclude` – Whether search results should *exclude* records with this term. (`false` by default) +- `exact` – Whether the term must be an exact match (only applies if the search term specifies an attribute). (`false` by default) + +```php Static Config +->defaultSearchTermOptions([ + 'subLeft' => true, + 'exclude' => 'secret', +]) +``` + + + +### `defaultTemplateExtensions` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[ + 'html', + 'twig', +]` + +Defined by +: [GeneralConfig::$defaultTemplateExtensions](craft4:craft\config\GeneralConfig::$defaultTemplateExtensions) + +
+ +The template file extensions Craft will look for when matching a template path to a file on the front end. + +::: code +```php Static Config +->defaultTemplateExtensions(['html', 'twig', 'txt']) +``` +```shell Environment Override +CRAFT_DEFAULT_TEMPLATE_EXTENSIONS=html,twig,txt +``` +::: + + + +### `defaultWeekStartDay` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `1` (Monday) + +Defined by +: [GeneralConfig::$defaultWeekStartDay](craft4:craft\config\GeneralConfig::$defaultWeekStartDay) + +
+ +The default day new users should have set as their Week Start Day. + +This should be set to one of the following integers: + +- `0` – Sunday +- `1` – Monday +- `2` – Tuesday +- `3` – Wednesday +- `4` – Thursday +- `5` – Friday +- `6` – Saturday + +::: code +```php Static Config +->defaultWeekStartDay(0) +``` +```shell Environment Override +CRAFT_DEFAULT_WEEK_START_DAY=0 +``` +::: + + + +### `devMode` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$devMode](craft4:craft\config\GeneralConfig::$devMode) + +
+ +Whether the system should run in [Dev Mode](https://craftcms.com/support/dev-mode). + +::: code +```php Static Config +->devMode(true) +``` +```shell Environment Override +CRAFT_DEV_MODE=true +``` +::: + + + +### `disabledPlugins` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$disabledPlugins](craft4:craft\config\GeneralConfig::$disabledPlugins) + +Since +: 3.1.9 + +
+ +Array of plugin handles that should be disabled, regardless of what the project config says. + +```php +->disabledPlugins([ + 'webhooks', +]) +``` + +This can also be set to `'*'` to disable **all** plugins. + +```php +->disabledPlugins('*') +``` + +::: warning +This should not be set on a per-environment basis, as it could result in plugin schema version mismatches +between environments, which will prevent project config changes from getting applied. +::: + +::: code +```php Static Config +->disabledPlugins([ + 'redactor', + 'webhooks', +]) +``` +```shell Environment Override +CRAFT_DISABLED_PLUGINS=redactor,webhooks +``` +::: + + + +### `disabledUtilities` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[]` + +Defined by +: [GeneralConfig::$disabledUtilities](craft4:craft\config\GeneralConfig::$disabledUtilities) + +Since +: 4.6.0 + +
+ +Array of utility IDs that should be disabled. + +::: code +```php Static Config + ->disabledUtilities([ + 'updates', + 'find-replace', + ]) +``` +```shell Environment Override +CRAFT_DISABLED_UTILITIES=updates,find-replace +``` +::: + + + +### `disallowRobots` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$disallowRobots](craft4:craft\config\GeneralConfig::$disallowRobots) + +Since +: 3.5.10 + +
+ +Whether front end requests should respond with `X-Robots-Tag: none` HTTP headers, indicating that pages should not be indexed, +and links on the page should not be followed, by web crawlers. + +::: tip +This should be set to `true` for development and staging environments. +::: + +::: code +```php Static Config +->disallowRobots(true) +``` +```shell Environment Override +CRAFT_DISALLOW_ROBOTS=1 +``` +::: + + + +### `enableTemplateCaching` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableTemplateCaching](craft4:craft\config\GeneralConfig::$enableTemplateCaching) + +
+ +Whether to enable Craft’s template `{% cache %}` tag on a global basis. + +::: code +```php Static Config +->enableTemplateCaching(false) +``` +```shell Environment Override +CRAFT_ENABLE_TEMPLATE_CACHING=false +``` +::: + + + +### `errorTemplatePrefix` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [GeneralConfig::$errorTemplatePrefix](craft4:craft\config\GeneralConfig::$errorTemplatePrefix) + +
+ +The prefix that should be prepended to HTTP error status codes when determining the path to look for an error’s template. + +If set to `'_'` your site’s 404 template would live at `templates/_404.twig`, for example. + +::: code +```php Static Config +->errorTemplatePrefix('_') +``` +```shell Environment Override +CRAFT_ERROR_TEMPLATE_PREFIX=_ +``` +::: + + + +### `extraAllowedFileExtensions` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$extraAllowedFileExtensions](craft4:craft\config\GeneralConfig::$extraAllowedFileExtensions) + +
+ +List of file extensions that will be merged into the config setting. + +::: code +```php Static Config +->extraAllowedFileExtensions(['mbox', 'xml']) +``` +```shell Environment Override +CRAFT_EXTRA_ALLOWED_FILE_EXTENSIONS=mbox,xml +``` +::: + + + +### `extraAppLocales` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$extraAppLocales](craft4:craft\config\GeneralConfig::$extraAppLocales) + +Since +: 3.0.24 + +
+ +List of extra locale IDs that the application should support, and users should be able to select as their Preferred Language. + +::: code +```php Static Config +->extraAppLocales(['uk']) +``` +```shell Environment Override +CRAFT_EXTRA_APP_LOCALES=uk +``` +::: + + + +### `handleCasing` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `GeneralConfig::CAMEL_CASE` + +Defined by +: [GeneralConfig::$handleCasing](craft4:craft\config\GeneralConfig::$handleCasing) + +Since +: 3.6.0 + +
+ +The casing to use for autogenerated component handles. + + + +### `headlessMode` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$headlessMode](craft4:craft\config\GeneralConfig::$headlessMode) + +Since +: 3.3.0 + +
+ +Whether the system should run in Headless Mode, which optimizes the system and control panel for headless CMS implementations. + +When this is enabled, the following changes will take place: + +- Template settings for sections and category groups will be hidden. +- Template route management will be hidden. +- Front-end routing will skip checks for element and template requests. +- Front-end responses will be JSON-formatted rather than HTML by default. +- Twig will be configured to escape unsafe strings for JavaScript/JSON rather than HTML by default for front-end requests. +- The , , , and settings will be ignored. + +::: tip +With Headless Mode enabled, users may only set passwords and verify email addresses via the control panel. Be sure to grant “Access the control +panel” permission to all content editors and administrators. You’ll also need to set the config setting if the control +panel is located on a different domain than your front end. +::: + +::: code +```php Static Config +->headlessMode(true) +``` +```shell Environment Override +CRAFT_HEADLESS_MODE=1 +``` +::: + + + +### `httpProxy` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$httpProxy](craft4:craft\config\GeneralConfig::$httpProxy) + +Since +: 3.7.0 + +
+ +The proxy server that should be used for outgoing HTTP requests. + +This can be set to a URL (`http://localhost`) or a URL plus a port (`http://localhost:8125`). + +::: code +```php Static Config +->httpProxy(' +``` +```shell Environment Override +CRAFT_HTTP_PROXY=http://localhost +``` +::: + + + +### `indexTemplateFilenames` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[ + 'index', +]` + +Defined by +: [GeneralConfig::$indexTemplateFilenames](craft4:craft\config\GeneralConfig::$indexTemplateFilenames) + +
+ +The template filenames Craft will look for within a directory to represent the directory’s “index” template when +matching a template path to a file on the front end. + +::: code +```php Static Config +->indexTemplateFilenames(['index', 'default']) +``` +```shell Environment Override +CRAFT_INDEX_TEMPLATE_FILENAMES=index,default +``` +::: + + + +### `ipHeaders` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$ipHeaders](craft4:craft\config\GeneralConfig::$ipHeaders) + +
+ +List of headers where proxies store the real client IP. + +See [yii\web\Request::$ipHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$ipHeaders-detail) for more details. + +If not set, the default [craft\web\Request::$ipHeaders](https://docs.craftcms.com/api/v4/craft-web-request.html#ipheaders) value will be used. + +::: code +```php Static Config +->ipHeaders(['X-Forwarded-For', 'CF-Connecting-IP']) +``` +```shell Environment Override +CRAFT_IP_HEADERS=X-Forwarded-For,CF-Connecting-IP +``` +::: + + + +### `isSystemLive` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$isSystemLive](craft4:craft\config\GeneralConfig::$isSystemLive) + +
+ +Whether the site is currently live. If set to `true` or `false`, it will take precedence over the System Status setting +in Settings → General. + +::: code +```php Static Config +->isSystemLive(true) +``` +```shell Environment Override +CRAFT_IS_SYSTEM_LIVE=true +``` +::: + + + +### `limitAutoSlugsToAscii` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$limitAutoSlugsToAscii](craft4:craft\config\GeneralConfig::$limitAutoSlugsToAscii) + +
+ +Whether non-ASCII characters in auto-generated slugs should be converted to ASCII (i.e. ñ → n). + +::: tip +This only affects the JavaScript auto-generated slugs. Non-ASCII characters can still be used in slugs if entered manually. +::: + +::: code +```php Static Config +->limitAutoSlugsToAscii(true) +``` +```shell Environment Override +CRAFT_LIMIT_AUTO_SLUGS_TO_ASCII=1 +``` +::: + + + +### `maxBackups` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [false](https://php.net/language.types.boolean) + +Default value +: `20` + +Defined by +: [GeneralConfig::$maxBackups](craft4:craft\config\GeneralConfig::$maxBackups) + +
+ +The number of backups Craft should make before it starts deleting the oldest backups. If set to `false`, Craft will +not delete any backups. + +::: code +```php Static Config +->maxBackups(5) +``` +```shell Environment Override +CRAFT_MAX_BACKUPS=5 +``` +::: + + + +### `maxRevisions` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) + +Default value +: `50` + +Defined by +: [GeneralConfig::$maxRevisions](craft4:craft\config\GeneralConfig::$maxRevisions) + +Since +: 3.2.0 + +
+ +The maximum number of revisions that should be stored for each element. + +Set to `0` if you want to store an unlimited number of revisions. + +::: code +```php Static Config +->maxRevisions(25) +``` +```shell Environment Override +CRAFT_MAX_REVISIONS=25 +``` +::: + + + +### `maxSlugIncrement` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `100` + +Defined by +: [GeneralConfig::$maxSlugIncrement](craft4:craft\config\GeneralConfig::$maxSlugIncrement) + +
+ +The highest number Craft will tack onto a slug in order to make it unique before giving up and throwing an error. + +::: code +```php Static Config +->maxSlugIncrement(10) +``` +```shell Environment Override +CRAFT_MAX_SLUG_INCREMENT=10 +``` +::: + + + +### `permissionsPolicyHeader` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$permissionsPolicyHeader](craft4:craft\config\GeneralConfig::$permissionsPolicyHeader) + +Since +: 3.6.14 + +
+ +The `Permissions-Policy` header that should be sent for web responses. + +::: code +```php Static Config +->permissionsPolicyHeader('Permissions-Policy: geolocation=(self)') +``` +```shell Environment Override +CRAFT_PERMISSIONS_POLICY_HEADER=Permissions-Policy: geolocation=(self) +``` +::: + + + +### `phpMaxMemoryLimit` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$phpMaxMemoryLimit](craft4:craft\config\GeneralConfig::$phpMaxMemoryLimit) + +
+ +The maximum amount of memory Craft will try to reserve during memory-intensive operations such as zipping, +unzipping and updating. Defaults to an empty string, which means it will use as much memory as it can. + +See for a list of acceptable values. + +::: code +```php Static Config +->phpMaxMemoryLimit('512M') +``` +```shell Environment Override +CRAFT_PHP_MAX_MEMORY_LIMIT=512M +``` +::: + + + +### `preloadSingles` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$preloadSingles](craft4:craft\config\GeneralConfig::$preloadSingles) + +Since +: 4.4.0 + +
+ +Whether Single section entries should be preloaded for Twig templates. + +When enabled, Craft will make an educated guess on which Singles should be preloaded for each template based on +the variable names that are referenced. + +::: warning +You will need to clear your compiled templates from the Caches utility before this setting will take effect. +::: + +::: code +```php Static Config +->preloadSingles() +``` +```shell Environment Override +CRAFT_PRELOAD_SINGLES=true +``` +::: + + + +### `previewIframeResizerOptions` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$previewIframeResizerOptions](craft4:craft\config\GeneralConfig::$previewIframeResizerOptions) + +Since +: 3.5.0 + +
+ +Custom [iFrame Resizer options](http://davidjbradshaw.github.io/iframe-resizer/#options) that should be used for preview iframes. + +```php Static Config +->previewIframeResizerOptions([ + 'autoResize' => false, +]) +``` + + + +### `privateTemplateTrigger` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'_'` + +Defined by +: [GeneralConfig::$privateTemplateTrigger](craft4:craft\config\GeneralConfig::$privateTemplateTrigger) + +
+ +The template path segment prefix that should be used to identify “private” templates, which are templates that are not +directly accessible via a matching URL. + +Set to an empty value to disable public template routing. + +::: code +```php Static Config +->privateTemplateTrigger('') +``` +```shell Environment Override +CRAFT_PRIVATE_TEMPLATE_TRIGGER= +``` +::: + + + +### `runQueueAutomatically` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$runQueueAutomatically](craft4:craft\config\GeneralConfig::$runQueueAutomatically) + +
+ +Whether Craft should run pending queue jobs automatically when someone visits the control panel. + +If disabled, an alternate queue worker *must* be set up separately, either as an +[always-running daemon](https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/worker.md), or a cron job that runs the +`queue/run` command every minute: + +```cron +* * * * * /path/to/project/craft queue/run +``` + +::: tip +This setting should be disabled for servers running Win32, or with Apache’s mod_deflate/mod_gzip installed, +where PHP’s [flush()](https://php.net/manual/en/function.flush.php) method won’t work. +::: + +::: code +```php Static Config +->runQueueAutomatically(false) +``` +```shell Environment Override +CRAFT_RUN_QUEUE_AUTOMATICALLY=false +``` +::: + + + +### `sameSiteCookieValue` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$sameSiteCookieValue](craft4:craft\config\GeneralConfig::$sameSiteCookieValue) + +Since +: 3.1.33 + +
+ +The [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) value that should be set on Craft cookies, if any. + + + +### `sendContentLengthHeader` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$sendContentLengthHeader](craft4:craft\config\GeneralConfig::$sendContentLengthHeader) + +Since +: 3.7.3 + +
+ +Whether a `Content-Length` header should be sent with responses. + +::: code +```php Static Config +->sendContentLengthHeader(true) +``` +```shell Environment Override +CRAFT_SEND_CONTENT_LENGTH_HEADER=1 +``` +::: + + + +### `sendPoweredByHeader` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$sendPoweredByHeader](craft4:craft\config\GeneralConfig::$sendPoweredByHeader) + +
+ +Whether an `X-Powered-By: Craft CMS` header should be sent, helping services like [BuiltWith](https://builtwith.com/) and +[Wappalyzer](https://www.wappalyzer.com/) identify that the site is running on Craft. + +::: code +```php Static Config +->sendPoweredByHeader(false) +``` +```shell Environment Override +CRAFT_SEND_POWERED_BY_HEADER=false +``` +::: + + + +### `slugWordSeparator` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'-'` + +Defined by +: [GeneralConfig::$slugWordSeparator](craft4:craft\config\GeneralConfig::$slugWordSeparator) + +
+ +The character(s) that should be used to separate words in slugs. + +::: code +```php Static Config +->slugWordSeparator('.') +``` +```shell Environment Override +CRAFT_SLUG_WORD_SEPARATOR=. +``` +::: + + + +### `testToEmailAddress` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [array](https://php.net/language.types.array), [null](https://php.net/language.types.null), [false](https://php.net/language.types.boolean) + +Default value +: `null` + +Defined by +: [GeneralConfig::$testToEmailAddress](craft4:craft\config\GeneralConfig::$testToEmailAddress) + +
+ +Configures Craft to send all system emails to either a single email address or an array of email addresses +for testing purposes. + +By default, the recipient name(s) will be “Test Recipient”, but you can customize that by setting the value with the format +`['me@domain.tld' => 'Name']`. + +::: code +```php Static Config +->testToEmailAddress('me@domain.tld') +``` +```shell Environment Override +CRAFT_TEST_TO_EMAIL_ADDRESS=me@domain.tld +``` +::: + + + +### `timezone` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$timezone](craft4:craft\config\GeneralConfig::$timezone) + +
+ +The timezone of the site. If set, it will take precedence over the Timezone setting in Settings → General. + +This can be set to one of PHP’s [supported timezones](https://php.net/manual/en/timezones.php). + +::: code +```php Static Config +->timezone('Europe/London') +``` +```shell Environment Override +CRAFT_TIMEZONE=Europe/London +``` +::: + + + +### `translationDebugOutput` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$translationDebugOutput](craft4:craft\config\GeneralConfig::$translationDebugOutput) + +
+ +Whether translated messages should be wrapped in special characters to help find any strings that are not being run through +`Craft::t()` or the `|translate` filter. + +::: code +```php Static Config +->translationDebugOutput(true) +``` +```shell Environment Override +CRAFT_TRANSLATION_DEBUG_OUTPUT=1 +``` +::: + + + +### `useEmailAsUsername` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$useEmailAsUsername](craft4:craft\config\GeneralConfig::$useEmailAsUsername) + +
+ +Whether Craft should set users’ usernames to their email addresses, rather than let them set their username separately. + +If you enable this setting after user accounts already exist, run this terminal command to update existing usernames: + +```bash +php craft utils/update-usernames +``` + +::: code +```php Static Config +->useEmailAsUsername(true) +``` +```shell Environment Override +CRAFT_USE_EMAIL_AS_USERNAME=1 +``` +::: + + + +### `useFileLocks` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$useFileLocks](craft4:craft\config\GeneralConfig::$useFileLocks) + +
+ +Whether to grab an exclusive lock on a file when writing to it by using the `LOCK_EX` flag. + +Some file systems, such as NFS, do not support exclusive file locking. + +If `null`, Craft will try to detect if the underlying file system supports exclusive file locking and cache the results. + +::: code +```php Static Config +->useFileLocks(false) +``` +```shell Environment Override +CRAFT_USE_FILE_LOCKS=false +``` +::: + + + +### `useIframeResizer` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$useIframeResizer](craft4:craft\config\GeneralConfig::$useIframeResizer) + +Since +: 3.5.5 + +
+ +Whether [iFrame Resizer options](http://davidjbradshaw.github.io/iframe-resizer/#options) should be used for Live Preview. + +Using iFrame Resizer makes it possible for Craft to retain the preview’s scroll position between page loads, for cross-origin web pages. + +It works by setting the height of the iframe to match the height of the inner web page, and the iframe’s container will be scrolled rather +than the iframe document itself. This can lead to some unexpected CSS issues, however, because the previewed viewport height will be taller +than the visible portion of the iframe. + +If you have a [decoupled front end](https://craftcms.com/docs/4.x/entries.html#previewing-decoupled-front-ends), you will need to include +[iframeResizer.contentWindow.min.js](https://raw.github.com/davidjbradshaw/iframe-resizer/master/js/iframeResizer.contentWindow.min.js) on your +page as well for this to work. You can conditionally include it for only Live Preview requests by checking if the requested URL contains a +`x-craft-live-preview` query string parameter. + +::: tip +You can customize the behavior of iFrame Resizer via the config setting. +::: + +::: code +```php Static Config +->useIframeResizer(true) +``` +```shell Environment Override +CRAFT_USE_IFRAME_RESIZER=1 +``` +::: + + + +## Environment + +### `aliases` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$aliases](craft4:craft\config\GeneralConfig::$aliases) + +
+ +Any custom Yii [aliases](https://www.yiiframework.com/doc/guide/2.0/en/concept-aliases) that should be defined for every request. + +```php Static Config +->aliases([ + '@webroot' => '/var/www/', +]) +``` + + + +### `backupCommand` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null), [false](https://php.net/language.types.boolean) + +Default value +: `null` + +Defined by +: [GeneralConfig::$backupCommand](craft4:craft\config\GeneralConfig::$backupCommand) + +
+ +The shell command that Craft should execute to create a database backup. + +When set to `null` (default), Craft will run `mysqldump` or `pg_dump`, provided that those libraries are in the `$PATH` variable +for the system user running the web server. + +You may provide your own command, which can include several tokens Craft will substitute at runtime: + +- `{file}` - the target backup file path +- `{port}` - the current database port +- `{server}` - the current database hostname +- `{user}` - user that was used to connect to the database +- `{password}` - password for the specified `{user}` +- `{database}` - the current database name +- `{schema}` - the current database schema (if any) + +This can also be set to `false` to disable database backups completely. + +::: code +```php Static Config +->backupCommand(false) +``` +```shell Environment Override +CRAFT_BACKUP_COMMAND=false +``` +::: + + + +### `buildId` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$buildId](craft4:craft\config\GeneralConfig::$buildId) + +Since +: 4.0.0 + +
+ +A unique ID representing the current build of the codebase. + +This should be set to something unique to the deployment, e.g. a Git SHA or a deployment timestamp. + +::: code +```php Static Config +->buildId(\craft\helpers\App::env('GIT_SHA')) +``` +```shell Environment Override +CRAFT_BUILD_ID=$GIT_SHA +``` +::: + + + +### `defaultCookieDomain` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [GeneralConfig::$defaultCookieDomain](craft4:craft\config\GeneralConfig::$defaultCookieDomain) + +
+ +The domain that cookies generated by Craft should be created for. If blank, it will be left up to the browser to determine +which domain to use (almost always the current). If you want the cookies to work for all subdomains, for example, you could +set this to `'.my-project.tld'`. + +::: code +```php Static Config +->defaultCookieDomain('.my-project.tld') +``` +```shell Environment Override +CRAFT_DEFAULT_COOKIE_DOMAIN=.my-project.tld +``` +::: + + + +### `resourceBasePath` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'@webroot/cpresources'` + +Defined by +: [GeneralConfig::$resourceBasePath](craft4:craft\config\GeneralConfig::$resourceBasePath) + +
+ +The path to the root directory that should store published control panel resources. + +::: code +```php Static Config +->resourceBasePath('@webroot/craft-resources') +``` +```shell Environment Override +CRAFT_RESOURCE_BASE_PATH=@webroot/craft-resources +``` +::: + + + +### `resourceBaseUrl` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'@web/cpresources'` + +Defined by +: [GeneralConfig::$resourceBaseUrl](craft4:craft\config\GeneralConfig::$resourceBaseUrl) + +
+ +The URL to the root directory that should store published control panel resources. + +::: code +```php Static Config +->resourceBaseUrl('@web/craft-resources') +``` +```shell Environment Override +CRAFT_RESOURCE_BASE_URL=@web/craft-resources +``` +::: + + + +### `restoreCommand` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null), [false](https://php.net/language.types.boolean) + +Default value +: `null` + +Defined by +: [GeneralConfig::$restoreCommand](craft4:craft\config\GeneralConfig::$restoreCommand) + +
+ +The shell command Craft should execute to restore a database backup. + +By default Craft will run `mysql` or `psql`, provided those libraries are in the `$PATH` variable for the user the web server is running as. + +There are several tokens you can use that Craft will swap out at runtime: + +- `{path}` - the backup file path +- `{port}` - the current database port +- `{server}` - the current database hostname +- `{user}` - the user to connect to the database +- `{database}` - the current database name +- `{schema}` - the current database schema (if any) + +This can also be set to `false` to disable database restores completely. + +::: code +```php Static Config +->restoreCommand(false) +``` +```shell Environment Override +CRAFT_RESTORE_COMMAND=false +``` +::: + + + +## Routing + +### `actionTrigger` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'actions'` + +Defined by +: [GeneralConfig::$actionTrigger](craft4:craft\config\GeneralConfig::$actionTrigger) + +
+ +The URI segment Craft should look for when determining if the current request should be routed to a controller action. + +::: code +```php Static Config +->actionTrigger('do-it') +``` +```shell Environment Override +CRAFT_ACTION_TRIGGER=do-it +``` +::: + + + +### `activateAccountSuccessPath` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$activateAccountSuccessPath](craft4:craft\config\GeneralConfig::$activateAccountSuccessPath) + +
+ +The URI that users without access to the control panel should be redirected to after activating their account. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->activateAccountSuccessPath('welcome') +``` +```shell Environment Override +CRAFT_ACTIVATE_ACCOUNT_SUCCESS_PATH=welcome +``` +::: + + + +### `addTrailingSlashesToUrls` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$addTrailingSlashesToUrls](craft4:craft\config\GeneralConfig::$addTrailingSlashesToUrls) + +
+ +Whether auto-generated URLs should have trailing slashes. + +::: code +```php Static Config +->addTrailingSlashesToUrls(true) +``` +```shell Environment Override +CRAFT_ADD_TRAILING_SLASHES_TO_URLS=1 +``` +::: + + + +### `allowUppercaseInSlug` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$allowUppercaseInSlug](craft4:craft\config\GeneralConfig::$allowUppercaseInSlug) + +
+ +Whether uppercase letters should be allowed in slugs. + +::: code +```php Static Config +->allowUppercaseInSlug(true) +``` +```shell Environment Override +CRAFT_ALLOW_UPPERCASE_IN_SLUG=1 +``` +::: + + + +### `baseCpUrl` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$baseCpUrl](craft4:craft\config\GeneralConfig::$baseCpUrl) + +
+ +The base URL Craft should use when generating control panel URLs. + +It will be determined automatically if left blank. + +::: tip +The base control panel URL should **not** include the [control panel trigger word](config4:cpTrigger) (e.g. `/admin`). +::: + +::: code +```php Static Config +->baseCpUrl(' +``` +```shell Environment Override +CRAFT_BASE_CP_URL=https://cms.my-project.tld/ +``` +::: + + + +### `cpTrigger` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `'admin'` + +Defined by +: [GeneralConfig::$cpTrigger](craft4:craft\config\GeneralConfig::$cpTrigger) + +
+ +The URI segment Craft should look for when determining if the current request should route to the control panel rather than +the front-end website. + +This can be set to `null` if you have a dedicated hostname for the control panel (e.g. `cms.my-project.tld`), or you are running Craft in +[Headless Mode](config4:headlessMode). If you do that, you will need to ensure that the control panel is being served from its own web root +directory on your server, with an `index.php` file that defines the `CRAFT_CP` PHP constant. + +```php +define('CRAFT_CP', true); +``` + +Alternatively, you can set the config setting, but then you will run the risk of losing access to portions of your +control panel due to URI conflicts with actual folders/files in your main web root. + +(For example, if you have an `assets/` folder, that would conflict with the `/assets` page in the control panel.) + +::: code +```php Static Config +->cpTrigger(null) +``` +```shell Environment Override +CRAFT_CP_TRIGGER= +``` +::: + + + +### `invalidUserTokenPath` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$invalidUserTokenPath](craft4:craft\config\GeneralConfig::$invalidUserTokenPath) + +
+ +The URI Craft should redirect to when user token validation fails. A token is used on things like setting and resetting user account +passwords. Note that this only affects front-end site requests. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +// 1 day +->invalidUserTokenPath('nope') +``` +```shell Environment Override +# 1 day +CRAFT_INVALID_USER_TOKEN_PATH=nope +``` +::: + + + +### `loginPath` + +
+ +Allowed types +: `mixed` + +Default value +: `'login'` + +Defined by +: [GeneralConfig::$loginPath](craft4:craft\config\GeneralConfig::$loginPath) + +
+ +The URI Craft should use for user login on the front end. + +This can be set to `false` to disable front-end login. + +Note that this config setting is ignored when is enabled. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->loginPath(false) +``` +```shell Environment Override +CRAFT_LOGIN_PATH=false +``` +::: + + + +### `logoutPath` + +
+ +Allowed types +: `mixed` + +Default value +: `'logout'` + +Defined by +: [GeneralConfig::$logoutPath](craft4:craft\config\GeneralConfig::$logoutPath) + +
+ +The URI Craft should use for user logout on the front end. + +This can be set to `false` to disable front-end logout. + +Note that this config setting is ignored when is enabled. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->logoutPath(false) +``` +```shell Environment Override +CRAFT_LOGOUT_PATH=false +``` +::: + + + +### `omitScriptNameInUrls` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$omitScriptNameInUrls](craft4:craft\config\GeneralConfig::$omitScriptNameInUrls) + +
+ +Whether generated URLs should omit `index.php` (e.g. `http://my-project.tld/path` instead of `http://my-project.tld/index.php/path`) + +This can only be possible if your server is configured to redirect would-be 404s to `index.php`, for example, with the redirect found +in the `.htaccess` file that came with Craft: + +``` +RewriteEngine On +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule (.+) /index.php?p= [QSA,L] +``` + +::: code +```php Static Config +->omitScriptNameInUrls(true) +``` +```shell Environment Override +CRAFT_OMIT_SCRIPT_NAME_IN_URLS=1 +``` +::: + +::: tip +Even when this is set to `true`, the script name could still be included in some action URLs. +If you want to ensure that `index.php` is fully omitted from **all** generated URLs, set the +config setting to `null`. +::: + + + +### `pageTrigger` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'p'` + +Defined by +: [GeneralConfig::$pageTrigger](craft4:craft\config\GeneralConfig::$pageTrigger) + +
+ +The string preceding a number which Craft will look for when determining if the current request is for a particular page in +a paginated list of pages. + +Example Value | Example URI +------------- | ----------- +`p` | `/news/p5` +`page` | `/news/page5` +`page/` | `/news/page/5` +`?page` | `/news?page=5` + +::: tip +If you want to set this to `?p` (e.g. `/news?p=5`), you’ll also need to change your setting which defaults to `p`. +If your server is running Apache, you’ll need to update the redirect code in your `.htaccess` file to match your new `pathParam` value. +::: + +::: code +```php Static Config +->pageTrigger('page') +``` +```shell Environment Override +CRAFT_PAGE_TRIGGER=page +``` +::: + + + +### `pathParam` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `'p'` + +Defined by +: [GeneralConfig::$pathParam](craft4:craft\config\GeneralConfig::$pathParam) + +
+ +The query string param that Craft will check when determining the request’s path. + +This can be set to `null` if your web server is capable of directing traffic to `index.php` without a query string param. +If you’re using Apache, that means you’ll need to change the `RewriteRule` line in your `.htaccess` file to: + +``` +RewriteRule (.+) index.php [QSA,L] +``` + +::: code +```php Static Config +->pathParam(null) +``` +```shell Environment Override +CRAFT_PATH_PARAM= +``` +::: + + + +### `postCpLoginRedirect` + +
+ +Allowed types +: `mixed` + +Default value +: `'dashboard'` + +Defined by +: [GeneralConfig::$postCpLoginRedirect](craft4:craft\config\GeneralConfig::$postCpLoginRedirect) + +
+ +The path users should be redirected to after logging into the control panel. + +This setting will also come into effect if a user visits the control panel’s login page (`/admin/login`) or the control panel’s +root URL (`/admin`) when they are already logged in. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->postCpLoginRedirect('entries') +``` +```shell Environment Override +CRAFT_POST_CP_LOGIN_REDIRECT=entries +``` +::: + + + +### `postLoginRedirect` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$postLoginRedirect](craft4:craft\config\GeneralConfig::$postLoginRedirect) + +
+ +The path users should be redirected to after logging in from the front-end site. + +This setting will also come into effect if the user visits the login page (as specified by the config setting) when +they are already logged in. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->postLoginRedirect('welcome') +``` +```shell Environment Override +CRAFT_POST_LOGIN_REDIRECT=welcome +``` +::: + + + +### `postLogoutRedirect` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$postLogoutRedirect](craft4:craft\config\GeneralConfig::$postLogoutRedirect) + +
+ +The path that users should be redirected to after logging out from the front-end site. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->postLogoutRedirect('goodbye') +``` +```shell Environment Override +CRAFT_POST_LOGOUT_REDIRECT=goodbye +``` +::: + + + +### `setPasswordPath` + +
+ +Allowed types +: `mixed` + +Default value +: `'setpassword'` + +Defined by +: [GeneralConfig::$setPasswordPath](craft4:craft\config\GeneralConfig::$setPasswordPath) + +
+ +The URI or URL that Craft should use for Set Password forms on the front end. + +This setting is ignored when is enabled, unless it’s set to an absolute URL. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: tip +You might also want to set in case a user clicks on an expired password reset link. +::: + +::: code +```php Static Config +->setPasswordPath('set-password') +``` +```shell Environment Override +CRAFT_SET_PASSWORD_PATH=set-password +``` +::: + + + +### `setPasswordRequestPath` + +
+ +Allowed types +: `mixed` + +Default value +: `null` + +Defined by +: [GeneralConfig::$setPasswordRequestPath](craft4:craft\config\GeneralConfig::$setPasswordRequestPath) + +Since +: 3.5.14 + +
+ +The URI to the page where users can request to change their password. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +If this is set, Craft will redirect [.well-known/change-password requests](https://w3c.github.io/webappsec-change-password-url/) to this URI. + +::: tip +You’ll also need to set [setPasswordPath](config4:setPasswordPath), which determines the URI and template path for the Set Password form +where the user resets their password after following the link in the Password Reset email. +::: + +::: code +```php Static Config +->setPasswordRequestPath('request-password') +``` +```shell Environment Override +CRAFT_SET_PASSWORD_REQUEST_PATH=request-password +``` +::: + + + +### `setPasswordSuccessPath` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$setPasswordSuccessPath](craft4:craft\config\GeneralConfig::$setPasswordSuccessPath) + +
+ +The URI Craft should redirect users to after setting their password from the front end. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->setPasswordSuccessPath('password-set') +``` +```shell Environment Override +CRAFT_SET_PASSWORD_SUCCESS_PATH=password-set +``` +::: + + + +### `siteToken` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'siteToken'` + +Defined by +: [GeneralConfig::$siteToken](craft4:craft\config\GeneralConfig::$siteToken) + +Since +: 3.5.0 + +
+ +The query string parameter name that site tokens should be set to. + +::: code +```php Static Config +->siteToken('t') +``` +```shell Environment Override +CRAFT_SITE_TOKEN=t +``` +::: + + + +### `tokenParam` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'token'` + +Defined by +: [GeneralConfig::$tokenParam](craft4:craft\config\GeneralConfig::$tokenParam) + +
+ +The query string parameter name that Craft tokens should be set to. + +::: code +```php Static Config +->tokenParam('t') +``` +```shell Environment Override +CRAFT_TOKEN_PARAM=t +``` +::: + + + +### `usePathInfo` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$usePathInfo](craft4:craft\config\GeneralConfig::$usePathInfo) + +
+ +Whether Craft should specify the path using `PATH_INFO` or as a query string parameter when generating URLs. + +This setting only takes effect if is set to `false`. + +::: code +```php Static Config +->usePathInfo(true) +``` +```shell Environment Override +CRAFT_USE_PATH_INFO=1 +``` +::: + + + +### `useSslOnTokenizedUrls` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean), [string](https://php.net/language.types.string) + +Default value +: `'auto'` + +Defined by +: [GeneralConfig::$useSslOnTokenizedUrls](craft4:craft\config\GeneralConfig::$useSslOnTokenizedUrls) + +
+ +Determines what protocol/schema Craft will use when generating tokenized URLs. If set to `'auto'`, Craft will check the +current site’s base URL and the protocol of the current request and if either of them are HTTPS will use `https` in the tokenized URL. If not, +will use `http`. + +If set to `false`, Craft will always use `http`. If set to `true`, then, Craft will always use `https`. + +::: code +```php Static Config +->useSslOnTokenizedUrls(true) +``` +```shell Environment Override +CRAFT_USE_SSL_ON_TOKENIZED_URLS=1 +``` +::: + + + +### `verifyEmailPath` + +
+ +Allowed types +: `mixed` + +Default value +: `'verifyemail'` + +Defined by +: [GeneralConfig::$verifyEmailPath](craft4:craft\config\GeneralConfig::$verifyEmailPath) + +Since +: 3.4.0 + +
+ +The URI or URL that Craft should use for email verification links on the front end. + +This setting is ignored when is enabled, unless it’s set to an absolute URL. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->verifyEmailPath('verify-email') +``` +```shell Environment Override +CRAFT_VERIFY_EMAIL_PATH=verify-email +``` +::: + + + +### `verifyEmailSuccessPath` + +
+ +Allowed types +: `mixed` + +Default value +: `''` + +Defined by +: [GeneralConfig::$verifyEmailSuccessPath](craft4:craft\config\GeneralConfig::$verifyEmailSuccessPath) + +Since +: 3.1.20 + +
+ +The URI that users without access to the control panel should be redirected to after verifying a new email address. + +See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. + +::: code +```php Static Config +->verifyEmailSuccessPath('verified-email') +``` +```shell Environment Override +CRAFT_VERIFY_EMAIL_SUCCESS_PATH=verified-email +``` +::: + + + +## Session + +### `phpSessionName` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'CraftSessionId'` + +Defined by +: [GeneralConfig::$phpSessionName](craft4:craft\config\GeneralConfig::$phpSessionName) + +
+ +The name of the PHP session cookie. + +::: code +```php Static Config +->phpSessionName(null) +``` +```shell Environment Override +CRAFT_PHP_SESSION_NAME= +``` +::: + + + +### `rememberUsernameDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `31536000` (1 year) + +Defined by +: [GeneralConfig::$rememberUsernameDuration](craft4:craft\config\GeneralConfig::$rememberUsernameDuration) + +
+ +The amount of time Craft will remember a username and pre-populate it on the control panel’s Login page. + +Set to `0` to disable this feature altogether. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +->rememberUsernameDuration(0) +``` +```shell Environment Override +CRAFT_REMEMBER_USERNAME_DURATION=0 +``` +::: + + + +### `rememberedUserSessionDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `1209600` (14 days) + +Defined by +: [GeneralConfig::$rememberedUserSessionDuration](craft4:craft\config\GeneralConfig::$rememberedUserSessionDuration) + +
+ +The amount of time a user stays logged if “Remember Me” is checked on the login page. + +Set to `0` to disable the “Remember Me” feature altogether. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +->rememberedUserSessionDuration(0) +``` +```shell Environment Override +CRAFT_REMEMBERED_USER_SESSION_DURATION=0 +``` +::: + + + +### `requireMatchingUserAgentForSession` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$requireMatchingUserAgentForSession](craft4:craft\config\GeneralConfig::$requireMatchingUserAgentForSession) + +
+ +Whether Craft should require a matching user agent string when restoring a user session from a cookie. + +::: code +```php Static Config +->requireMatchingUserAgentForSession(false) +``` +```shell Environment Override +CRAFT_REQUIRE_MATCHING_USER_AGENT_FOR_SESSION=false +``` +::: + + + +### `requireUserAgentAndIpForSession` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$requireUserAgentAndIpForSession](craft4:craft\config\GeneralConfig::$requireUserAgentAndIpForSession) + +
+ +Whether Craft should require the existence of a user agent string and IP address when creating a new user session. + +::: code +```php Static Config +->requireUserAgentAndIpForSession(false) +``` +```shell Environment Override +CRAFT_REQUIRE_USER_AGENT_AND_IP_FOR_SESSION=false +``` +::: + + + +### `userSessionDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `3600` (1 hour) + +Defined by +: [GeneralConfig::$userSessionDuration](craft4:craft\config\GeneralConfig::$userSessionDuration) + +
+ +The amount of time before a user will get logged out due to inactivity. + +Set to `0` if you want users to stay logged in as long as their browser is open rather than a predetermined amount of time. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +// 3 hours +->userSessionDuration(10800) +``` +```shell Environment Override +# 3 hours +CRAFT_USER_SESSION_DURATION=10800 +``` +::: + + + +## Security + +### `blowfishHashCost` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `13` + +Defined by +: [GeneralConfig::$blowfishHashCost](craft4:craft\config\GeneralConfig::$blowfishHashCost) + +
+ +The higher the cost value, the longer it takes to generate a password hash and to verify against it. + +Therefore, higher cost slows down a brute-force attack. + +For best protection against brute force attacks, set it to the highest value that is tolerable on production servers. + +The time taken to compute the hash doubles for every increment by one for this value. + +For example, if the hash takes 1 second to compute when the value is 14 then the compute time varies as +2^(value - 14) seconds. + +::: code +```php Static Config +->blowfishHashCost(15) +``` +```shell Environment Override +CRAFT_BLOWFISH_HASH_COST=15 +``` +::: + + + +### `cooldownDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `300` (5 minutes) + +Defined by +: [GeneralConfig::$cooldownDuration](craft4:craft\config\GeneralConfig::$cooldownDuration) + +
+ +The amount of time a user must wait before re-attempting to log in after their account is locked due to too many +failed login attempts. + +Set to `0` to keep the account locked indefinitely, requiring an admin to manually unlock the account. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +->cooldownDuration(0) +``` +```shell Environment Override +CRAFT_COOLDOWN_DURATION=0 +``` +::: + + + +### `csrfTokenName` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'CRAFT_CSRF_TOKEN'` + +Defined by +: [GeneralConfig::$csrfTokenName](craft4:craft\config\GeneralConfig::$csrfTokenName) + +
+ +The name of CSRF token used for CSRF validation if is set to `true`. + +::: code +```php Static Config +->csrfTokenName('MY_CSRF') +``` +```shell Environment Override +CRAFT_CSRF_TOKEN_NAME=MY_CSRF +``` +::: + + + +### `defaultTokenDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `86400` (1 day) + +Defined by +: [GeneralConfig::$defaultTokenDuration](craft4:craft\config\GeneralConfig::$defaultTokenDuration) + +
+ +The default amount of time tokens can be used before expiring. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +// One week +->defaultTokenDuration(604800) +``` +```shell Environment Override +# One week +CRAFT_DEFAULT_TOKEN_DURATION=604800 +``` +::: + + + +### `deferPublicRegistrationPassword` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$deferPublicRegistrationPassword](craft4:craft\config\GeneralConfig::$deferPublicRegistrationPassword) + +
+ +By default, Craft requires a front-end “password” field for public user registrations. Setting this to `true` +removes that requirement for the initial registration form. + +If you have email verification enabled, new users will set their password once they’ve followed the verification link in the email. +If you don’t, the only way they can set their password is to go through your “forgot password” workflow. + +::: code +```php Static Config +->deferPublicRegistrationPassword(true) +``` +```shell Environment Override +CRAFT_DEFER_PUBLIC_REGISTRATION_PASSWORD=true +``` +::: + + + +### `elevatedSessionDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `300` (5 minutes) + +Defined by +: [GeneralConfig::$elevatedSessionDuration](craft4:craft\config\GeneralConfig::$elevatedSessionDuration) + +
+ +The amount of time a user’s elevated session will last, which is required for some sensitive actions (e.g. user group/permission assignment). + +Set to `0` to disable elevated session support. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +->elevatedSessionDuration(0) +``` +```shell Environment Override +CRAFT_ELEVATED_SESSION_DURATION=0 +``` +::: + + + +### `enableBasicHttpAuth` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$enableBasicHttpAuth](craft4:craft\config\GeneralConfig::$enableBasicHttpAuth) + +Since +: 3.5.0 + +
+ +Whether front-end web requests should support basic HTTP authentication. + +::: code +```php Static Config +->enableBasicHttpAuth(true) +``` +```shell Environment Override +CRAFT_ENABLE_BASIC_HTTP_AUTH=1 +``` +::: + + + +### `enableCsrfCookie` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableCsrfCookie](craft4:craft\config\GeneralConfig::$enableCsrfCookie) + +
+ +Whether to use a cookie to persist the CSRF token if is enabled. If false, the CSRF token will be +stored in session under the `csrfTokenName` config setting name. Note that while storing CSRF tokens in session increases security, +it requires starting a session for every page that a CSRF token is needed, which may degrade site performance. + +::: code +```php Static Config +->enableCsrfCookie(false) +``` +```shell Environment Override +CRAFT_ENABLE_CSRF_COOKIE=false +``` +::: + + + +### `enableCsrfProtection` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableCsrfProtection](craft4:craft\config\GeneralConfig::$enableCsrfProtection) + +
+ +Whether to enable CSRF protection via hidden form inputs for all forms submitted via Craft. + +::: code +```php Static Config +->enableCsrfProtection(false) +``` +```shell Environment Override +CRAFT_ENABLE_CSRF_PROTECTION=false +``` +::: + + + +### `invalidLoginWindowDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `3600` (1 hour) + +Defined by +: [GeneralConfig::$invalidLoginWindowDuration](craft4:craft\config\GeneralConfig::$invalidLoginWindowDuration) + +
+ +The amount of time to track invalid login attempts for a user, for determining if Craft should lock an account. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +// 1 day +->invalidLoginWindowDuration(86400) +``` +```shell Environment Override +# 1 day +CRAFT_INVALID_LOGIN_WINDOW_DURATION=86400 +``` +::: + + + +### `maxInvalidLogins` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [false](https://php.net/language.types.boolean) + +Default value +: `5` + +Defined by +: [GeneralConfig::$maxInvalidLogins](craft4:craft\config\GeneralConfig::$maxInvalidLogins) + +
+ +The number of invalid login attempts Craft will allow within the specified duration before the account gets locked. + +::: code +```php Static Config +->maxInvalidLogins(3) +``` +```shell Environment Override +CRAFT_MAX_INVALID_LOGINS=3 +``` +::: + + + +### `preventUserEnumeration` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$preventUserEnumeration](craft4:craft\config\GeneralConfig::$preventUserEnumeration) + +
+ +When `true`, Craft will always return a successful response in the “forgot password” flow, making it difficult to enumerate users. + +When set to `false` and you go through the “forgot password” flow from the control panel login page, you’ll get distinct messages indicating +whether the username/email exists and whether an email was sent with further instructions. This can be helpful for the user attempting to +log in but allow for username/email enumeration based on the response. + +::: code +```php Static Config +->preventUserEnumeration(true) +``` +```shell Environment Override +CRAFT_PREVENT_USER_ENUMERATION=1 +``` +::: + + + +### `previewTokenDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `null` (1 day) + +Defined by +: [GeneralConfig::$previewTokenDuration](craft4:craft\config\GeneralConfig::$previewTokenDuration) + +Since +: 3.7.0 + +
+ +The amount of time content preview tokens can be used before expiring. + +Defaults to value. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +// 1 hour +->previewTokenDuration(3600) +``` +```shell Environment Override +# 1 hour +CRAFT_PREVIEW_TOKEN_DURATION=3600 +``` +::: + + + +### `sanitizeCpImageUploads` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$sanitizeCpImageUploads](craft4:craft\config\GeneralConfig::$sanitizeCpImageUploads) + +Since +: 3.6.0 + +
+ +Whether images uploaded via the control panel should be sanitized. + +::: code +```php Static Config +->sanitizeCpImageUploads(false) +``` +```shell Environment Override +CRAFT_SANITIZE_CP_IMAGE_UPLOADS=false +``` +::: + + + +### `sanitizeSvgUploads` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$sanitizeSvgUploads](craft4:craft\config\GeneralConfig::$sanitizeSvgUploads) + +
+ +Whether Craft should sanitize uploaded SVG files and strip out potential malicious-looking content. + +This should definitely be enabled if you are accepting SVG uploads from untrusted sources. + +::: code +```php Static Config +->sanitizeSvgUploads(false) +``` +```shell Environment Override +CRAFT_SANITIZE_SVG_UPLOADS=false +``` +::: + + + +### `secureHeaders` + +
+ +Allowed types +: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$secureHeaders](craft4:craft\config\GeneralConfig::$secureHeaders) + +
+ +Lists of headers that are, by default, subject to the trusted host configuration. + +See [yii\web\Request::$secureHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureHeaders-detail) for more details. + +If not set, the default [yii\web\Request::$secureHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureHeaders-detail) value will be used. + +::: code +```php Static Config +->secureHeaders([ + 'X-Forwarded-For', + 'X-Forwarded-Host', + 'X-Forwarded-Proto', + 'X-Rewrite-Url', + 'X-Original-Host', + 'CF-Connecting-IP', +]) +``` +```shell Environment Override +CRAFT_SECURE_HEADERS=X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Proto,X-Rewrite-Url,X-Original-Host,CF-Connecting-IP +``` +::: + + + +### `secureProtocolHeaders` + +
+ +Allowed types +: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$secureProtocolHeaders](craft4:craft\config\GeneralConfig::$secureProtocolHeaders) + +
+ +List of headers to check for determining whether the connection is made via HTTPS. + +See [yii\web\Request::$secureProtocolHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureProtocolHeaders-detail) for more details. + +If not set, the default [yii\web\Request::$secureProtocolHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureProtocolHeaders-detail) value will be used. + +```php Static Config +->secureProtocolHeaders([ + 'X-Forwarded-Proto' => [ + 'https', + ], + 'Front-End-Https' => [ + 'on', + ], + 'CF-Visitor' => [ + '{\"scheme\":\"https\"}', + ], +]) +``` + + + +### `securityKey` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [GeneralConfig::$securityKey](craft4:craft\config\GeneralConfig::$securityKey) + +
+ +A private, random, cryptographically-secure key that is used for hashing and encrypting data in [craft\services\Security](craft4:craft\services\Security). + +This value should be the same across all environments. If this key ever changes, any data that was encrypted with it will be inaccessible. + +```php Static Config +->securityKey('2cf24dba5...') +``` + + + +### `storeUserIps` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$storeUserIps](craft4:craft\config\GeneralConfig::$storeUserIps) + +Since +: 3.1.0 + +
+ +Whether user IP addresses should be stored/logged by the system. + +::: code +```php Static Config +->storeUserIps(true) +``` +```shell Environment Override +CRAFT_STORE_USER_IPS=1 +``` +::: + + + +### `trustedHosts` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[ + 'any', +]` + +Defined by +: [GeneralConfig::$trustedHosts](craft4:craft\config\GeneralConfig::$trustedHosts) + +
+ +The configuration for trusted security-related headers. + +See [yii\web\Request::$trustedHosts](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$trustedHosts-detail) for more details. + +By default, all hosts are trusted. + +::: code +```php Static Config +->trustedHosts(['trusted-one.foo', 'trusted-two.foo']) +``` +```shell Environment Override +CRAFT_TRUSTED_HOSTS=trusted-one.foo,trusted-two.foo +``` +::: + + + +### `useSecureCookies` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean), [string](https://php.net/language.types.string) + +Default value +: `'auto'` + +Defined by +: [GeneralConfig::$useSecureCookies](craft4:craft\config\GeneralConfig::$useSecureCookies) + +
+ +Whether Craft will set the “secure” flag when saving cookies when using `Craft::cookieConfig()` to create a cookie. + +Valid values are `true`, `false`, and `'auto'`. Defaults to `'auto'`, which will set the secure flag if the page you’re currently accessing +is over `https://`. `true` will always set the flag, regardless of protocol and `false` will never automatically set the flag. + +::: code +```php Static Config +->useSecureCookies(true) +``` +```shell Environment Override +CRAFT_USE_SECURE_COOKIES=1 +``` +::: + + + +### `verificationCodeDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `86400` (1 day) + +Defined by +: [GeneralConfig::$verificationCodeDuration](craft4:craft\config\GeneralConfig::$verificationCodeDuration) + +
+ +The amount of time a user verification code can be used before expiring. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +// 1 hour +->verificationCodeDuration(3600) +``` +```shell Environment Override +# 1 hour +CRAFT_VERIFICATION_CODE_DURATION=3600 +``` +::: + + + +## Assets + +### `allowedFileExtensions` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[ + '7z', + 'aiff', + 'asc', + 'asf', + 'avi', + 'avif', + 'bmp', + 'cap', + 'cin', + 'csv', + 'dfxp', + 'doc', + 'docx', + 'dotm', + 'dotx', + 'fla', + 'flv', + 'gif', + 'gz', + 'gzip', + 'heic', + 'heif', + 'hevc', + 'itt', + 'jp2', + 'jpeg', + 'jpg', + 'jpx', + 'js', + 'json', + 'lrc', + 'm2t', + 'm4a', + 'm4v', + 'mcc', + 'mid', + 'mov', + 'mp3', + 'mp4', + 'mpc', + 'mpeg', + 'mpg', + 'mpsub', + 'ods', + 'odt', + 'ogg', + 'ogv', + 'pdf', + 'png', + 'potx', + 'pps', + 'ppsm', + 'ppsx', + 'ppt', + 'pptm', + 'pptx', + 'ppz', + 'pxd', + 'qt', + 'ram', + 'rar', + 'rm', + 'rmi', + 'rmvb', + 'rt', + 'rtf', + 'sami', + 'sbv', + 'scc', + 'sdc', + 'sitd', + 'smi', + 'srt', + 'stl', + 'sub', + 'svg', + 'swf', + 'sxc', + 'sxw', + 'tar', + 'tds', + 'tgz', + 'tif', + 'tiff', + 'ttml', + 'txt', + 'vob', + 'vsd', + 'vtt', + 'wav', + 'webm', + 'webp', + 'wma', + 'wmv', + 'xls', + 'xlsx', + 'zip', +]` + +Defined by +: [GeneralConfig::$allowedFileExtensions](craft4:craft\config\GeneralConfig::$allowedFileExtensions) + +
+ +The file extensions Craft should allow when a user is uploading files. + +```php Static Config +// Nothing bug GIFs! +->allowedFileExtensions([ + 'gif', +]) +``` + + + +### `convertFilenamesToAscii` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$convertFilenamesToAscii](craft4:craft\config\GeneralConfig::$convertFilenamesToAscii) + +
+ +Whether uploaded filenames with non-ASCII characters should be converted to ASCII (i.e. `ñ` → `n`). + +::: tip +You can run `php craft utils/ascii-filenames` in your terminal to apply ASCII filenames to all existing assets. +::: + +::: code +```php Static Config +->convertFilenamesToAscii(false) +``` +```shell Environment Override +CRAFT_CONVERT_FILENAMES_TO_ASCII=false +``` +::: + + + +### `extraFileKinds` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[]` + +Defined by +: [GeneralConfig::$extraFileKinds](craft4:craft\config\GeneralConfig::$extraFileKinds) + +Since +: 3.0.37 + +
+ +List of additional file kinds Craft should support. This array will get merged with the one defined in +`\craft\helpers\Assets::_buildFileKinds()`. + +```php Static Config +->extraFileKinds([ + // merge .psb into list of Photoshop file kinds + 'photoshop' => [ + 'extensions' => ['psb'], + ], + // register new "Stylesheet" file kind + 'stylesheet' => [ + 'label' => 'Stylesheet', + 'extensions' => ['css', 'less', 'pcss', 'sass', 'scss', 'styl'], + ], +]) +``` + +::: tip +File extensions listed here won’t immediately be allowed to be uploaded. You will also need to list them with +the config setting. +::: + + + +### `filenameWordSeparator` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [false](https://php.net/language.types.boolean) + +Default value +: `'-'` + +Defined by +: [GeneralConfig::$filenameWordSeparator](craft4:craft\config\GeneralConfig::$filenameWordSeparator) + +
+ +The string to use to separate words when uploading assets. If set to `false`, spaces will be left alone. + +::: code +```php Static Config +->filenameWordSeparator(false) +``` +```shell Environment Override +CRAFT_FILENAME_WORD_SEPARATOR=false +``` +::: + + + +### `maxUploadFileSize` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer), [string](https://php.net/language.types.string) + +Default value +: `16777216` (16MB) + +Defined by +: [GeneralConfig::$maxUploadFileSize](craft4:craft\config\GeneralConfig::$maxUploadFileSize) + +
+ +The maximum upload file size allowed. + +See [craft\helpers\ConfigHelper::sizeInBytes()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-sizeinbytes) for a list of supported value types. + +::: code +```php Static Config +// 25MB +->maxUploadFileSize(26214400) +``` +```shell Environment Override +# 25MB +CRAFT_MAX_UPLOAD_FILE_SIZE=26214400 +``` +::: + + + +### `revAssetUrls` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$revAssetUrls](craft4:craft\config\GeneralConfig::$revAssetUrls) + +Since +: 3.7.0 + +
+ +Whether asset URLs should be revved so browsers don’t load cached versions when they’re modified. + +::: code +```php Static Config +->revAssetUrls(true) +``` +```shell Environment Override +CRAFT_REV_ASSET_URLS=1 +``` +::: + + + +## Image Handling + +### `brokenImagePath` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [GeneralConfig::$brokenImagePath](craft4:craft\config\GeneralConfig::$brokenImagePath) + +Since +: 3.5.0 + +
+ +The server path to an image file that should be sent when responding to an image request with a +404 status code. + +This can be set to an aliased path such as `@webroot/assets/404.svg`. + +::: code +```php Static Config +->brokenImagePath('@webroot/assets/404.svg') +``` +```shell Environment Override +CRAFT_BROKEN_IMAGE_PATH=@webroot/assets/404.svg +``` +::: + + + +### `defaultImageQuality` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `82` + +Defined by +: [GeneralConfig::$defaultImageQuality](craft4:craft\config\GeneralConfig::$defaultImageQuality) + +
+ +The quality level Craft will use when saving JPG and PNG files. Ranges from 1 (worst quality, smallest file) to +100 (best quality, biggest file). + +::: code +```php Static Config +->defaultImageQuality(90) +``` +```shell Environment Override +CRAFT_DEFAULT_IMAGE_QUALITY=90 +``` +::: + + + +### `generateTransformsBeforePageLoad` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$generateTransformsBeforePageLoad](craft4:craft\config\GeneralConfig::$generateTransformsBeforePageLoad) + +
+ +Whether image transforms should be generated before page load. + +::: code +```php Static Config +->generateTransformsBeforePageLoad(true) +``` +```shell Environment Override +CRAFT_GENERATE_TRANSFORMS_BEFORE_PAGE_LOAD=1 +``` +::: + + + +### `imageDriver` + +
+ +Allowed types +: `mixed` + +Default value +: `GeneralConfig::IMAGE_DRIVER_AUTO` + +Defined by +: [GeneralConfig::$imageDriver](craft4:craft\config\GeneralConfig::$imageDriver) + +
+ +The image driver Craft should use to cleanse and transform images. By default Craft will use ImageMagick if it’s installed +and otherwise fall back to GD. You can explicitly set either `'imagick'` or `'gd'` here to override that behavior. + +::: code +```php Static Config +->imageDriver('imagick') +``` +```shell Environment Override +CRAFT_IMAGE_DRIVER=imagick +``` +::: + + + +### `imageEditorRatios` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `[ + 'Unconstrained' => 'none', + 'Original' => 'original', + 'Square' => 1, + '16:9' => 1.78, + '10:8' => 1.25, + '7:5' => 1.4, + '4:3' => 1.33, + '5:3' => 1.67, + '3:2' => 1.5, +]` + +Defined by +: [GeneralConfig::$imageEditorRatios](craft4:craft\config\GeneralConfig::$imageEditorRatios) + +
+ +An array containing the selectable image aspect ratios for the image editor. The array must be in the format +of `label` => `ratio`, where ratio must be a float or a string. For string values, only values of “none” and “original” are allowed. + +```php Static Config +->imageEditorRatios([ + 'Unconstrained' => 'none', + 'Original' => 'original', + 'Square' => 1, + 'IMAX' => 1.9, + 'Widescreen' => 1.78, +]) +``` + + + +### `maxCachedCloudImageSize` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `2000` + +Defined by +: [GeneralConfig::$maxCachedCloudImageSize](craft4:craft\config\GeneralConfig::$maxCachedCloudImageSize) + +
+ +The maximum dimension size to use when caching images from external sources to use in transforms. Set to `0` to never cache them. + +::: code +```php Static Config +->maxCachedCloudImageSize(0) +``` +```shell Environment Override +CRAFT_MAX_CACHED_CLOUD_IMAGE_SIZE=0 +``` +::: + + + +### `optimizeImageFilesize` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$optimizeImageFilesize](craft4:craft\config\GeneralConfig::$optimizeImageFilesize) + +
+ +Whether Craft should optimize images for reduced file sizes without noticeably reducing image quality. (Only supported when +ImageMagick is used.) + +::: code +```php Static Config +->optimizeImageFilesize(false) +``` +```shell Environment Override +CRAFT_OPTIMIZE_IMAGE_FILESIZE=1 +``` +::: + + + +### `preserveCmykColorspace` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$preserveCmykColorspace](craft4:craft\config\GeneralConfig::$preserveCmykColorspace) + +Since +: 3.0.8 + +
+ +Whether CMYK should be preserved as the colorspace when manipulating images. + +Setting this to `true` will prevent Craft from transforming CMYK images to sRGB, but on some ImageMagick versions it can cause +image color distortion. This will only have an effect if ImageMagick is in use. + +::: code +```php Static Config +->preserveCmykColorspace(true) +``` +```shell Environment Override +CRAFT_PRESERVE_CMYK_COLORSPACE=1 +``` +::: + + + +### `preserveExifData` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$preserveExifData](craft4:craft\config\GeneralConfig::$preserveExifData) + +
+ +Whether the EXIF data should be preserved when manipulating and uploading images. + +Setting this to `true` will result in larger image file sizes. + +This will only have effect if ImageMagick is in use. + +::: code +```php Static Config +->preserveExifData(true) +``` +```shell Environment Override +CRAFT_PRESERVE_EXIF_DATA=1 +``` +::: + + + +### `preserveImageColorProfiles` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$preserveImageColorProfiles](craft4:craft\config\GeneralConfig::$preserveImageColorProfiles) + +
+ +Whether the embedded Image Color Profile (ICC) should be preserved when manipulating images. + +Setting this to `false` will reduce the image size a little bit, but on some ImageMagick versions can cause images to be saved with +an incorrect gamma value, which causes the images to become very dark. This will only have effect if ImageMagick is in use. + +::: code +```php Static Config +->preserveImageColorProfiles(false) +``` +```shell Environment Override +CRAFT_PRESERVE_IMAGE_COLOR_PROFILES=false +``` +::: + + + +### `rasterizeSvgThumbs` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$rasterizeSvgThumbs](craft4:craft\config\GeneralConfig::$rasterizeSvgThumbs) + +Since +: 3.6.0 + +
+ +Whether SVG thumbnails should be rasterized. + +This will only work if ImageMagick is installed, and is set to either `auto` or `imagick`. + +::: code +```php Static Config +->rasterizeSvgThumbs(true) +``` +```shell Environment Override +CRAFT_RASTERIZE_SVG_THUMBS=1 +``` +::: + + + +### `rotateImagesOnUploadByExifData` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$rotateImagesOnUploadByExifData](craft4:craft\config\GeneralConfig::$rotateImagesOnUploadByExifData) + +
+ +Whether Craft should rotate images according to their EXIF data on upload. + +::: code +```php Static Config +->rotateImagesOnUploadByExifData(false) +``` +```shell Environment Override +CRAFT_ROTATE_IMAGES_ON_UPLOAD_BY_EXIF_DATA=false +``` +::: + + + +### `transformGifs` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$transformGifs](craft4:craft\config\GeneralConfig::$transformGifs) + +Since +: 3.0.7 + +
+ +Whether GIF files should be cleansed/transformed. + +::: code +```php Static Config +->transformGifs(false) +``` +```shell Environment Override +CRAFT_TRANSFORM_GIFS=false +``` +::: + + + +### `transformSvgs` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$transformSvgs](craft4:craft\config\GeneralConfig::$transformSvgs) + +Since +: 3.7.1 + +
+ +Whether SVG files should be transformed. + +::: code +```php Static Config +->transformSvgs(false) +``` +```shell Environment Override +CRAFT_TRANSFORM_SVGS=false +``` +::: + + + +### `upscaleImages` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$upscaleImages](craft4:craft\config\GeneralConfig::$upscaleImages) + +Since +: 3.4.0 + +
+ +Whether image transforms should allow upscaling by default, for images that are smaller than the transform dimensions. + +::: code +```php Static Config +->upscaleImages(false) +``` +```shell Environment Override +CRAFT_UPSCALE_IMAGES=false +``` +::: + + + +## GraphQL + +### `allowedGraphqlOrigins` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null), [false](https://php.net/language.types.boolean) + +Default value +: `null` + +Defined by +: [GeneralConfig::$allowedGraphqlOrigins](craft4:craft\config\GeneralConfig::$allowedGraphqlOrigins) + +Since +: 3.5.0 + +
+ +The Ajax origins that should be allowed to access the GraphQL API, if enabled. + +If this is set to an array, then `graphql/api` requests will only include the current request’s [origin](https://www.yiiframework.com/doc/api/2.0/yii-web-request#getOrigin()-detail) +in the `Access-Control-Allow-Origin` response header if it’s listed here. + +If this is set to `false`, then the `Access-Control-Allow-Origin` response header will never be sent. + +::: code +```php Static Config +->allowedGraphqlOrigins(false) +``` +```shell Environment Override +CRAFT_ALLOW_GRAPHQL_ORIGINS=false +``` +::: + + + +### `disableGraphqlTransformDirective` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$disableGraphqlTransformDirective](craft4:craft\config\GeneralConfig::$disableGraphqlTransformDirective) + +Since +: 3.6.0 + +
+ +Whether the `transform` directive should be disabled for the GraphQL API. + +::: code +```php Static Config +->disableGraphqlTransformDirective(true) +``` +```shell Environment Override +CRAFT_DISABLE_GRAPHQL_TRANSFORM_DIRECTIVE=1 +``` +::: + + + +### `enableGql` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableGql](craft4:craft\config\GeneralConfig::$enableGql) + +Since +: 3.3.1 + +
+ +Whether the GraphQL API should be enabled. + +The GraphQL API is only available for Craft Pro. + +::: code +```php Static Config +->enableGql(false) +``` +```shell Environment Override +CRAFT_ENABLE_GQL=false +``` +::: + + + +### `enableGraphqlCaching` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableGraphqlCaching](craft4:craft\config\GeneralConfig::$enableGraphqlCaching) + +Since +: 3.3.12 + +
+ +Whether Craft should cache GraphQL queries. + +If set to `true`, Craft will cache the results for unique GraphQL queries per access token. The cache is automatically invalidated any time +an element is saved, the site structure is updated, or a GraphQL schema is saved. + +This setting will have no effect if a plugin is using the [craft\services\Gql::EVENT_BEFORE_EXECUTE_GQL_QUERY](https://docs.craftcms.com/api/v4/craft-services-gql.html#event-before-execute-gql-query) event to provide its own +caching logic and setting the `result` property. + +::: code +```php Static Config +->enableGraphqlCaching(false) +``` +```shell Environment Override +CRAFT_ENABLE_GRAPHQL_CACHING=false +``` +::: + + + +### `enableGraphqlIntrospection` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$enableGraphqlIntrospection](craft4:craft\config\GeneralConfig::$enableGraphqlIntrospection) + +Since +: 3.6.0 + +
+ +Whether GraphQL introspection queries are allowed. Defaults to `true` and is always allowed in the control panel. + +::: code +```php Static Config +->enableGraphqlIntrospection(false) +``` +```shell Environment Override +CRAFT_ENABLE_GRAPHQL_INTROSPECTION=false +``` +::: + + + +### `gqlTypePrefix` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [GeneralConfig::$gqlTypePrefix](craft4:craft\config\GeneralConfig::$gqlTypePrefix) + +
+ +Prefix to use for all type names returned by GraphQL. + +::: code +```php Static Config +->gqlTypePrefix('craft_') +``` +```shell Environment Override +CRAFT_GQL_TYPE_PREFIX=craft_ +``` +::: + + + +### `maxGraphqlBatchSize` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `0` + +Defined by +: [GeneralConfig::$maxGraphqlBatchSize](craft4:craft\config\GeneralConfig::$maxGraphqlBatchSize) + +Since +: 4.5.5 + +
+ +The maximum allowed GraphQL queries that can be executed in a single batched request. Set to `0` to allow any number of queries. + +::: code +```php Static Config +->maxGraphqlBatchSize(5) +``` +```shell Environment Override +CRAFT_MAX_GRAPHQL_BATCH_SIZE=5 +``` +::: + + + +### `maxGraphqlComplexity` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `0` + +Defined by +: [GeneralConfig::$maxGraphqlComplexity](craft4:craft\config\GeneralConfig::$maxGraphqlComplexity) + +Since +: 3.6.0 + +
+ +The maximum allowed complexity a GraphQL query is allowed to have. Set to `0` to allow any complexity. + +::: code +```php Static Config +->maxGraphqlComplexity(500) +``` +```shell Environment Override +CRAFT_MAX_GRAPHQL_COMPLEXITY=500 +``` +::: + + + +### `maxGraphqlDepth` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `0` + +Defined by +: [GeneralConfig::$maxGraphqlDepth](craft4:craft\config\GeneralConfig::$maxGraphqlDepth) + +Since +: 3.6.0 + +
+ +The maximum allowed depth a GraphQL query is allowed to reach. Set to `0` to allow any depth. + +::: code +```php Static Config +->maxGraphqlDepth(5) +``` +```shell Environment Override +CRAFT_MAX_GRAPHQL_DEPTH=5 +``` +::: + + + +### `maxGraphqlResults` + +
+ +Allowed types +: [integer](https://php.net/language.types.integer) + +Default value +: `0` + +Defined by +: [GeneralConfig::$maxGraphqlResults](craft4:craft\config\GeneralConfig::$maxGraphqlResults) + +Since +: 3.6.0 + +
+ +The maximum allowed results for a single GraphQL query. Set to `0` to disable any limits. + +::: code +```php Static Config +->maxGraphqlResults(100) +``` +```shell Environment Override +CRAFT_MAX_GRAPHQL_RESULTS=100 +``` +::: + + + +### `prefixGqlRootTypes` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [GeneralConfig::$prefixGqlRootTypes](craft4:craft\config\GeneralConfig::$prefixGqlRootTypes) + +Since +: 3.6.6 + +
+ +Whether the config setting should have an impact on `query`, `mutation`, and `subscription` types. + +::: code +```php Static Config +->prefixGqlRootTypes(false) +``` +```shell Environment Override +CRAFT_PREFIX_GQL_ROOT_TYPES=false +``` +::: + + + +### `setGraphqlDatesToSystemTimeZone` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$setGraphqlDatesToSystemTimeZone](craft4:craft\config\GeneralConfig::$setGraphqlDatesToSystemTimeZone) + +Since +: 3.7.0 + +
+ +Whether dates returned by the GraphQL API should be set to the system time zone by default, rather than UTC. + +::: code +```php Static Config +->setGraphqlDatesToSystemTimeZone(true) +``` +```shell Environment Override +CRAFT_SET_GRAPHQL_DATES_TO_SYSTEM_TIMEZONE=1 +``` +::: + + + +## Garbage Collection + +### `purgePendingUsersDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `0` + +Defined by +: [GeneralConfig::$purgePendingUsersDuration](craft4:craft\config\GeneralConfig::$purgePendingUsersDuration) + +
+ +The amount of time to wait before Craft purges pending users from the system that have not activated. + +Any content assigned to a pending user will be deleted as well when the given time interval passes. + +Set to `0` to disable this feature. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: tip +Users will only be purged when [garbage collection](https://craftcms.com/docs/4.x/gc.html) is run. +::: + +::: code +```php Static Config +// 2 weeks +->purgePendingUsersDuration(1209600) +``` +```shell Environment Override +# 2 weeks +CRAFT_PURGE_PENDING_USERS_DURATION=1209600 +``` +::: + + + +### `purgeStaleUserSessionDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `7776000` (90 days) + +Defined by +: [GeneralConfig::$purgeStaleUserSessionDuration](craft4:craft\config\GeneralConfig::$purgeStaleUserSessionDuration) + +Since +: 3.3.0 + +
+ +The amount of time to wait before Craft purges stale user sessions from the sessions table in the database. + +Set to `0` to disable this feature. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +// 1 week +->purgeStaleUserSessionDuration(604800) +``` +```shell Environment Override +# 1 week +CRAFT_PURGE_STALE_USER_SESSION_DURATION=604800 +``` +::: + + + +### `purgeUnsavedDraftsDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `2592000` (30 days) + +Defined by +: [GeneralConfig::$purgeUnsavedDraftsDuration](craft4:craft\config\GeneralConfig::$purgeUnsavedDraftsDuration) + +Since +: 3.2.0 + +
+ +The amount of time to wait before Craft purges unpublished drafts that were never updated with content. + +Set to `0` to disable this feature. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +->purgeUnsavedDraftsDuration(0) +``` +```shell Environment Override +CRAFT_PURGE_UNSAVED_DRAFTS_DURATION=0 +``` +::: + + + +### `softDeleteDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `2592000` (30 days) + +Defined by +: [GeneralConfig::$softDeleteDuration](craft4:craft\config\GeneralConfig::$softDeleteDuration) + +Since +: 3.1.0 + +
+ +The amount of time before a soft-deleted item will be up for hard-deletion by garbage collection. + +Set to `0` if you don’t ever want to delete soft-deleted items. + +See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v4/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. + +::: code +```php Static Config +->softDeleteDuration(0) +``` +```shell Environment Override +CRAFT_SOFT_DELETE_DURATION=0 +``` +::: + + + +## Users + +### `extraLastNamePrefixes` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[]` + +Defined by +: [GeneralConfig::$extraLastNamePrefixes](craft4:craft\config\GeneralConfig::$extraLastNamePrefixes) + +Since +: 4.3.0 + +
+ +Any additional last name prefixes that should be supported by the name parser. + +::: code +```php Static Config +->extraLastNamePrefixes(['Dal', 'Van Der']) +``` +```shell Environment Override +CRAFT_EXTRA_LAST_NAME_PREFIXES="Dal,Van Der" +``` +::: + + + +### `extraNameSalutations` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[]` + +Defined by +: [GeneralConfig::$extraNameSalutations](craft4:craft\config\GeneralConfig::$extraNameSalutations) + +Since +: 4.3.0 + +
+ +Any additional name salutations that should be supported by the name parser. + +::: code +```php Static Config +->extraNameSalutations(['Lady', 'Sire']) +``` +```shell Environment Override +CRAFT_EXTRA_NAME_SALUTATIONS=Lady,Sire +``` +::: + + + +### `extraNameSuffixes` + +
+ +Allowed types +: [string](https://php.net/language.types.string)[] + +Default value +: `[]` + +Defined by +: [GeneralConfig::$extraNameSuffixes](craft4:craft\config\GeneralConfig::$extraNameSuffixes) + +Since +: 4.3.0 + +
+ +Any additional name suffixes that should be supported by the name parser. + +::: code +```php Static Config +->extraNameSuffixes(['CCNA', 'OBE']) +``` +```shell Environment Override +CRAFT_EXTRA_NAME_SUFFIXES=CCNA,OBE +``` +::: + + + +### `showFirstAndLastNameFields` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [GeneralConfig::$showFirstAndLastNameFields](craft4:craft\config\GeneralConfig::$showFirstAndLastNameFields) + +Since +: 4.6.0 + +
+ +Whether “First Name” and “Last Name” fields should be shown in place of “Full Name” fields. + +::: code +```php Static Config +->showFirstAndLastNameFields() +``` +```shell Environment Override +CRAFT_SHOW_FIRST_AND_LAST_NAME_FIELDS=true +``` +::: + + + + + diff --git a/docs/.artifacts/cms/4.x/console-commands.md b/docs/.artifacts/cms/4.x/console-commands.md new file mode 100644 index 000000000..9962d1039 --- /dev/null +++ b/docs/.artifacts/cms/4.x/console-commands.md @@ -0,0 +1,3139 @@ + + + + + + +## `cache` + +Allows you to flush caches. + +

+ # + cache/flush +

+ + +Flushes given cache components. + +Example: + +```sh +# flushes caches by ID: “first”, “second”, “third” +php craft cache/flush first second third +``` + +

+ # + cache/flush-all +

+ + +Flushes all caches registered in the system. + +

+ # + cache/flush-schema +

+ + +Clears DB schema cache for a given connection component. + +```sh +php craft cache/flush-schema +# identical to `php craft cache/flush-schema db` +``` + +

Parameters

+ +componentId +: ID of the connection component. (Defaults to `db`.) + + + +

+ # + cache +

+ + +Lists the caches that can be flushed. + +## `clear-caches` + +Allows you to clear various Craft caches. + +

+ # + clear-caches/all +

+ + +Clear all caches. + +

+ # + clear-caches/asset +

+ + +Clears Asset caches. + +

+ # + clear-caches/asset-indexing-data +

+ + +Clears Asset indexing data. + +

+ # + clear-caches/compiled-classes +

+ + +Clears compiled classes. + +

+ # + clear-caches/compiled-templates +

+ + +Clears compiled templates. + +

+ # + clear-caches/cp-resources +

+ + +Clears control panel resources. + +

+ # + clear-caches/data +

+ + +Clears data caches. + +

+ # + clear-caches +

+ + +Lists the caches that can be cleared. + +

+ # + clear-caches/temp-files +

+ + +Clears temporary files. + +

+ # + clear-caches/transform-indexes +

+ + +Clears the Asset transform index. + +## `clear-deprecations` + + +

+ # + clear-deprecations +

+ + +Clears all deprecation warnings. + +## `db` + +Performs database operations. + +

+ # + db/backup +

+ + +Creates a new database backup. + +Example: +``` +php craft db/backup ./my-backups/ +``` + +

Parameters

+ +path +: The path the database backup should be created at. +Can be any of the following: + + - A full file path + - A folder path (backup will be saved in there with a dynamically-generated name) + - A filename (backup will be saved in the working directory with the given name) + - Blank (backup will be saved to the `storage/backups/` folder with a dynamically-generated name) + + + +

Options

+ + +--zip +: Whether the backup should be saved as a zip file. + + +--overwrite +: Whether to overwrite an existing backup file, if a specific file path is given. + + + +

+ # + db/convert-charset +

+ + +Converts tables’ character sets and collations. (MySQL only) + +Example: +``` +php craft db/convert-charset utf8 utf8_unicode_ci +``` + +

Parameters

+ +charset +: The target character set, which honors `DbConfig::$charset` + or defaults to `utf8`. + +collation +: The target collation, which honors `DbConfig::$collation` + or defaults to `utf8_unicode_ci`. + + + +

+ # + db/drop-all-tables +

+ + +Drops all tables in the database. + +Example: +``` +php craft db/drop-all-tables +``` + +

+ # + db/drop-table-prefix +

+ + +Drops the database table prefix from all tables. + +

Parameters

+ +prefix +: The current table prefix. If omitted, the prefix will be detected automatically. + + + +

+ # + db/restore +

+ + +Restores a database backup. + +Example: +``` +php craft db/restore ./my-backup.sql +``` + +

Parameters

+ +path +: The path to the database backup file. + + + +

Options

+ + +--drop-all-tables +: Whether to drop all preexisting tables in the database prior to restoring the backup. + + + +## `elements` + +Manages elements. + +

+ # + elements/delete +

+ + +Deletes an element by its ID. + +

Parameters

+ +id +: The element ID to delete. + + + +

Options

+ + +--hard +: Whether the element should be hard-deleted. + + + +

+ # + elements/restore +

+ + +Restores an element by its ID. + +

Parameters

+ +id +: The element ID to restore. + + + +## `entrify` + +Converts categories, tags, and global sets to entries. + +

+ # + entrify/categories +

+ + +Converts categories to entries. + +

Parameters

+ +categoryGroup +: The category group handle + + + +

Options

+ + +--section +: The section handle that entries should be saved in + + +--entry-type +: The entry type handle that entries should have + + +--author +: The author username or email that entries should have + + + +

+ # + entrify/global-set +

+ + +Converts a global set to a Single section. + +

Parameters

+ +globalSet +: The global set handle + + + +

Options

+ + +--section +: The section handle that entries should be saved in + + + +

+ # + entrify/tags +

+ + +Converts tags to entries. + +

Parameters

+ +tagGroup +: The tag group handle + + + +

Options

+ + +--section +: The section handle that entries should be saved in + + +--entry-type +: The entry type handle that entries should have + + +--author +: The author username or email that entries should have + + + +## `exec` + + +

+ # + exec/exec +

+ + +Executes a PHP statement and outputs the result. + +

Parameters

+ +command +: + + + +## `fixture` + +Allows you to manage test fixtures. + +

+ # + fixture/load +

+ + +Loads the specified fixture data. + +Example: + +```sh +# load User fixture data (any existing fixture data will be removed first) +php craft fixture/load "User" + +# load all available fixtures found under 'tests\unit\fixtures' +php craft fixture/load "*" + +# load all fixtures except User +php craft fixture/load "*, -User" +``` + +

Parameters

+ +fixturesInput +: Array of fixtures to load. + + + +

Options

+ + +--global-fixtures, -g +: Array of global fixtures that should be applied when loading and unloading. Set to `InitDbFixture` by default, which disables and enables integrity check so your data can be safely loaded. + + +--namespace, -n +: Namespace to search for fixtures. Defaults to `tests\unit\fixtures`. + + + +

+ # + fixture/unload +

+ + +Unloads the specified fixtures. + +Example: + +```sh +# unload User fixture data +php craft fixture/load "User" + +# unload all fixtures found under 'tests\unit\fixtures' +php craft fixture/load "*" + +# unload all fixtures except User +php craft fixture/load "*, -User" +``` + +

Parameters

+ +fixturesInput +: Array of fixtures to unload. + + + +

Options

+ + +--global-fixtures, -g +: Array of global fixtures that should be applied when loading and unloading. Set to `InitDbFixture` by default, which disables and enables integrity check so your data can be safely loaded. + + +--namespace, -n +: Namespace to search for fixtures. Defaults to `tests\unit\fixtures`. + + + +## `gc` + + +

+ # + gc/run +

+ + +Runs garbage collection. + +

Options

+ + +--delete-all-trashed +: Whether all soft-deleted items should be deleted, rather than just +the ones that were deleted long enough ago to be ready for hard-deletion +per the `softDeleteDuration` config setting. + + + +## `graphql` + +Allows you to manage GraphQL schemas. + +

+ # + graphql/create-token +

+ + +Creates a new authorization token for a schema. + +

Parameters

+ +schemaUid +: The schema UUID + + + +

Options

+ + +--name +: The schema name + + +--expiry +: Expiry date + + + +

+ # + graphql/dump-schema +

+ + +Dumps a given GraphQL schema to a file. + +

Options

+ + +--schema +: The GraphQL schema UUID. + + +--token +: The token to look up to determine the appropriate GraphQL schema. + + +--full-schema +: Whether full schema should be printed or dumped. + + + +

+ # + graphql/list-schemas +

+ + +Lists all GraphQL schemas. + +

+ # + graphql/print-schema +

+ + +Prints a given GraphQL schema. + +

Options

+ + +--schema +: The GraphQL schema UUID. + + +--token +: The token to look up to determine the appropriate GraphQL schema. + + +--full-schema +: Whether full schema should be printed or dumped. + + + +## `help` + +Provides help information about console commands. + +

+ # + help +

+ + +Displays available commands or the detailed information +about a particular command. + +Example: + +``` +$ php craft help db/backup + +DESCRIPTION + +Creates a new database backup. + +Example: +php craft db/backup ./my-backups/ + + +USAGE + +craft db/backup [path] [...options...] + +- path: string + The path the database backup should be created at. + Can be any of the following: + + - A full file path + - A folder path (backup will be saved in there with a dynamically-generated name) + - A filename (backup will be saved in the working directory with the given name) + - Blank (backup will be saved to the `storage/backups/` folder with a dynamically-generated name) + + +OPTIONS + +--appconfig: string + custom application configuration file path. + If not set, default application configuration is used. + +--color: boolean, 0 or 1 + whether to enable ANSI color in the output. + If not set, ANSI color will only be enabled for terminals that support it. + +--help, -h: boolean, 0 or 1 (defaults to 0) + whether to display help information about current command. + +--interactive: boolean, 0 or 1 (defaults to 1) + whether to run the command interactively. + +--overwrite: boolean, 0 or 1 (defaults to 0) + Whether to overwrite an existing backup file, if a specific file path is given. + +--silent-exit-on-exception: boolean, 0 or 1 + if true - script finish with `ExitCode::OK` in case of exception. + false - `ExitCode::UNSPECIFIED_ERROR`. + Default: `YII_ENV_TEST` + +--zip: boolean, 0 or 1 (defaults to 0) + Whether the backup should be saved as a zip file. + +$ +``` + + +

Parameters

+ +command +: The name of the command to show help about. +If not provided, all available commands will be displayed. + + + +

Options

+ + +--as-json, -j +: Should the commands help be returned in JSON format? + + + +

+ # + help/list +

+ + +Lists all available controllers and actions in machine-readable format. + +

+ # + help/list-action-options +

+ + +List all available options for `action` in machine-readable format. + +

Parameters

+ +action +: Route to action. + + + +

+ # + help/usage +

+ + +Displays usage information for `action`. + +

Parameters

+ +action +: Route to action. + + + +## `index-assets` + +Allows you to re-index assets in volumes. + +

+ # + index-assets/all +

+ + +Re-indexes assets across all volumes. + +

Options

+ + +--cache-remote-images +: Whether remote-stored images should be locally cached in the process. + + +--create-missing-assets +: Whether to auto-create new asset records when missing. + + +--delete-missing-assets +: Whether to delete all the asset records that have their files missing. + + +--delete-empty-folders +: Whether empty folders should be deleted. + + + +

+ # + index-assets/cleanup +

+ + +Removes all CLI indexing sessions. + +

+ # + index-assets/one +

+ + +Re-indexes assets from the given volume handle. + +

Parameters

+ +handle +: The handle of the volume to index. +You can optionally provide a volume sub-path, e.g. `php craft index-assets/one volume-handle/path/to/folder`. + +startAt +: Index of the asset to start with, which defaults to `0`. + + + +

Options

+ + +--cache-remote-images +: Whether remote-stored images should be locally cached in the process. + + +--create-missing-assets +: Whether to auto-create new asset records when missing. + + +--delete-missing-assets +: Whether to delete all the asset records that have their files missing. + + +--delete-empty-folders +: Whether empty folders should be deleted. + + + +## `install` + +Craft CMS CLI installer. + +

+ # + install/check +

+ + +Checks whether Craft is already installed. + +

+ # + install/craft +

+ + +Runs the install migration. + +

Options

+ + +--email +: The default email address for the first user to create during install. + + +--username +: The default username for the first user to create during install. + + +--password +: The default password for the first user to create during install. + + +--site-name +: The default site name for the first site to create during install. + + +--site-url +: The default site URL for the first site to create during install. + + +--language +: The default language for the first site to create during install. + + + +## `invalidate-tags` + +Allows you to invalidate cache tags. + +

+ # + invalidate-tags/all +

+ + +Invalidates all cache tags. + +

+ # + invalidate-tags/graphql +

+ + +Invalidates all GraphQL query cache tags. + +

+ # + invalidate-tags +

+ + +Lists the cache tags that can be invalidated. + +

+ # + invalidate-tags/template +

+ + +Invalidates all template cache tags. + +## `mailer` + + +

+ # + mailer/test +

+ + +Tests sending an email with the current mailer settings. + +

Options

+ + +--to +: Email address that should receive the test message. + + + +## `migrate` + +Manages Craft and plugin migrations. + +

+ # + migrate/all +

+ + +Runs all pending Craft, plugin, and content migrations. + +

Options

+ + +--no-content +: Exclude pending content migrations. + + +--no-backup +: Skip backing up the database. + + + +

+ # + migrate/create +

+ + +Creates a new migration. + +This command creates a new migration using the available migration template. +After using this command, developers should modify the created migration +skeleton by filling up the actual migration logic. + +``` +craft migrate/create create_news_section +``` + +By default, the migration is created in the project’s `migrations/` +folder (as a “content migration”).\ +Use `--plugin=` to create a new plugin migration.\ +Use `--type=app` to create a new Craft CMS app migration. + +

Parameters

+ +name +: the name of the new migration. This should only contain +letters, digits, and underscores. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + +--template-file +: The template file for generating new migrations. This can be either a path alias (e.g. `@app/migrations/template.php`) or a file path. Defaults to `vendor/craftcms/cms/src/updates/migration.php.template`. + + + +

+ # + migrate/down +

+ + +Downgrades Craft by reverting old migrations. + +Example: + +```sh +php craft migrate/down # revert last migration +php craft migrate/down 3 # revert last three migrations +php craft migrate/down all # revert all migrations +``` + +

Parameters

+ +limit +: The number of migrations to be reverted. Defaults to `1`, meaning the last applied migration will be reverted. When value is `all`, all migrations will be reverted. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/history +

+ + +Shows the list of migrations that have been applied so far. + +Example: + +```sh +php craft migrate/history # displays the last ten migrations +php craft migrate/history 5 # displays the last five migrations +php craft migrate/history all # displays the entire migration history +``` + +

Parameters

+ +limit +: The maximum number of migrations to be displayed. (Defaults to `10`.) +If `all`, the whole migration history will be displayed. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/mark +

+ + +Modifies the migration history to the specified version. + +No actual migration will be performed. + +```sh +php craft migrate/mark 101129_185401 # using timestamp +php craft migrate/mark m101129_185401_create_user_table # using name +php craft migrate/mark app\migrations\M101129185401CreateUser # using namespace name +php craft migrate/mark m000000_000000_base # reset entire history +``` + +

Parameters

+ +version +: The version at which the migration history should be marked, which can be either the timestamp or the full name of the migration. + + Specify `m000000_000000_base` to set the migration history to a state where no migration has been applied. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/new +

+ + +Shows any new migrations that have not been applied. + +Example: + +```sh +php craft migrate/new # displays the first 10 new migrations +php craft migrate/new 5 # displays the first 5 new migrations +php craft migrate/new all # displays all new migrations +``` + +

Parameters

+ +limit +: The maximum number of new migrations to be displayed. (Defaults to `10`.) +If `all`, then every available new migration will be displayed. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/redo +

+ + +Reapplies previous migrations by first reverting them and then applying them again. + +Example: + +```sh +php craft migrate/redo # redo the last applied migration +php craft migrate/redo 3 # redo the last three applied migrations +php craft migrate/redo all # redo all migrations +``` + +

Parameters

+ +limit +: The number of migrations to be redone. Defaults to `1`, meaning the last applied migration will be redone. When `all`, every migration will be redone. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/to +

+ + +Upgrades or downgrades until the specified version. + +You can downgrade versions to a past apply time by providing a UNIX timestamp or a [strtotime()](https://www.php.net/manual/en/function.strtotime.php)-parseable value. All versions applied after that specified time will then be reverted. + +Example: + +```sh +php craft migrate/to 101129_185401 # migration timestamp +php craft migrate/to m101129_185401_create_user_table # full name +php craft migrate/to 1392853618 # UNIX timestamp +php craft migrate/to "2022-02-02 02:02:02" # strtotime()-parseable +php craft migrate/to app\migrations\M101129185401CreateUser # full namespace name +``` + +

Parameters

+ +version +: Either the version name or a past time value to be migrated to. This can be a timestamp, the full name of the migration, a UNIX timestamp, or a string value that can be parsed by [strotime()](https://www.php.net/manual/en/function.strtotime.php). + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +

+ # + migrate/up +

+ + +Upgrades Craft by applying new migrations. + +Example: +``` +php craft migrate # apply all new migrations +php craft migrate 3 # apply the first 3 new migrations +``` + +

Parameters

+ +limit +: The number of new migrations to be applied. If `0`, every new migration +will be applied. + + + +

Options

+ + +--track +: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) + + Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. + + +--plugin, -p +: The handle of the plugin to use during migration operations, or the plugin itself. + + + +## `off` + + +

+ # + off +

+ + +Disables `system.live` project config value—bypassing any `allowAdminChanges` config setting +restrictions—meant for temporary use during the deployment process. + +

Options

+ + +--retry +: Number of seconds the `Retry-After` HTTP header should be set to for 503 responses. + + The `retryDuration` config setting can be used to configure a *system-wide* `Retry-After` header. + + ::: warning + The `isSystemLive` config setting takes precedence over the `system.live` project config value, + so if `config/general.php` sets `isSystemLive` to `true` or `false` these `on`/`off` commands error out. + ::: + + **Example** + + Running the following takes the system offline and returns 503 responses until it’s switched on again: + + ``` + $ php craft off --retry=60 + The system is now offline. + The retry duration is now set to 60. + ``` + + + +## `on` + + +

+ # + on +

+ + +Turns the system on. + +Example: +``` +$ php craft on +The system is now online. +``` + +## `plugin` + +Manages plugins. + +

+ # + plugin/disable +

+ + +Disables a plugin. + +``` +$ php craft plugin/disable + +The following plugins are enabled: + + Handle Name Version + ------------- -------------- ------- + apple-news Apple News 3.0.0 + ckeditor CKEditor 2.0.0 + commerce Craft Commerce 4.0.0 + gatsby-helper Gatsby Helper 2.0.0 + +Choose a plugin handle to disable: ckeditor +*** disabling ckeditor +*** disabled ckeditor successfully (time: 0.003s) +``` + + +

Parameters

+ +handle +: The plugin handle (omitted if --all provided). + + + +

Options

+ + +--all +: Whether the action should be run for all Composer-installed plugins. + + + +

+ # + plugin/enable +

+ + +Enables a plugin. + +``` +$ php craft plugin/enable + +The following plugins are disabled: + + Handle Name Version + ---------- ---------- ------- + apple-news Apple News 3.0.0 + ckeditor CKEditor 2.0.0 + +Choose a plugin handle to enable: ckeditor +*** enabling ckeditor +*** enabled ckeditor successfully (time: 0.004s) +``` + + +

Parameters

+ +handle +: The plugin handle (omitted if --all provided). + + + +

Options

+ + +--all +: Whether the action should be run for all Composer-installed plugins. + + + +

+ # + plugin/install +

+ + +Installs a plugin. + +``` +$ php craft plugin/install + +The following uninstalled plugins are present: + + Handle Name Version + ------------- -------------- ------- + anchors Anchors 3.0.0 + apple-news Apple News 3.0.0 + ckeditor CKEditor 2.0.0 + commerce Craft Commerce 4.0.0 + gatsby-helper Gatsby Helper 2.0.0 + +Choose a plugin handle to install: ckeditor +*** installing ckeditor +*** installed ckeditor successfully (time: 0.496s) +``` + + +

Parameters

+ +handle +: The plugin handle (omitted if --all provided). + + + +

Options

+ + +--all +: Whether the action should be run for all Composer-installed plugins. + + + +

+ # + plugin/list +

+ + +Lists all plugins. + +``` +$ php craft plugin/list + + Name Handle Package Name Version Installed Enabled + -------------- ------------- ---------------------- ------- --------- ------- + Anchors anchors craftcms/anchors 3.0.0 Yes Yes + Apple News apple-news craftcms/apple-news 3.0.0 Yes Yes + CKEditor ckeditor craftcms/ckeditor 2.0.0 Yes Yes + Craft Commerce commerce craftcms/commerce 4.0.0 Yes Yes + Gatsby Helper gatsby-helper craftcms/gatsby-helper 2.0.0 Yes Yes +``` + + +

+ # + plugin/uninstall +

+ + +Uninstalls a plugin. + +``` +$ php craft plugin/uninstall + +The following plugins plugins are installed and enabled: + + Handle Name Version + ------------- -------------- ------- + anchors Anchors 3.0.0 + apple-news Apple News 3.0.0 + ckeditor CKEditor 2.0.0 + commerce Craft Commerce 4.0.0 + gatsby-helper Gatsby Helper 2.0.0 + +Choose a plugin handle to uninstall: ckeditor +*** uninstalling ckeditor +*** uninstalled ckeditor successfully (time: 0.496s) +``` + + +

Parameters

+ +handle +: The plugin handle (omitted if --all provided). + + + +

Options

+ + +--force +: Whether the plugin uninstallation should be forced. + + +--all +: Whether the action should be run for all Composer-installed plugins. + + + +## `project-config` + +Manages the Project Config. + +

+ # + project-config/apply +

+ + +Applies project config file changes. + +

Options

+ + +--force +: Whether every entry change should be force-applied. + + +--quiet +: Whether to reduce the command output. + + + +

+ # + project-config/diff +

+ + +Outputs a diff of the pending project config YAML changes. + +

Options

+ + +--invert +: Whether to treat the loaded project config as the source of truth, instead of the YAML files. + + + +

+ # + project-config/export +

+ + +Exports the entire project config to a single file. + +

Parameters

+ +path +: The path the project config should be exported to. +Can be any of the following: + + - A full file path + - A folder path (export will be saved in there with a dynamically-generated name) + - A filename (export will be saved in the working directory with the given name) + - Blank (export will be saved in the working directly with a dynamically-generated name) + + + +

Options

+ + +--external +: Whether to pull values from the project config YAML files instead of the loaded config. + + +--overwrite +: Whether to overwrite an existing export file, if a specific file path is given. + + + +

+ # + project-config/get +

+ + +Outputs a project config value. + +Example: +``` +php craft project-config/get system.edition +``` + +The “path” syntax used here may be composed of directory and filenames (within your `config/project` folder), YAML object keys (including UUIDs for many Craft resources), and integers (referencing numerically-indexed arrays), joined by a dot (`.`): `path.to.nested.array.0.property`. + +

Parameters

+ +path +: The config item path + + + +

Options

+ + +--external +: Whether to pull values from the project config YAML files instead of the loaded config. + + + +

+ # + project-config/rebuild +

+ + +Rebuilds the project config. + +

+ # + project-config/remove +

+ + +Removes a project config value. + +Example: +``` +php craft project-config/remove some.nested.key +``` + +::: danger +This should only be used when the equivalent change is not possible through the control panel or other Craft APIs. By directly modifying project config values, you are bypassing all validation and can easily destabilize configuration. +::: + +As with [set](#project-config-set), removing values only updates the root `dateModified` key when using the [`--update-timestamp` flag](#project-config-set-options). If you do not include this flag, you must run `project-config/touch` before changes will be detected or applied in other environments! + +

Parameters

+ +path +: The config item path + + + +

+ # + project-config/set +

+ + +Sets a project config value. + +Example: +``` +php craft project-config/set some.nested.key +``` + +See [get](#project-config-get) for the accepted key formats. + +::: danger +This should only be used when the equivalent change is not possible through the control panel or other Craft APIs. By directly modifying project config values, you are bypassing all validation and can easily destabilize configuration. +::: + +Values are updated in the database *and* in your local YAML files, but the root `dateModified` project config property is only touched when using the [`--update-timestamp` flag](#project-config-set-options). If you do not update the timestamp along with the value, the change may not be detected or applied in other environments! + +

Parameters

+ +path +: The config item path + +value +: The config item value as a valid YAML string + + + +

Options

+ + +--force +: Whether every entry change should be force-applied. + + +--message +: A message describing the changes. + + +--update-timestamp +: Whether the `dateModified` value should be updated + + + +

+ # + project-config/touch +

+ + +Updates the `dateModified` value in `config/project/project.yaml`, attempting to resolve a Git conflict for it. + +

+ # + project-config/write +

+ + +Writes out the currently-loaded project config as YAML files to the `config/project/` folder, discarding any pending YAML changes. + +## `queue` + +Manages the queue. + +

+ # + queue/exec +

+ + +Executes a job. +The command is internal, and used to isolate a job execution. Manual usage is not provided. + +

Parameters

+ +id +: of a message + +ttr +: time to reserve + +attempt +: number + +pid +: of a worker + + + +

Options

+ + +--verbose, -v +: verbose mode of a job execute. If enabled, execute result of each job +will be printed. + + + +

+ # + queue/info +

+ + +Info about queue status. + +

+ # + queue/listen +

+ + +Listens for new jobs added to the queue and runs them. + +

Parameters

+ +timeout +: The number of seconds to wait between cycles. + + + +

Options

+ + +--verbose, -v +: verbose mode of a job execute. If enabled, execute result of each job +will be printed. + + +--isolate +: isolate mode. It executes a job in a child process. + + +--php-binary +: path to php interpreter that uses to run child processes. +If it is undefined, PHP_BINARY will be used. + + + +

+ # + queue/release +

+ + +Releases job(s) from the queue. + +Example: + +``` +php craft queue/release all +``` + +

Parameters

+ +job +: The job ID to release. Pass `all` to release all jobs. + + + +

+ # + queue/retry +

+ + +Re-adds failed job(s) to the queue. + +

Parameters

+ +job +: The job ID that should be retried, or `all` to retry all failed jobs. + + + +

+ # + queue/run +

+ + +Runs all jobs in the queue. + +

Options

+ + +--verbose, -v +: verbose mode of a job execute. If enabled, execute result of each job +will be printed. + + +--isolate +: isolate mode. It executes a job in a child process. + + +--php-binary +: path to php interpreter that uses to run child processes. +If it is undefined, PHP_BINARY will be used. + + + +## `resave` + +Allows you to bulk-save elements. + +

+ # + resave/addresses +

+ + +Re-saves user addresses. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to fetch elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--owner-id +: Comma-separated list of owner element IDs. + + +--country-code +: Comma-separated list of country codes. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/assets +

+ + +Re-saves assets. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to fetch elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--volume +: The volume handle(s) to save assets from. Can be set to multiple comma-separated volumes. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/categories +

+ + +Re-saves categories. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to fetch elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--group +: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/entries +

+ + +Re-saves entries. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--drafts +: Whether to resave element drafts. + + +--provisional-drafts +: Whether to resave provisional element drafts. + + +--revisions +: Whether to resave element revisions. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to fetch elements from. + + +--propagate-to +: Comma-separated site handles to propagate entries to. + + When this is set, the entry will *only* be saved for this site. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--section +: The section handle(s) to save entries from. Can be set to multiple comma-separated sections. + + +--type +: The type handle(s) of the elements to resave. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--set-enabled-for-site +: The site-enabled status that should be set on the entry, for the site it’s initially being saved/propagated to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/matrix-blocks +

+ + +Re-saves Matrix blocks. + +You must supply the `--field` or `--element-id` argument for this to work properly. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to fetch elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--type +: The type handle(s) of the elements to resave. + + +--field +: The field handle to save Matrix blocks for. + + +--owner-id +: Comma-separated list of owner element IDs. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/tags +

+ + +Re-saves tags. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to fetch elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--group +: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +

+ # + resave/users +

+ + +Re-saves users. + +

Options

+ + +--queue +: Whether the elements should be resaved via a queue job. + + +--element-id +: The ID(s) of the elements to resave. + + +--uid +: The UUID(s) of the elements to resave. + + +--site +: The site handle to fetch elements from. + + +--status +: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. + + +--offset +: The number of elements to skip. + + +--limit +: The number of elements to resave. + + +--update-search-index +: Whether to update the search indexes for the resaved elements. + + +--touch +: Whether to update the `dateUpdated` timestamp for the elements. + + +--group +: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. + + +--set +: An attribute name that should be set for each of the elements. The value will be determined by --to. + + +--to +: The value that should be set on the --set attribute. + + The following value types are supported: + - An attribute name: `--to myCustomField` + - An object template: `--to "={myCustomField|lower}"` + - A raw value: `--to "=foo bar"` + - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` + - An empty value: `--to :empty:` + + +--if-empty +: Whether the `--set` attribute should only be set if it doesn’t have a value. + + + +## `sections` + +Manages sections. + +

+ # + sections/create +

+ + +Creates a section. + +

Options

+ + +--name +: The section name. + + +--handle +: The section handle. + + +--type +: The section type (single, channel, or structure). + + +--no-versioning +: Whether to disable versioning for the section. + + +--uri-format +: The entry URI format to set for each site. + + +--template +: The template to load when an entry’s URL is requested. + + +--from-category-group +: The category group handle to model the section from. + + +--from-tag-group +: The tag group handle to model the section from. + + +--from-global-set +: The global set handle to model the section from. + + + +

+ # + sections/delete +

+ + +Deletes a section. + +

Parameters

+ +handle +: The section handle + + + +## `serve` + + +

+ # + serve +

+ + +Runs PHP built-in web server. + +

Parameters

+ +address +: address to serve on. Either "host" or "host:port". + + + +

Options

+ + +--docroot, -t +: path or [path alias](https://craftcms.com/docs/4.x/config/#aliases) of the directory to serve. + + +--router, -r +: + + +--port, -p +: port to serve on. + + + +## `setup` + +Craft CMS setup installer. + +

+ # + setup/app-id +

+ + +Generates a new application ID and saves it in the `.env` file. + +

+ # + setup/cloud +

+ + +Prepares the Craft install to be deployed to Craft Cloud. + +

+ # + setup/db +

+ + +Alias for [setup/db-creds](#setup-db-creds). + +

Options

+ + +--driver +: The database driver to use. Either `'mysql'` for MySQL or `'pgsql'` for PostgreSQL. + + +--server +: The database server name or IP address. Usually `'localhost'` or `'127.0.0.1'`. + + +--port +: The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. + + +--user +: The database username to connect with. + + +--password +: The database password to connect with. + + +--database +: The name of the database to select. + + +--schema +: The schema that Postgres is configured to use by default (PostgreSQL only). + + +--table-prefix +: The table prefix to add to all database tables. This can +be no more than 5 characters, and must be all lowercase. + + + +

+ # + setup/db-cache-table +

+ + +Creates a database table for storing DB caches. + +

+ # + setup/db-creds +

+ + +Stores new DB connection settings to the `.env` file. + +

Options

+ + +--driver +: The database driver to use. Either `'mysql'` for MySQL or `'pgsql'` for PostgreSQL. + + +--server +: The database server name or IP address. Usually `'localhost'` or `'127.0.0.1'`. + + +--port +: The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. + + +--user +: The database username to connect with. + + +--password +: The database password to connect with. + + +--database +: The name of the database to select. + + +--schema +: The schema that Postgres is configured to use by default (PostgreSQL only). + + +--table-prefix +: The table prefix to add to all database tables. This can +be no more than 5 characters, and must be all lowercase. + + + +

+ # + setup +

+ + +Sets up all the things. + +This is an interactive wrapper for the `setup/app-id`, `setup/security-key`, `setup/db-creds`, +and `install` commands, each of which support being run non-interactively. + +

+ # + setup/keys +

+ + +Generates an application ID and security key (if they don’t exist), and saves them in the `.env` file. + +

+ # + setup/message-tables +

+ + +Creates database tables for storing message translations. (EXPERIMENTAL!) + +

+ # + setup/php-session-table +

+ + +Creates a database table for storing PHP session information. + +

+ # + setup/security-key +

+ + +Generates a new security key and saves it in the `.env` file. + +

+ # + setup/welcome +

+ + +Called from the `post-create-project-cmd` Composer hook. + +## `shell` + + +

+ # + shell +

+ + +Runs an interactive shell. + +::: tip +This command requires the [`yiisoft/yii2-shell`](https://github.com/yiisoft/yii2-shell) package, which you may need to add to your project: + +``` +composer require --dev yiisoft/yii2-shell +``` +::: + +``` +$ php craft shell + +Psy Shell v0.10.12 (PHP 8.0.3 — cli) by Justin Hileman +>>> help + help Show a list of commands. Type `help [foo]` for information about [foo]. Aliases: ? + ls List local, instance or class variables, methods and constants. Aliases: dir + dump Dump an object or primitive. + doc Read the documentation for an object, class, constant, method or property. Aliases: rtfm, m + show Show the code for an object, class, constant, method or property. + wtf Show the backtrace of the most recent exception. Aliases: last-ex + whereami Show where you are in the code. + throw-up Throw an exception or error out of the Psy Shell. + timeit Profiles with a timer. + trace Show the current call stack. + buffer Show (or clear) the contents of the code input buffer. Aliases: buf + clear Clear the Psy Shell screen. + edit Open an external editor. Afterwards, get produced code in input buffer. + sudo Evaluate PHP code, bypassing visibility restrictions. + history Show the Psy Shell history. Aliases: hist + exit End the current session and return to caller. Aliases: quit, q +``` + + +

Options

+ + +--include +: Include file(s) before starting tinker shell. + + + +## `tests` + + +

+ # + tests/setup +

+ + +Sets up a test suite for the current project. + +

Parameters

+ +dst +: The folder that the test suite should be generated in. + Defaults to the current working directory. + + + +## `up` + + +

+ # + up +

+ + +Runs pending migrations and applies pending project config changes. + +

Options

+ + +--no-backup +: Skip backing up the database. + + +--force +: Whether to perform the action even if a mutex lock could not be acquired. + + + +## `update` + +Updates Craft and plugins. + +

+ # + update/composer-install +

+ + +Installs dependencies based on the current `composer.json` & `composer.lock`. + +

+ # + update/info +

+ + +Displays info about available updates. + +

+ # + update/update +

+ + +Updates Craft and/or plugins. + +

Parameters

+ +handle +: The update handle (`all`, `craft`, or a plugin handle). +You can pass multiple handles separated by spaces, and you can update to a specific +version using the syntax `:`. + + + +

Options

+ + +--force, -f +: Force the update if allowUpdates is disabled + + +--backup +: Backup the database before updating + + +--migrate +: Run new database migrations after completing the update + + + +## `users` + +Manages user accounts. + +

+ # + users/activation-url +

+ + +Generates an activation URL for a pending user. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

+ # + users/create +

+ + +Creates a user. + +

Options

+ + +--email +: The user’s email address. + + +--username +: The user’s username. + + +--password +: The user’s new password. + + +--admin +: Whether the user should be an admin. + + +--groups +: The group handles to assign the created user to. + + +--group-ids +: The group IDs to assign the user to the created user to. + + + +

+ # + users/delete +

+ + +Deletes a user. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

Options

+ + +--inheritor +: The email or username of the user to inherit content when deleting a user. + + +--delete-content +: Whether to delete the user’s content if no inheritor is specified. + + +--hard +: Whether the user should be hard-deleted immediately, instead of soft-deleted. + + + +

+ # + users/impersonate +

+ + +Generates a URL to impersonate a user. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

+ # + users/list-admins +

+ + +Lists admin users. + +

+ # + users/logout-all +

+ + +Logs all users out of the system. + +

+ # + users/password-reset-url +

+ + +Generates a password reset URL for a user. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

+ # + users/set-password +

+ + +Changes a user’s password. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +

Options

+ + +--password +: The user’s new password. + + + +

+ # + users/unlock +

+ + +Unlocks a user's account. + +

Parameters

+ +user +: The ID, username, or email address of the user account. + + + +## `utils/ascii-filenames` + + +

+ # + utils/ascii-filenames +

+ + +Converts all non-ASCII asset filenames to ASCII. + +## `utils/fix-element-uids` + + +

+ # + utils/fix-element-uids +

+ + +Ensures all elements UIDs are unique. + +## `utils/fix-field-layout-uids` + + +

+ # + utils/fix-field-layout-uids +

+ + +Fixes any duplicate UUIDs found within field layout components in the project config. + +## `utils/prune-provisional-drafts` + + +

+ # + utils/prune-provisional-drafts +

+ + +Prunes provisional drafts for elements that have more than one per user. + +

Options

+ + +--dry-run +: Whether this is a dry run. + + + +## `utils/prune-revisions` + + +

+ # + utils/prune-revisions +

+ + +Prunes excess element revisions. + +

Options

+ + +--section +: The section handle(s) to prune revisions from. Can be set to multiple comma-separated sections. + + +--max-revisions +: The maximum number of revisions an element can have. + + +--dry-run +: Whether this is a dry run. + + + +## `utils/repair` + +Repairs data. + +

+ # + utils/repair/category-group-structure +

+ + +Repairs structure data for a category group. + +

Parameters

+ +handle +: The category group handle. + + + +

Options

+ + +--dry-run +: Whether to only do a dry run of the repair process. + + + +

+ # + utils/repair/project-config +

+ + +Repairs double-packed associative arrays in the project config. + +

Options

+ + +--dry-run +: Whether to only do a dry run of the repair process. + + + +

+ # + utils/repair/section-structure +

+ + +Repairs structure data for a section. + +

Parameters

+ +handle +: The section handle. + + + +

Options

+ + +--dry-run +: Whether to only do a dry run of the repair process. + + + +## `utils/update-usernames` + + +

+ # + utils/update-usernames +

+ + +Updates all users’ usernames to ensure they match their email address. + + + + diff --git a/docs/.artifacts/cms/4.x/entries.md b/docs/.artifacts/cms/4.x/entries.md new file mode 100644 index 000000000..b7ad0035a --- /dev/null +++ b/docs/.artifacts/cms/4.x/entries.md @@ -0,0 +1,1980 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [after](#after) | Narrows the query results to only entries that were posted on or after a certain date. +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [ancestorDist](#ancestordist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). +| [ancestorOf](#ancestorof) | Narrows the query results to only entries that are ancestors of another entry in its structure. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only entries that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching entries as arrays of data, rather than [Entry](craft4:craft\elements\Entry) objects. +| [authorGroup](#authorgroup) | Narrows the query results based on the user group the entries’ authors belong to. +| [authorGroupId](#authorgroupid) | Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. +| [authorId](#authorid) | Narrows the query results based on the entries’ authors. +| [before](#before) | Narrows the query results to only entries that were posted before a certain date. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [collect](#collect) | +| [dateCreated](#datecreated) | Narrows the query results based on the entries’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the entries’ last-updated dates. +| [descendantDist](#descendantdist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). +| [descendantOf](#descendantof) | Narrows the query results to only entries that are descendants of another entry in its structure. +| [draftCreator](#draftcreator) | Narrows the query results to only drafts created by a given user. +| [draftId](#draftid) | Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). +| [draftOf](#draftof) | Narrows the query results to only drafts of a given entry. +| [drafts](#drafts) | Narrows the query results to only drafts entries. +| [expiryDate](#expirydate) | Narrows the query results based on the entries’ expiry dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the entries have any descendants in their structure. +| [id](#id) | Narrows the query results based on the entries’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [leaves](#leaves) | Narrows the query results based on whether the entries are “leaves” (entries with no descendants). +| [level](#level) | Narrows the query results based on the entries’ level within the structure. +| [limit](#limit) | Determines the number of entries that should be returned. +| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the entry that comes immediately after another entry in its structure. +| [offset](#offset) | Determines how many entries should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`, or the order defined by the section if the [section](#section) or [sectionId](#sectionid) params are set to a single Structure section.) +| [positionedAfter](#positionedafter) | Narrows the query results to only entries that are positioned after another entry in its structure. +| [positionedBefore](#positionedbefore) | Narrows the query results to only entries that are positioned before another entry in its structure. +| [postDate](#postdate) | Narrows the query results based on the entries’ post dates. +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the entry that comes immediately before another entry in its structure. +| [provisionalDrafts](#provisionaldrafts) | Narrows the query results to only provisional drafts. +| [relatedTo](#relatedto) | Narrows the query results to only entries that are related to certain other elements. +| [revisionCreator](#revisioncreator) | Narrows the query results to only revisions created by a given user. +| [revisionId](#revisionid) | Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). +| [revisionOf](#revisionof) | Narrows the query results to only revisions of a given entry. +| [revisions](#revisions) | Narrows the query results to only revision entries. +| [savable](#savable) | Sets the [savable](https://docs.craftcms.com/api/v3/craft-elements-db-entryquery.html#savable) property. +| [savedDraftsOnly](#saveddraftsonly) | Narrows the query results to only unpublished drafts which have been saved after initial creation. +| [search](#search) | Narrows the query results to only entries that match a search query. +| [section](#section) | Narrows the query results based on the sections the entries belong to. +| [sectionId](#sectionid) | Narrows the query results based on the sections the entries belong to, per the sections’ IDs. +| [siblingOf](#siblingof) | Narrows the query results to only entries that are siblings of another entry in its structure. +| [site](#site) | Determines which site(s) the entries should be queried in. +| [siteId](#siteid) | Determines which site(s) the entries should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the entries’ IDs in the `elements_sites` table. +| [slug](#slug) | Narrows the query results based on the entries’ slugs. +| [status](#status) | Narrows the query results based on the entries’ statuses. +| [title](#title) | Narrows the query results based on the entries’ titles. +| [trashed](#trashed) | Narrows the query results to only entries that have been soft-deleted. +| [type](#type) | Narrows the query results based on the entries’ entry types. +| [typeId](#typeid) | Narrows the query results based on the entries’ entry types, per the types’ IDs. +| [uid](#uid) | Narrows the query results based on the entries’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uri](#uri) | Narrows the query results based on the entries’ URIs. +| [with](#with) | Causes the query to return matching entries eager-loaded with related elements. + + + + + +#### `after` + +Narrows the query results to only entries that were posted on or after a certain date. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'2018-04-01'` | that were posted after 2018-04-01. +| a [DateTime](https://php.net/class.datetime) object | that were posted after the date represented by the object. +| `now`/`today`/`tomorrow`/`yesterday` | that were posted after midnight of the specified relative date. + + + +::: code +```twig +{# Fetch entries posted this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set entries = craft.entries() + .after(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch entries posted this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$entries = \craft\elements\Entry::find() + ->after($firstDayOfMonth) + ->all(); +``` +::: + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `ancestorDist` + +Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). + + + + + +::: code +```twig +{# Fetch entries above this one #} +{% set entries = craft.entries() + .ancestorOf(myEntry) + .ancestorDist(3) + .all() %} +``` + +```php +// Fetch entries above this one +$entries = \craft\elements\Entry::find() + ->ancestorOf($myEntry) + ->ancestorDist(3) + ->all(); +``` +::: + + +#### `ancestorOf` + +Narrows the query results to only entries that are ancestors of another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | above the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | above the entry represented by the object. + + + +::: code +```twig +{# Fetch entries above this one #} +{% set entries = craft.entries() + .ancestorOf(myEntry) + .all() %} +``` + +```php +// Fetch entries above this one +$entries = \craft\elements\Entry::find() + ->ancestorOf($myEntry) + ->all(); +``` +::: + + + +::: tip +This can be combined with [ancestorDist](#ancestordist) if you want to limit how far away the ancestor entries can be. +::: + + +#### `andRelatedTo` + +Narrows the query results to only entries that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all entries that are related to myCategoryA and myCategoryB #} +{% set entries = craft.entries() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all entries that are related to $myCategoryA and $myCategoryB +$entries = \craft\elements\Entry::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching entries as arrays of data, rather than [Entry](craft4:craft\elements\Entry) objects. + + + + + +::: code +```twig +{# Fetch entries as arrays #} +{% set entries = craft.entries() + .asArray() + .all() %} +``` + +```php +// Fetch entries as arrays +$entries = \craft\elements\Entry::find() + ->asArray() + ->all(); +``` +::: + + +#### `authorGroup` + +Narrows the query results based on the user group the entries’ authors belong to. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | with an author in a group with a handle of `foo`. +| `'not foo'` | not with an author in a group with a handle of `foo`. +| `['foo', 'bar']` | with an author in a group with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not with an author in a group with a handle of `foo` or `bar`. +| a [UserGroup](craft4:craft\models\UserGroup) object | with an author in a group represented by the object. +| an array of [UserGroup](craft4:craft\models\UserGroup) objects | with an author in a group represented by the objects. + + + +::: code +```twig +{# Fetch entries with an author in the Foo user group #} +{% set entries = craft.entries() + .authorGroup('foo') + .all() %} +``` + +```php +// Fetch entries with an author in the Foo user group +$entries = \craft\elements\Entry::find() + ->authorGroup('foo') + ->all(); +``` +::: + + +#### `authorGroupId` + +Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with an author in a group with an ID of 1. +| `'not 1'` | not with an author in a group with an ID of 1. +| `[1, 2]` | with an author in a group with an ID of 1 or 2. +| `['not', 1, 2]` | not with an author in a group with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch entries with an author in a group with an ID of 1 #} +{% set entries = craft.entries() + .authorGroupId(1) + .all() %} +``` + +```php +// Fetch entries with an author in a group with an ID of 1 +$entries = \craft\elements\Entry::find() + ->authorGroupId(1) + ->all(); +``` +::: + + +#### `authorId` + +Narrows the query results based on the entries’ authors. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with an author with an ID of 1. +| `'not 1'` | not with an author with an ID of 1. +| `[1, 2]` | with an author with an ID of 1 or 2. +| `['not', 1, 2]` | not with an author with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch entries with an author with an ID of 1 #} +{% set entries = craft.entries() + .authorId(1) + .all() %} +``` + +```php +// Fetch entries with an author with an ID of 1 +$entries = \craft\elements\Entry::find() + ->authorId(1) + ->all(); +``` +::: + + +#### `before` + +Narrows the query results to only entries that were posted before a certain date. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'2018-04-01'` | that were posted before 2018-04-01. +| a [DateTime](https://php.net/class.datetime) object | that were posted before the date represented by the object. +| `now`/`today`/`tomorrow`/`yesterday` | that were posted before midnight of specified relative date. + + + +::: code +```twig +{# Fetch entries posted before this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set entries = craft.entries() + .before(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch entries posted before this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$entries = \craft\elements\Entry::find() + ->before($firstDayOfMonth) + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `collect` + + + + + + + + +#### `dateCreated` + +Narrows the query results based on the entries’ creation dates. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch entries created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set entries = craft.entries() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch entries created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$entries = \craft\elements\Entry::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the entries’ last-updated dates. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch entries updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set entries = craft.entries() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch entries updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$entries = \craft\elements\Entry::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `descendantDist` + +Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). + + + + + +::: code +```twig +{# Fetch entries below this one #} +{% set entries = craft.entries() + .descendantOf(myEntry) + .descendantDist(3) + .all() %} +``` + +```php +// Fetch entries below this one +$entries = \craft\elements\Entry::find() + ->descendantOf($myEntry) + ->descendantDist(3) + ->all(); +``` +::: + + +#### `descendantOf` + +Narrows the query results to only entries that are descendants of another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | below the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | below the entry represented by the object. + + + +::: code +```twig +{# Fetch entries below this one #} +{% set entries = craft.entries() + .descendantOf(myEntry) + .all() %} +``` + +```php +// Fetch entries below this one +$entries = \craft\elements\Entry::find() + ->descendantOf($myEntry) + ->all(); +``` +::: + + + +::: tip +This can be combined with [descendantDist](#descendantdist) if you want to limit how far away the descendant entries can be. +::: + + +#### `draftCreator` + +Narrows the query results to only drafts created by a given user. + + + +Possible values include: + +| Value | Fetches drafts… +| - | - +| `1` | created by the user with an ID of 1. +| a [craft\elements\User](craft4:craft\elements\User) object | created by the user represented by the object. + + + +::: code +```twig +{# Fetch drafts by the current user #} +{% set entries = craft.entries() + .draftCreator(currentUser) + .all() %} +``` + +```php +// Fetch drafts by the current user +$entries = \craft\elements\Entry::find() + ->draftCreator(Craft::$app->user->identity) + ->all(); +``` +::: + + +#### `draftId` + +Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). + + + +Possible values include: + +| Value | Fetches drafts… +| - | - +| `1` | for the draft with an ID of 1. + + + +::: code +```twig +{# Fetch a draft #} +{% set entries = craft.entries() + .draftId(10) + .all() %} +``` + +```php +// Fetch a draft +$entries = \craft\elements\Entry::find() + ->draftId(10) + ->all(); +``` +::: + + +#### `draftOf` + +Narrows the query results to only drafts of a given entry. + + + +Possible values include: + +| Value | Fetches drafts… +| - | - +| `1` | for the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | for the entry represented by the object. +| `'*'` | for any entry +| `false` | that aren’t associated with a published entry + + + +::: code +```twig +{# Fetch drafts of the entry #} +{% set entries = craft.entries() + .draftOf(myEntry) + .all() %} +``` + +```php +// Fetch drafts of the entry +$entries = \craft\elements\Entry::find() + ->draftOf($myEntry) + ->all(); +``` +::: + + +#### `drafts` + +Narrows the query results to only drafts entries. + + + + + +::: code +```twig +{# Fetch a draft entry #} +{% set entries = craft.entries() + .drafts() + .id(123) + .one() %} +``` + +```php +// Fetch a draft entry +$entries = \craft\elements\Entry::find() + ->drafts() + ->id(123) + ->one(); +``` +::: + + +#### `expiryDate` + +Narrows the query results based on the entries’ expiry dates. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `':empty:'` | that don’t have an expiry date. +| `':notempty:'` | that have an expiry date. +| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. +| `'< 2020-05-01'` | that will expire before 2020-05-01 +| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that expire at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch entries expiring this month #} +{% set nextMonth = date('first day of next month')|atom %} + +{% set entries = craft.entries() + .expiryDate("< #{nextMonth}") + .all() %} +``` + +```php +// Fetch entries expiring this month +$nextMonth = (new \DateTime('first day of next month'))->format(\DateTime::ATOM); + +$entries = \craft\elements\Entry::find() + ->expiryDate("< {$nextMonth}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch entries in a specific order #} +{% set entries = craft.entries() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch entries in a specific order +$entries = \craft\elements\Entry::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `hasDescendants` + +Narrows the query results based on whether the entries have any descendants in their structure. + + + +(This has the opposite effect of calling [leaves](#leaves).) + + + +::: code +```twig +{# Fetch entries that have descendants #} +{% set entries = craft.entries() + .hasDescendants() + .all() %} +``` + +```php +// Fetch entries that have descendants +$entries = \craft\elements\Entry::find() + ->hasDescendants() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the entries’ IDs. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the entry by its ID #} +{% set entry = craft.entries() + .id(1) + .one() %} +``` + +```php +// Fetch the entry by its ID +$entry = \craft\elements\Entry::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch entries in reverse #} +{% set entries = craft.entries() + .inReverse() + .all() %} +``` + +```php +// Fetch entries in reverse +$entries = \craft\elements\Entry::find() + ->inReverse() + ->all(); +``` +::: + + +#### `leaves` + +Narrows the query results based on whether the entries are “leaves” (entries with no descendants). + + + +(This has the opposite effect of calling [hasDescendants](#hasdescendants).) + + + +::: code +```twig +{# Fetch entries that have no descendants #} +{% set entries = craft.entries() + .leaves() + .all() %} +``` + +```php +// Fetch entries that have no descendants +$entries = \craft\elements\Entry::find() + ->leaves() + ->all(); +``` +::: + + +#### `level` + +Narrows the query results based on the entries’ level within the structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with a level of 1. +| `'not 1'` | not with a level of 1. +| `'>= 3'` | with a level greater than or equal to 3. +| `[1, 2]` | with a level of 1 or 2 +| `['not', 1, 2]` | not with level of 1 or 2. + + + +::: code +```twig +{# Fetch entries positioned at level 3 or above #} +{% set entries = craft.entries() + .level('>= 3') + .all() %} +``` + +```php +// Fetch entries positioned at level 3 or above +$entries = \craft\elements\Entry::find() + ->level('>= 3') + ->all(); +``` +::: + + +#### `limit` + +Determines the number of entries that should be returned. + + + +::: code +```twig +{# Fetch up to 10 entries #} +{% set entries = craft.entries() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 entries +$entries = \craft\elements\Entry::find() + ->limit(10) + ->all(); +``` +::: + + +#### `nextSiblingOf` + +Narrows the query results to only the entry that comes immediately after another entry in its structure. + + + +Possible values include: + +| Value | Fetches the entry… +| - | - +| `1` | after the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | after the entry represented by the object. + + + +::: code +```twig +{# Fetch the next entry #} +{% set entry = craft.entries() + .nextSiblingOf(myEntry) + .one() %} +``` + +```php +// Fetch the next entry +$entry = \craft\elements\Entry::find() + ->nextSiblingOf($myEntry) + ->one(); +``` +::: + + +#### `offset` + +Determines how many entries should be skipped in the results. + + + +::: code +```twig +{# Fetch all entries except for the first 3 #} +{% set entries = craft.entries() + .offset(3) + .all() %} +``` + +```php +// Fetch all entries except for the first 3 +$entries = \craft\elements\Entry::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`, or the order defined by the section if the [section](#section) or [sectionId](#sectionid) params are set to a single Structure section.) + + + +::: code +```twig +{# Fetch all entries in order of date created #} +{% set entries = craft.entries() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all entries in order of date created +$entries = \craft\elements\Entry::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `positionedAfter` + +Narrows the query results to only entries that are positioned after another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | after the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | after the entry represented by the object. + + + +::: code +```twig +{# Fetch entries after this one #} +{% set entries = craft.entries() + .positionedAfter(myEntry) + .all() %} +``` + +```php +// Fetch entries after this one +$entries = \craft\elements\Entry::find() + ->positionedAfter($myEntry) + ->all(); +``` +::: + + +#### `positionedBefore` + +Narrows the query results to only entries that are positioned before another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | before the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | before the entry represented by the object. + + + +::: code +```twig +{# Fetch entries before this one #} +{% set entries = craft.entries() + .positionedBefore(myEntry) + .all() %} +``` + +```php +// Fetch entries before this one +$entries = \craft\elements\Entry::find() + ->positionedBefore($myEntry) + ->all(); +``` +::: + + +#### `postDate` + +Narrows the query results based on the entries’ post dates. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. +| `'< 2018-05-01'` | that were posted before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were posted at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch entries posted last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set entries = craft.entries() + .postDate(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch entries posted last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$entries = \craft\elements\Entry::find() + ->postDate(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique entries from Site A, or Site B if they don’t exist in Site A #} +{% set entries = craft.entries() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique entries from Site A, or Site B if they don’t exist in Site A +$entries = \craft\elements\Entry::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `prevSiblingOf` + +Narrows the query results to only the entry that comes immediately before another entry in its structure. + + + +Possible values include: + +| Value | Fetches the entry… +| - | - +| `1` | before the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | before the entry represented by the object. + + + +::: code +```twig +{# Fetch the previous entry #} +{% set entry = craft.entries() + .prevSiblingOf(myEntry) + .one() %} +``` + +```php +// Fetch the previous entry +$entry = \craft\elements\Entry::find() + ->prevSiblingOf($myEntry) + ->one(); +``` +::: + + +#### `provisionalDrafts` + +Narrows the query results to only provisional drafts. + + + + + +::: code +```twig +{# Fetch provisional drafts created by the current user #} +{% set entries = craft.entries() + .provisionalDrafts() + .draftCreator(currentUser) + .all() %} +``` + +```php +// Fetch provisional drafts created by the current user +$entries = \craft\elements\Entry::find() + ->provisionalDrafts() + ->draftCreator(Craft::$app->user->identity) + ->all(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only entries that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all entries that are related to myCategory #} +{% set entries = craft.entries() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all entries that are related to $myCategory +$entries = \craft\elements\Entry::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `revisionCreator` + +Narrows the query results to only revisions created by a given user. + + + +Possible values include: + +| Value | Fetches revisions… +| - | - +| `1` | created by the user with an ID of 1. +| a [craft\elements\User](craft4:craft\elements\User) object | created by the user represented by the object. + + + +::: code +```twig +{# Fetch revisions by the current user #} +{% set entries = craft.entries() + .revisionCreator(currentUser) + .all() %} +``` + +```php +// Fetch revisions by the current user +$entries = \craft\elements\Entry::find() + ->revisionCreator(Craft::$app->user->identity) + ->all(); +``` +::: + + +#### `revisionId` + +Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). + + + +Possible values include: + +| Value | Fetches revisions… +| - | - +| `1` | for the revision with an ID of 1. + + + +::: code +```twig +{# Fetch a revision #} +{% set entries = craft.entries() + .revisionId(10) + .all() %} +``` + +```php +// Fetch a revision +$entries = \craft\elements\Entry::find() + ->revisionIf(10) + ->all(); +``` +::: + + +#### `revisionOf` + +Narrows the query results to only revisions of a given entry. + + + +Possible values include: + +| Value | Fetches revisions… +| - | - +| `1` | for the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | for the entry represented by the object. + + + +::: code +```twig +{# Fetch revisions of the entry #} +{% set entries = craft.entries() + .revisionOf(myEntry) + .all() %} +``` + +```php +// Fetch revisions of the entry +$entries = \craft\elements\Entry::find() + ->revisionOf($myEntry) + ->all(); +``` +::: + + +#### `revisions` + +Narrows the query results to only revision entries. + + + + + +::: code +```twig +{# Fetch a revision entry #} +{% set entries = craft.entries() + .revisions() + .id(123) + .one() %} +``` + +```php +// Fetch a revision entry +$entries = \craft\elements\Entry::find() + ->revisions() + ->id(123) + ->one(); +``` +::: + + +#### `savable` + +Sets the [savable](https://docs.craftcms.com/api/v3/craft-elements-db-entryquery.html#savable) property. + + + + + + +#### `savedDraftsOnly` + +Narrows the query results to only unpublished drafts which have been saved after initial creation. + + + + + +::: code +```twig +{# Fetch saved, unpublished draft entries #} +{% set entries = craft.entries() + .draftOf(false) + .savedDraftsOnly() + .all() %} +``` + +```php +// Fetch saved, unpublished draft entries +$entries = \craft\elements\Entry::find() + ->draftOf(false) + ->savedDraftsOnly() + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only entries that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all entries that match the search query #} +{% set entries = craft.entries() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all entries that match the search query +$entries = \craft\elements\Entry::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `section` + +Narrows the query results based on the sections the entries belong to. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | in a section with a handle of `foo`. +| `'not foo'` | not in a section with a handle of `foo`. +| `['foo', 'bar']` | in a section with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a section with a handle of `foo` or `bar`. +| a [Section](craft4:craft\models\Section) object | in a section represented by the object. + + + +::: code +```twig +{# Fetch entries in the Foo section #} +{% set entries = craft.entries() + .section('foo') + .all() %} +``` + +```php +// Fetch entries in the Foo section +$entries = \craft\elements\Entry::find() + ->section('foo') + ->all(); +``` +::: + + +#### `sectionId` + +Narrows the query results based on the sections the entries belong to, per the sections’ IDs. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | in a section with an ID of 1. +| `'not 1'` | not in a section with an ID of 1. +| `[1, 2]` | in a section with an ID of 1 or 2. +| `['not', 1, 2]` | not in a section with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch entries in the section with an ID of 1 #} +{% set entries = craft.entries() + .sectionId(1) + .all() %} +``` + +```php +// Fetch entries in the section with an ID of 1 +$entries = \craft\elements\Entry::find() + ->sectionId(1) + ->all(); +``` +::: + + +#### `siblingOf` + +Narrows the query results to only entries that are siblings of another entry in its structure. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | beside the entry with an ID of 1. +| a [Entry](craft4:craft\elements\Entry) object | beside the entry represented by the object. + + + +::: code +```twig +{# Fetch entries beside this one #} +{% set entries = craft.entries() + .siblingOf(myEntry) + .all() %} +``` + +```php +// Fetch entries beside this one +$entries = \craft\elements\Entry::find() + ->siblingOf($myEntry) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the entries should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch entries from the Foo site #} +{% set entries = craft.entries() + .site('foo') + .all() %} +``` + +```php +// Fetch entries from the Foo site +$entries = \craft\elements\Entry::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the entries should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch entries from the site with an ID of 1 #} +{% set entries = craft.entries() + .siteId(1) + .all() %} +``` + +```php +// Fetch entries from the site with an ID of 1 +$entries = \craft\elements\Entry::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the entries’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the entry by its ID in the elements_sites table #} +{% set entry = craft.entries() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the entry by its ID in the elements_sites table +$entry = \craft\elements\Entry::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `slug` + +Narrows the query results based on the entries’ slugs. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | with a slug of `foo`. +| `'foo*'` | with a slug that begins with `foo`. +| `'*foo'` | with a slug that ends with `foo`. +| `'*foo*'` | with a slug that contains `foo`. +| `'not *foo*'` | with a slug that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested entry slug from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the entry with that slug #} +{% set entry = craft.entries() + .slug(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested entry slug from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the entry with that slug +$entry = \craft\elements\Entry::find() + ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the entries’ statuses. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'live'` _(default)_ | that are live. +| `'pending'` | that are pending (enabled with a Post Date in the future). +| `'expired'` | that are expired (enabled with an Expiry Date in the past). +| `'disabled'` | that are disabled. +| `['live', 'pending']` | that are live or pending. +| `['not', 'live', 'pending']` | that are not live or pending. + + + +::: code +```twig +{# Fetch disabled entries #} +{% set entries = craft.entries() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled entries +$entries = \craft\elements\Entry::find() + ->status('disabled') + ->all(); +``` +::: + + +#### `title` + +Narrows the query results based on the entries’ titles. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch entries with a title that contains "Foo" #} +{% set entries = craft.entries() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch entries with a title that contains "Foo" +$entries = \craft\elements\Entry::find() + ->title('*Foo*') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only entries that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed entries #} +{% set entries = craft.entries() + .trashed() + .all() %} +``` + +```php +// Fetch trashed entries +$entries = \craft\elements\Entry::find() + ->trashed() + ->all(); +``` +::: + + +#### `type` + +Narrows the query results based on the entries’ entry types. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | of a type with a handle of `foo`. +| `'not foo'` | not of a type with a handle of `foo`. +| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. +| an [EntryType](craft4:craft\models\EntryType) object | of a type represented by the object. + + + +::: code +```twig +{# Fetch entries in the Foo section with a Bar entry type #} +{% set entries = craft.entries() + .section('foo') + .type('bar') + .all() %} +``` + +```php +// Fetch entries in the Foo section with a Bar entry type +$entries = \craft\elements\Entry::find() + ->section('foo') + ->type('bar') + ->all(); +``` +::: + + +#### `typeId` + +Narrows the query results based on the entries’ entry types, per the types’ IDs. + +Possible values include: + +| Value | Fetches entries… +| - | - +| `1` | of a type with an ID of 1. +| `'not 1'` | not of a type with an ID of 1. +| `[1, 2]` | of a type with an ID of 1 or 2. +| `['not', 1, 2]` | not of a type with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch entries of the entry type with an ID of 1 #} +{% set entries = craft.entries() + .typeId(1) + .all() %} +``` + +```php +// Fetch entries of the entry type with an ID of 1 +$entries = \craft\elements\Entry::find() + ->typeId(1) + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the entries’ UIDs. + + + + + +::: code +```twig +{# Fetch the entry by its UID #} +{% set entry = craft.entries() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the entry by its UID +$entry = \craft\elements\Entry::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique entries across all sites #} +{% set entries = craft.entries() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique entries across all sites +$entries = \craft\elements\Entry::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `uri` + +Narrows the query results based on the entries’ URIs. + + + +Possible values include: + +| Value | Fetches entries… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the entry with that URI #} +{% set entry = craft.entries() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the entry with that URI +$entry = \craft\elements\Entry::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching entries eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch entries eager-loaded with the "Related" field’s relations #} +{% set entries = craft.entries() + .with(['related']) + .all() %} +``` + +```php +// Fetch entries eager-loaded with the "Related" field’s relations +$entries = \craft\elements\Entry::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/4.x/event-data/events.json b/docs/.artifacts/cms/4.x/events.json similarity index 99% rename from docs/4.x/event-data/events.json rename to docs/.artifacts/cms/4.x/events.json index 96f97f750..7afaf3f70 100644 --- a/docs/4.x/event-data/events.json +++ b/docs/.artifacts/cms/4.x/events.json @@ -28337,6 +28337,138 @@ "type": "yii\\base\\Event", "desc": "an event raised at the end of `validate()`" }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_BEFORE_ELEMENT_SAVE", + "type": "craft\\events\\FieldElementEvent", + "desc": "The event that is triggered before the element is saved." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_AFTER_ELEMENT_SAVE", + "type": "craft\\events\\FieldElementEvent", + "desc": "The event that is triggered after the element is saved." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_AFTER_ELEMENT_PROPAGATE", + "type": "craft\\events\\FieldElementEvent", + "desc": "The event that is triggered after the element is fully saved and propagated to other sites." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_BEFORE_ELEMENT_DELETE", + "type": "craft\\events\\FieldElementEvent", + "desc": "The event that is triggered before the element is deleted." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_AFTER_ELEMENT_DELETE", + "type": "craft\\events\\FieldElementEvent", + "desc": "The event that is triggered after the element is deleted." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_BEFORE_ELEMENT_RESTORE", + "type": "craft\\events\\FieldElementEvent", + "desc": "The event that is triggered before the element is restored." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_AFTER_ELEMENT_RESTORE", + "type": "craft\\events\\FieldElementEvent", + "desc": "The event that is triggered after the element is restored." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_DEFINE_KEYWORDS", + "type": "craft\\events\\DefineFieldKeywordsEvent", + "desc": "The event that is triggered when defining the field’s search keywords for an element." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_DEFINE_INPUT_HTML", + "type": "craft\\events\\DefineFieldHtmlEvent", + "desc": "The event that is triggered when defining the field’s input HTML." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_BEFORE_SAVE", + "type": "craft\\events\\ModelEvent", + "desc": "The event that is triggered before the component is saved." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_AFTER_SAVE", + "type": "craft\\events\\ModelEvent", + "desc": "The event that is triggered after the component is saved." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_BEFORE_DELETE", + "type": "craft\\events\\ModelEvent", + "desc": "The event that is triggered before the component is deleted." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_BEFORE_APPLY_DELETE", + "type": "craft\\events\\ModelEvent", + "desc": "The event that is triggered before the delete is applied to the database." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_AFTER_DELETE", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the component is deleted." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_DEFINE_SETTINGS_ATTRIBUTES", + "type": "craft\\events\\DefineValueEvent", + "desc": "The event that is triggered when defining the component’s settings attributes, as returned by `settingsAttributes()`." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_INIT", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the model's init cycle" + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_DEFINE_RULES", + "type": "craft\\events\\DefineRulesEvent", + "desc": "The event that is triggered when defining the model rules" + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_DEFINE_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the arrayable fields" + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_DEFINE_EXTRA_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the extra arrayable fields" + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_BEFORE_VALIDATE", + "type": "yii\\base\\ModelEvent", + "desc": "an event raised at the beginning of `validate()`. You may set `ModelEvent::isValid` to be false to stop the validation." + }, + { + "class": "craft\\fields\\Country", + "name": "EVENT_AFTER_VALIDATE", + "type": "yii\\base\\Event", + "desc": "an event raised at the end of `validate()`" + }, { "class": "craft\\fields\\Date", "name": "EVENT_BEFORE_ELEMENT_SAVE", @@ -30623,6 +30755,48 @@ "type": "yii\\base\\Event", "desc": "an event raised at the end of `validate()`" }, + { + "class": "craft\\fields\\conditions\\CountryFieldConditionRule", + "name": "EVENT_INIT", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the model's init cycle" + }, + { + "class": "craft\\fields\\conditions\\CountryFieldConditionRule", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, + { + "class": "craft\\fields\\conditions\\CountryFieldConditionRule", + "name": "EVENT_DEFINE_RULES", + "type": "craft\\events\\DefineRulesEvent", + "desc": "The event that is triggered when defining the model rules" + }, + { + "class": "craft\\fields\\conditions\\CountryFieldConditionRule", + "name": "EVENT_DEFINE_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the arrayable fields" + }, + { + "class": "craft\\fields\\conditions\\CountryFieldConditionRule", + "name": "EVENT_DEFINE_EXTRA_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the extra arrayable fields" + }, + { + "class": "craft\\fields\\conditions\\CountryFieldConditionRule", + "name": "EVENT_BEFORE_VALIDATE", + "type": "yii\\base\\ModelEvent", + "desc": "an event raised at the beginning of `validate()`. You may set `ModelEvent::isValid` to be false to stop the validation." + }, + { + "class": "craft\\fields\\conditions\\CountryFieldConditionRule", + "name": "EVENT_AFTER_VALIDATE", + "type": "yii\\base\\Event", + "desc": "an event raised at the end of `validate()`" + }, { "class": "craft\\fields\\conditions\\DateFieldConditionRule", "name": "EVENT_INIT", @@ -37306,6 +37480,12 @@ } } }, + { + "class": "craft\\services\\Elements", + "name": "EVENT_SET_ELEMENT_URI", + "type": "craft\\events\\ElementEvent", + "desc": "The event that is triggered when setting a unique URI on an element." + }, { "class": "craft\\services\\Elements", "name": "EVENT_BEFORE_UPDATE_SEARCH_INDEX", @@ -37530,6 +37710,12 @@ "type": "craft\\events\\RegisterComponentTypesEvent", "desc": "The event that is triggered when registering field types." }, + { + "class": "craft\\services\\Fields", + "name": "EVENT_DEFINE_COMPATIBLE_FIELD_TYPES", + "type": "craft\\events\\DefineCompatibleFieldTypesEvent", + "desc": "The event that is triggered when defining the compatible field types for a field." + }, { "class": "craft\\services\\Fields", "name": "EVENT_BEFORE_SAVE_FIELD_GROUP", @@ -38244,6 +38430,12 @@ "type": "craft\\events\\UserGroupsAssignEvent", "desc": "The event that is triggered after a user is assigned to some user groups." }, + { + "class": "craft\\services\\Users", + "name": "EVENT_DEFINE_DEFAULT_USER_GROUPS", + "type": "craft\\events\\DefineUserGroupsEvent", + "desc": "The event that is triggered when defining the default user groups to assign to a publicly-registered user." + }, { "class": "craft\\services\\Users", "name": "EVENT_BEFORE_ASSIGN_USER_TO_DEFAULT_GROUP", diff --git a/docs/.artifacts/cms/4.x/globals.md b/docs/.artifacts/cms/4.x/globals.md new file mode 100644 index 000000000..3e9917bbd --- /dev/null +++ b/docs/.artifacts/cms/4.x/globals.md @@ -0,0 +1,754 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only global sets that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](craft4:craft\elements\GlobalSet) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [collect](#collect) | +| [dateCreated](#datecreated) | Narrows the query results based on the global sets’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the global sets’ last-updated dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [handle](#handle) | Narrows the query results based on the global sets’ handles. +| [id](#id) | Narrows the query results based on the global sets’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [limit](#limit) | Determines the number of global sets that should be returned. +| [offset](#offset) | Determines how many global sets should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the global sets should be returned in. (If empty, defaults to `sortOrder ASC`.) +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [relatedTo](#relatedto) | Narrows the query results to only global sets that are related to certain other elements. +| [search](#search) | Narrows the query results to only global sets that match a search query. +| [site](#site) | Determines which site(s) the global sets should be queried in. +| [siteId](#siteid) | Determines which site(s) the global sets should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the global sets’ IDs in the `elements_sites` table. +| [trashed](#trashed) | Narrows the query results to only global sets that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the global sets’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [with](#with) | Causes the query to return matching global sets eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only global sets that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all global sets that are related to myCategoryA and myCategoryB #} +{% set globalSets = craft.globalSets() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all global sets that are related to $myCategoryA and $myCategoryB +$globalSets = \craft\elements\GlobalSet::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](craft4:craft\elements\GlobalSet) objects. + + + + + +::: code +```twig +{# Fetch global sets as arrays #} +{% set globalSets = craft.globalSets() + .asArray() + .all() %} +``` + +```php +// Fetch global sets as arrays +$globalSets = \craft\elements\GlobalSet::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `collect` + + + + + + + + +#### `dateCreated` + +Narrows the query results based on the global sets’ creation dates. + + + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch global sets created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set globalSets = craft.globalSets() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch global sets created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$globalSets = \craft\elements\GlobalSet::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the global sets’ last-updated dates. + + + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch global sets updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set globalSets = craft.globalSets() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch global sets updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$globalSets = \craft\elements\GlobalSet::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch global sets in a specific order #} +{% set globalSets = craft.globalSets() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch global sets in a specific order +$globalSets = \craft\elements\GlobalSet::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `handle` + +Narrows the query results based on the global sets’ handles. + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `'foo'` | with a handle of `foo`. +| `'not foo'` | not with a handle of `foo`. +| `['foo', 'bar']` | with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not with a handle of `foo` or `bar`. + + + +::: code +```twig +{# Fetch the global set with a handle of 'foo' #} +{% set globalSet = craft.globalSets() + .handle('foo') + .one() %} +``` + +```php +// Fetch the global set with a handle of 'foo' +$globalSet = \craft\elements\GlobalSet::find() + ->handle('foo') + ->one(); +``` +::: + + +#### `id` + +Narrows the query results based on the global sets’ IDs. + + + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the global set by its ID #} +{% set globalSet = craft.globalSets() + .id(1) + .one() %} +``` + +```php +// Fetch the global set by its ID +$globalSet = \craft\elements\GlobalSet::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch global sets in reverse #} +{% set globalSets = craft.globalSets() + .inReverse() + .all() %} +``` + +```php +// Fetch global sets in reverse +$globalSets = \craft\elements\GlobalSet::find() + ->inReverse() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of global sets that should be returned. + + + +::: code +```twig +{# Fetch up to 10 global sets #} +{% set globalSets = craft.globalSets() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 global sets +$globalSets = \craft\elements\GlobalSet::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many global sets should be skipped in the results. + + + +::: code +```twig +{# Fetch all global sets except for the first 3 #} +{% set globalSets = craft.globalSets() + .offset(3) + .all() %} +``` + +```php +// Fetch all global sets except for the first 3 +$globalSets = \craft\elements\GlobalSet::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the global sets should be returned in. (If empty, defaults to `sortOrder ASC`.) + + + +::: code +```twig +{# Fetch all global sets in order of date created #} +{% set globalSets = craft.globalSets() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all global sets in order of date created +$globalSets = \craft\elements\GlobalSet::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique global sets from Site A, or Site B if they don’t exist in Site A #} +{% set globalSets = craft.globalSets() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique global sets from Site A, or Site B if they don’t exist in Site A +$globalSets = \craft\elements\GlobalSet::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `relatedTo` + +Narrows the query results to only global sets that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all global sets that are related to myCategory #} +{% set globalSets = craft.globalSets() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all global sets that are related to $myCategory +$globalSets = \craft\elements\GlobalSet::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only global sets that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all global sets that match the search query #} +{% set globalSets = craft.globalSets() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all global sets that match the search query +$globalSets = \craft\elements\GlobalSet::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the global sets should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch global sets from the Foo site #} +{% set globalSets = craft.globalSets() + .site('foo') + .all() %} +``` + +```php +// Fetch global sets from the Foo site +$globalSets = \craft\elements\GlobalSet::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the global sets should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch global sets from the site with an ID of 1 #} +{% set globalSets = craft.globalSets() + .siteId(1) + .all() %} +``` + +```php +// Fetch global sets from the site with an ID of 1 +$globalSets = \craft\elements\GlobalSet::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the global sets’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches global sets… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the global set by its ID in the elements_sites table #} +{% set globalSet = craft.globalSets() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the global set by its ID in the elements_sites table +$globalSet = \craft\elements\GlobalSet::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `trashed` + +Narrows the query results to only global sets that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed global sets #} +{% set globalSets = craft.globalSets() + .trashed() + .all() %} +``` + +```php +// Fetch trashed global sets +$globalSets = \craft\elements\GlobalSet::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the global sets’ UIDs. + + + + + +::: code +```twig +{# Fetch the global set by its UID #} +{% set globalSet = craft.globalSets() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the global set by its UID +$globalSet = \craft\elements\GlobalSet::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique global sets across all sites #} +{% set globalSets = craft.globalSets() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique global sets across all sites +$globalSets = \craft\elements\GlobalSet::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `with` + +Causes the query to return matching global sets eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch global sets eager-loaded with the "Related" field’s relations #} +{% set globalSets = craft.globalSets() + .with(['related']) + .all() %} +``` + +```php +// Fetch global sets eager-loaded with the "Related" field’s relations +$globalSets = \craft\elements\GlobalSet::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/4.x/matrix-blocks.md b/docs/.artifacts/cms/4.x/matrix-blocks.md new file mode 100644 index 000000000..b7cd0f7b3 --- /dev/null +++ b/docs/.artifacts/cms/4.x/matrix-blocks.md @@ -0,0 +1,1033 @@ + + + + + + + + +| Param | Description +| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [allowOwnerDrafts](#allowownerdrafts) | Narrows the query results based on whether the Matrix blocks’ owners are drafts. +| [allowOwnerRevisions](#allowownerrevisions) | Narrows the query results based on whether the Matrix blocks’ owners are revisions. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](craft4:craft\elements\MatrixBlock) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [collect](#collect) | +| [dateCreated](#datecreated) | Narrows the query results based on the Matrix blocks’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the Matrix blocks’ last-updated dates. +| [field](#field) | Narrows the query results based on the field the Matrix blocks belong to. +| [fieldId](#fieldid) | Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [id](#id) | Narrows the query results based on the Matrix blocks’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [limit](#limit) | Determines the number of Matrix blocks that should be returned. +| [offset](#offset) | Determines how many Matrix blocks should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) +| [owner](#owner) | Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. +| [ownerId](#ownerid) | Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [primaryOwner](#primaryowner) | Sets the [primaryOwnerId](#primaryownerid) and [siteId](#siteid) parameters based on a given element. +| [primaryOwnerId](#primaryownerid) | Narrows the query results based on the primary owner element of the Matrix blocks, per the owners’ IDs. +| [relatedTo](#relatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. +| [search](#search) | Narrows the query results to only Matrix blocks that match a search query. +| [site](#site) | Determines which site(s) the Matrix blocks should be queried in. +| [siteId](#siteid) | Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the Matrix blocks’ IDs in the `elements_sites` table. +| [status](#status) | Narrows the query results based on the Matrix blocks’ statuses. +| [trashed](#trashed) | Narrows the query results to only Matrix blocks that have been soft-deleted. +| [type](#type) | Narrows the query results based on the Matrix blocks’ block types. +| [typeId](#typeid) | Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. +| [uid](#uid) | Narrows the query results based on the Matrix blocks’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [with](#with) | Causes the query to return matching Matrix blocks eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `allowOwnerDrafts` + +Narrows the query results based on whether the Matrix blocks’ owners are drafts. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `true` | which can belong to a draft. +| `false` | which cannot belong to a draft. + + + + +#### `allowOwnerRevisions` + +Narrows the query results based on whether the Matrix blocks’ owners are revisions. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `true` | which can belong to a revision. +| `false` | which cannot belong to a revision. + + + + +#### `andRelatedTo` + +Narrows the query results to only Matrix blocks that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all Matrix blocks that are related to myCategoryA and myCategoryB #} +{% set MatrixBlocks = craft.matrixBlocks() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all Matrix blocks that are related to $myCategoryA and $myCategoryB +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](craft4:craft\elements\MatrixBlock) objects. + + + + + +::: code +```twig +{# Fetch Matrix blocks as arrays #} +{% set MatrixBlocks = craft.matrixBlocks() + .asArray() + .all() %} +``` + +```php +// Fetch Matrix blocks as arrays +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `collect` + + + + + + + + +#### `dateCreated` + +Narrows the query results based on the Matrix blocks’ creation dates. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch Matrix blocks created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set MatrixBlocks = craft.matrixBlocks() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch Matrix blocks created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the Matrix blocks’ last-updated dates. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch Matrix blocks updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set MatrixBlocks = craft.matrixBlocks() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch Matrix blocks updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `field` + +Narrows the query results based on the field the Matrix blocks belong to. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'foo'` | in a field with a handle of `foo`. +| `'not foo'` | not in a field with a handle of `foo`. +| `['foo', 'bar']` | in a field with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a field with a handle of `foo` or `bar`. +| a [craft\fields\Matrix](craft4:craft\fields\Matrix) object | in a field represented by the object. + + + +::: code +```twig +{# Fetch Matrix blocks in the Foo field #} +{% set MatrixBlocks = craft.matrixBlocks() + .field('foo') + .all() %} +``` + +```php +// Fetch Matrix blocks in the Foo field +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->field('foo') + ->all(); +``` +::: + + +#### `fieldId` + +Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | in a field with an ID of 1. +| `'not 1'` | not in a field with an ID of 1. +| `[1, 2]` | in a field with an ID of 1 or 2. +| `['not', 1, 2]` | not in a field with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch Matrix blocks in the field with an ID of 1 #} +{% set MatrixBlocks = craft.matrixBlocks() + .fieldId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks in the field with an ID of 1 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->fieldId(1) + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch Matrix blocks in a specific order #} +{% set MatrixBlocks = craft.matrixBlocks() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch Matrix blocks in a specific order +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the Matrix blocks’ IDs. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the Matrix block by its ID #} +{% set MatrixBlock = craft.matrixBlocks() + .id(1) + .one() %} +``` + +```php +// Fetch the Matrix block by its ID +$MatrixBlock = \craft\elements\MatrixBlock::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch Matrix blocks in reverse #} +{% set MatrixBlocks = craft.matrixBlocks() + .inReverse() + .all() %} +``` + +```php +// Fetch Matrix blocks in reverse +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->inReverse() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of Matrix blocks that should be returned. + + + +::: code +```twig +{# Fetch up to 10 Matrix blocks #} +{% set MatrixBlocks = craft.matrixBlocks() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 Matrix blocks +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many Matrix blocks should be skipped in the results. + + + +::: code +```twig +{# Fetch all Matrix blocks except for the first 3 #} +{% set MatrixBlocks = craft.matrixBlocks() + .offset(3) + .all() %} +``` + +```php +// Fetch all Matrix blocks except for the first 3 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) + + + +::: code +```twig +{# Fetch all Matrix blocks in order of date created #} +{% set MatrixBlocks = craft.matrixBlocks() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all Matrix blocks in order of date created +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `owner` + +Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. + + + +::: code +```twig +{# Fetch Matrix blocks created for this entry #} +{% set MatrixBlocks = craft.matrixBlocks() + .owner(myEntry) + .all() %} +``` + +```php +// Fetch Matrix blocks created for this entry +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->owner($myEntry) + ->all(); +``` +::: + + +#### `ownerId` + +Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | created for an element with an ID of 1. +| `'not 1'` | not created for an element with an ID of 1. +| `[1, 2]` | created for an element with an ID of 1 or 2. +| `['not', 1, 2]` | not created for an element with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch Matrix blocks created for an element with an ID of 1 #} +{% set MatrixBlocks = craft.matrixBlocks() + .ownerId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks created for an element with an ID of 1 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->ownerId(1) + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique Matrix blocks from Site A, or Site B if they don’t exist in Site A #} +{% set MatrixBlocks = craft.matrixBlocks() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique Matrix blocks from Site A, or Site B if they don’t exist in Site A +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `primaryOwner` + +Sets the [primaryOwnerId](#primaryownerid) and [siteId](#siteid) parameters based on a given element. + + + +::: code +```twig +{# Fetch Matrix blocks created for this entry #} +{% set MatrixBlocks = craft.matrixBlocks() + .primaryOwner(myEntry) + .all() %} +``` + +```php +// Fetch Matrix blocks created for this entry +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->primaryOwner($myEntry) + ->all(); +``` +::: + + +#### `primaryOwnerId` + +Narrows the query results based on the primary owner element of the Matrix blocks, per the owners’ IDs. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | created for an element with an ID of 1. +| `'not 1'` | not created for an element with an ID of 1. +| `[1, 2]` | created for an element with an ID of 1 or 2. +| `['not', 1, 2]` | not created for an element with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch Matrix blocks created for an element with an ID of 1 #} +{% set MatrixBlocks = craft.matrixBlocks() + .primaryOwnerId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks created for an element with an ID of 1 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->primaryOwnerId(1) + ->all(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only Matrix blocks that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all Matrix blocks that are related to myCategory #} +{% set MatrixBlocks = craft.matrixBlocks() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all Matrix blocks that are related to $myCategory +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only Matrix blocks that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all Matrix blocks that match the search query #} +{% set MatrixBlocks = craft.matrixBlocks() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all Matrix blocks that match the search query +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the Matrix blocks should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch Matrix blocks from the Foo site #} +{% set MatrixBlocks = craft.matrixBlocks() + .site('foo') + .all() %} +``` + +```php +// Fetch Matrix blocks from the Foo site +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch Matrix blocks from the site with an ID of 1 #} +{% set MatrixBlocks = craft.matrixBlocks() + .siteId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks from the site with an ID of 1 +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the Matrix blocks’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the Matrix block by its ID in the elements_sites table #} +{% set MatrixBlock = craft.matrixBlocks() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the Matrix block by its ID in the elements_sites table +$MatrixBlock = \craft\elements\MatrixBlock::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the Matrix blocks’ statuses. + + + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'enabled'` _(default)_ | that are enabled. +| `'disabled'` | that are disabled. +| `['not', 'disabled']` | that are not disabled. + + + +::: code +```twig +{# Fetch disabled Matrix blocks #} +{% set MatrixBlocks = craft.matrixBlocks() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled Matrix blocks +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->status('disabled') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only Matrix blocks that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed Matrix blocks #} +{% set MatrixBlocks = craft.matrixBlocks() + .trashed() + .all() %} +``` + +```php +// Fetch trashed Matrix blocks +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->trashed() + ->all(); +``` +::: + + +#### `type` + +Narrows the query results based on the Matrix blocks’ block types. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `'foo'` | of a type with a handle of `foo`. +| `'not foo'` | not of a type with a handle of `foo`. +| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. +| an [MatrixBlockType](craft4:craft\models\MatrixBlockType) object | of a type represented by the object. + + + +::: code +```twig +{# Fetch Matrix blocks with a Foo block type #} +{% set MatrixBlocks = myEntry.myMatrixField + .type('foo') + .all() %} +``` + +```php +// Fetch Matrix blocks with a Foo block type +$MatrixBlocks = $myEntry->myMatrixField + ->type('foo') + ->all(); +``` +::: + + +#### `typeId` + +Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. + +Possible values include: + +| Value | Fetches Matrix blocks… +| - | - +| `1` | of a type with an ID of 1. +| `'not 1'` | not of a type with an ID of 1. +| `[1, 2]` | of a type with an ID of 1 or 2. +| `['not', 1, 2]` | not of a type with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch Matrix blocks of the block type with an ID of 1 #} +{% set MatrixBlocks = myEntry.myMatrixField + .typeId(1) + .all() %} +``` + +```php +// Fetch Matrix blocks of the block type with an ID of 1 +$MatrixBlocks = $myEntry->myMatrixField + ->typeId(1) + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the Matrix blocks’ UIDs. + + + + + +::: code +```twig +{# Fetch the Matrix block by its UID #} +{% set MatrixBlock = craft.matrixBlocks() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the Matrix block by its UID +$MatrixBlock = \craft\elements\MatrixBlock::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique Matrix blocks across all sites #} +{% set MatrixBlocks = craft.matrixBlocks() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique Matrix blocks across all sites +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `with` + +Causes the query to return matching Matrix blocks eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch Matrix blocks eager-loaded with the "Related" field’s relations #} +{% set MatrixBlocks = craft.matrixBlocks() + .with(['related']) + .all() %} +``` + +```php +// Fetch Matrix blocks eager-loaded with the "Related" field’s relations +$MatrixBlocks = \craft\elements\MatrixBlock::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/4.x/tags.md b/docs/.artifacts/cms/4.x/tags.md new file mode 100644 index 000000000..897953c18 --- /dev/null +++ b/docs/.artifacts/cms/4.x/tags.md @@ -0,0 +1,870 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only tags that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching tags as arrays of data, rather than [Tag](craft4:craft\elements\Tag) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [collect](#collect) | +| [dateCreated](#datecreated) | Narrows the query results based on the tags’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the tags’ last-updated dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [group](#group) | Narrows the query results based on the tag groups the tags belong to. +| [groupId](#groupid) | Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. +| [id](#id) | Narrows the query results based on the tags’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [limit](#limit) | Determines the number of tags that should be returned. +| [offset](#offset) | Determines how many tags should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) +| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [relatedTo](#relatedto) | Narrows the query results to only tags that are related to certain other elements. +| [search](#search) | Narrows the query results to only tags that match a search query. +| [site](#site) | Determines which site(s) the tags should be queried in. +| [siteId](#siteid) | Determines which site(s) the tags should be queried in, per the site’s ID. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the tags’ IDs in the `elements_sites` table. +| [title](#title) | Narrows the query results based on the tags’ titles. +| [trashed](#trashed) | Narrows the query results to only tags that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the tags’ UIDs. +| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uri](#uri) | Narrows the query results based on the tags’ URIs. +| [with](#with) | Causes the query to return matching tags eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only tags that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all tags that are related to myCategoryA and myCategoryB #} +{% set tags = craft.tags() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all tags that are related to $myCategoryA and $myCategoryB +$tags = \craft\elements\Tag::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching tags as arrays of data, rather than [Tag](craft4:craft\elements\Tag) objects. + + + + + +::: code +```twig +{# Fetch tags as arrays #} +{% set tags = craft.tags() + .asArray() + .all() %} +``` + +```php +// Fetch tags as arrays +$tags = \craft\elements\Tag::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `collect` + + + + + + + + +#### `dateCreated` + +Narrows the query results based on the tags’ creation dates. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch tags created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set tags = craft.tags() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch tags created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$tags = \craft\elements\Tag::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the tags’ last-updated dates. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch tags updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set tags = craft.tags() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch tags updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$tags = \craft\elements\Tag::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch tags in a specific order #} +{% set tags = craft.tags() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch tags in a specific order +$tags = \craft\elements\Tag::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `group` + +Narrows the query results based on the tag groups the tags belong to. + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'foo'` | in a group with a handle of `foo`. +| `'not foo'` | not in a group with a handle of `foo`. +| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. +| a [TagGroup](craft4:craft\models\TagGroup) object | in a group represented by the object. + + + +::: code +```twig +{# Fetch tags in the Foo group #} +{% set tags = craft.tags() + .group('foo') + .all() %} +``` + +```php +// Fetch tags in the Foo group +$tags = \craft\elements\Tag::find() + ->group('foo') + ->all(); +``` +::: + + +#### `groupId` + +Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. + +Possible values include: + +| Value | Fetches tags… +| - | - +| `1` | in a group with an ID of 1. +| `'not 1'` | not in a group with an ID of 1. +| `[1, 2]` | in a group with an ID of 1 or 2. +| `['not', 1, 2]` | not in a group with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch tags in the group with an ID of 1 #} +{% set tags = craft.tags() + .groupId(1) + .all() %} +``` + +```php +// Fetch tags in the group with an ID of 1 +$tags = \craft\elements\Tag::find() + ->groupId(1) + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the tags’ IDs. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the tag by its ID #} +{% set tag = craft.tags() + .id(1) + .one() %} +``` + +```php +// Fetch the tag by its ID +$tag = \craft\elements\Tag::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch tags in reverse #} +{% set tags = craft.tags() + .inReverse() + .all() %} +``` + +```php +// Fetch tags in reverse +$tags = \craft\elements\Tag::find() + ->inReverse() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of tags that should be returned. + + + +::: code +```twig +{# Fetch up to 10 tags #} +{% set tags = craft.tags() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 tags +$tags = \craft\elements\Tag::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many tags should be skipped in the results. + + + +::: code +```twig +{# Fetch all tags except for the first 3 #} +{% set tags = craft.tags() + .offset(3) + .all() %} +``` + +```php +// Fetch all tags except for the first 3 +$tags = \craft\elements\Tag::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) + + + +::: code +```twig +{# Fetch all tags in order of date created #} +{% set tags = craft.tags() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all tags in order of date created +$tags = \craft\elements\Tag::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique tags from Site A, or Site B if they don’t exist in Site A #} +{% set tags = craft.tags() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique tags from Site A, or Site B if they don’t exist in Site A +$tags = \craft\elements\Tag::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `relatedTo` + +Narrows the query results to only tags that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all tags that are related to myCategory #} +{% set tags = craft.tags() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all tags that are related to $myCategory +$tags = \craft\elements\Tag::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only tags that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all tags that match the search query #} +{% set tags = craft.tags() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all tags that match the search query +$tags = \craft\elements\Tag::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `site` + +Determines which site(s) the tags should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch tags from the Foo site #} +{% set tags = craft.tags() + .site('foo') + .all() %} +``` + +```php +// Fetch tags from the Foo site +$tags = \craft\elements\Tag::find() + ->site('foo') + ->all(); +``` +::: + + +#### `siteId` + +Determines which site(s) the tags should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches tags… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch tags from the site with an ID of 1 #} +{% set tags = craft.tags() + .siteId(1) + .all() %} +``` + +```php +// Fetch tags from the site with an ID of 1 +$tags = \craft\elements\Tag::find() + ->siteId(1) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the tags’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the tag by its ID in the elements_sites table #} +{% set tag = craft.tags() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the tag by its ID in the elements_sites table +$tag = \craft\elements\Tag::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `title` + +Narrows the query results based on the tags’ titles. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch tags with a title that contains "Foo" #} +{% set tags = craft.tags() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch tags with a title that contains "Foo" +$tags = \craft\elements\Tag::find() + ->title('*Foo*') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only tags that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed tags #} +{% set tags = craft.tags() + .trashed() + .all() %} +``` + +```php +// Fetch trashed tags +$tags = \craft\elements\Tag::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the tags’ UIDs. + + + + + +::: code +```twig +{# Fetch the tag by its UID #} +{% set tag = craft.tags() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the tag by its UID +$tag = \craft\elements\Tag::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique tags across all sites #} +{% set tags = craft.tags() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique tags across all sites +$tags = \craft\elements\Tag::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +#### `uri` + +Narrows the query results based on the tags’ URIs. + + + +Possible values include: + +| Value | Fetches tags… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the tag with that URI #} +{% set tag = craft.tags() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the tag with that URI +$tag = \craft\elements\Tag::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching tags eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch tags eager-loaded with the "Related" field’s relations #} +{% set tags = craft.tags() + .with(['related']) + .all() %} +``` + +```php +// Fetch tags eager-loaded with the "Related" field’s relations +$tags = \craft\elements\Tag::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/cms/4.x/users.md b/docs/.artifacts/cms/4.x/users.md new file mode 100644 index 000000000..ff6f33f2e --- /dev/null +++ b/docs/.artifacts/cms/4.x/users.md @@ -0,0 +1,1069 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [admin](#admin) | Narrows the query results to only users that have admin accounts. +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only users that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching users as arrays of data, rather than [User](craft4:craft\elements\User) objects. +| [assetUploaders](#assetuploaders) | Narrows the query results to only users that have uploaded an asset. +| [authors](#authors) | Narrows the query results to only users that are authors of an entry. +| [cache](#cache) | Enables query cache for this Query. +| [can](#can) | Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [collect](#collect) | +| [dateCreated](#datecreated) | Narrows the query results based on the users’ creation dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the users’ last-updated dates. +| [email](#email) | Narrows the query results based on the users’ email addresses. +| [firstName](#firstname) | Narrows the query results based on the users’ first names. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [fullName](#fullname) | Narrows the query results based on the users’ full names. +| [group](#group) | Narrows the query results based on the user group the users belong to. +| [groupId](#groupid) | Narrows the query results based on the user group the users belong to, per the groups’ IDs. +| [hasPhoto](#hasphoto) | Narrows the query results to only users that have (or don’t have) a user photo. +| [id](#id) | Narrows the query results based on the users’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching users as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [lastLoginDate](#lastlogindate) | Narrows the query results based on the users’ last login dates. +| [lastName](#lastname) | Narrows the query results based on the users’ last names. +| [limit](#limit) | Determines the number of users that should be returned. +| [offset](#offset) | Determines how many users should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) +| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [relatedTo](#relatedto) | Narrows the query results to only users that are related to certain other elements. +| [search](#search) | Narrows the query results to only users that match a search query. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the users’ IDs in the `elements_sites` table. +| [status](#status) | Narrows the query results based on the users’ statuses. +| [trashed](#trashed) | Narrows the query results to only users that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the users’ UIDs. +| [username](#username) | Narrows the query results based on the users’ usernames. +| [with](#with) | Causes the query to return matching users eager-loaded with related elements. +| [withGroups](#withgroups) | Causes the query to return matching users eager-loaded with their user groups. + + + + + +#### `admin` + +Narrows the query results to only users that have admin accounts. + + + +::: code +```twig +{# Fetch admins #} +{% set users = craft.users() + .admin() + .all() %} +``` + +```php +// Fetch admins +$users = \craft\elements\User::find() + ->admin() + ->all(); +``` +::: + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only users that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all users that are related to myCategoryA and myCategoryB #} +{% set users = craft.users() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all users that are related to $myCategoryA and $myCategoryB +$users = \craft\elements\User::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching users as arrays of data, rather than [User](craft4:craft\elements\User) objects. + + + + + +::: code +```twig +{# Fetch users as arrays #} +{% set users = craft.users() + .asArray() + .all() %} +``` + +```php +// Fetch users as arrays +$users = \craft\elements\User::find() + ->asArray() + ->all(); +``` +::: + + +#### `assetUploaders` + +Narrows the query results to only users that have uploaded an asset. + + + +::: code +```twig +{# Fetch all users who have uploaded an asset #} +{% set users = craft.users() + .assetUploaders() + .all() %} +``` + +```php +// Fetch all users who have uploaded an asset +$users = \craft\elements\User::find() + ->assetUploaders() + ->all(); +``` +::: + + +#### `authors` + +Narrows the query results to only users that are authors of an entry. + + + +::: code +```twig +{# Fetch authors #} +{% set users = craft.users() + .authors() + .all() %} +``` + +```php +// Fetch authors +$users = \craft\elements\User::find() + ->authors() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `can` + +Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. + +See [User Management](https://craftcms.com/docs/4.x/user-management.html) for a full list of available user permissions defined by Craft. + + + +::: code +```twig +{# Fetch users that can access the control panel #} +{% set users = craft.users() + .can('accessCp') + .all() %} +``` + +```php +// Fetch users that can access the control panel +$users = \craft\elements\User::find() + ->can('accessCp') + ->all(); +``` +::: + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `collect` + + + + + + + + +#### `dateCreated` + +Narrows the query results based on the users’ creation dates. + + + +Possible values include: + +| Value | Fetches users… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch users created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set users = craft.users() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch users created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$users = \craft\elements\User::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the users’ last-updated dates. + + + +Possible values include: + +| Value | Fetches users… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch users updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set users = craft.users() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch users updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$users = \craft\elements\User::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `email` + +Narrows the query results based on the users’ email addresses. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'me@domain.tld'` | with an email of `me@domain.tld`. +| `'not me@domain.tld'` | not with an email of `me@domain.tld`. +| `'*@domain.tld'` | with an email that ends with `@domain.tld`. + + + +::: code +```twig +{# Fetch users with a .co.uk domain on their email address #} +{% set users = craft.users() + .email('*.co.uk') + .all() %} +``` + +```php +// Fetch users with a .co.uk domain on their email address +$users = \craft\elements\User::find() + ->email('*.co.uk') + ->all(); +``` +::: + + +#### `firstName` + +Narrows the query results based on the users’ first names. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'Jane'` | with a first name of `Jane`. +| `'not Jane'` | not with a first name of `Jane`. + + + +::: code +```twig +{# Fetch all the Jane's #} +{% set users = craft.users() + .firstName('Jane') + .all() %} +``` + +```php +// Fetch all the Jane's +$users = \craft\elements\User::find() + ->firstName('Jane') + ->one(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch users in a specific order #} +{% set users = craft.users() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch users in a specific order +$users = \craft\elements\User::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `fullName` + +Narrows the query results based on the users’ full names. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'Jane Doe'` | with a full name of `Jane Doe`. +| `'not Jane Doe'` | not with a full name of `Jane Doe`. + + + +::: code +```twig +{# Fetch all the Jane Doe's #} +{% set users = craft.users() + .fullName('Jane Doe') + .all() %} +``` + +```php +// Fetch all the Jane Doe's +$users = \craft\elements\User::find() + ->fullName('JaneDoe') + ->one(); +``` +::: + + +#### `group` + +Narrows the query results based on the user group the users belong to. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'foo'` | in a group with a handle of `foo`. +| `'not foo'` | not in a group with a handle of `foo`. +| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. +| `['and', 'foo', 'bar']` | in both groups with handles of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. +| a [UserGroup](craft4:craft\models\UserGroup) object | in a group represented by the object. + + + +::: code +```twig +{# Fetch users in the Foo user group #} +{% set users = craft.users() + .group('foo') + .all() %} +``` + +```php +// Fetch users in the Foo user group +$users = \craft\elements\User::find() + ->group('foo') + ->all(); +``` +::: + + +#### `groupId` + +Narrows the query results based on the user group the users belong to, per the groups’ IDs. + +Possible values include: + +| Value | Fetches users… +| - | - +| `1` | in a group with an ID of 1. +| `'not 1'` | not in a group with an ID of 1. +| `[1, 2]` | in a group with an ID of 1 or 2. +| `['and', 1, 2]` | in both groups with IDs of 1 or 2. +| `['not', 1, 2]` | not in a group with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch users in a group with an ID of 1 #} +{% set users = craft.users() + .groupId(1) + .all() %} +``` + +```php +// Fetch users in a group with an ID of 1 +$users = \craft\elements\User::find() + ->groupId(1) + ->all(); +``` +::: + + +#### `hasPhoto` + +Narrows the query results to only users that have (or don’t have) a user photo. + + + +::: code +```twig +{# Fetch users with photos #} +{% set users = craft.users() + .hasPhoto() + .all() %} +``` + +```php +// Fetch users without photos +$users = \craft\elements\User::find() + ->hasPhoto() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the users’ IDs. + + + +Possible values include: + +| Value | Fetches users… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the user by its ID #} +{% set user = craft.users() + .id(1) + .one() %} +``` + +```php +// Fetch the user by its ID +$user = \craft\elements\User::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching users as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch users in reverse #} +{% set users = craft.users() + .inReverse() + .all() %} +``` + +```php +// Fetch users in reverse +$users = \craft\elements\User::find() + ->inReverse() + ->all(); +``` +::: + + +#### `lastLoginDate` + +Narrows the query results based on the users’ last login dates. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'>= 2018-04-01'` | that last logged in on or after 2018-04-01. +| `'< 2018-05-01'` | that last logged in before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that last logged in between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that last logged in at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch users that logged in recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set users = craft.users() + .lastLoginDate(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch users that logged in recently +$aWeekAgo = (new \DateTime('7 days ago'))->format(\DateTime::ATOM); + +$users = \craft\elements\User::find() + ->lastLoginDate(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `lastName` + +Narrows the query results based on the users’ last names. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'Doe'` | with a last name of `Doe`. +| `'not Doe'` | not with a last name of `Doe`. + + + +::: code +```twig +{# Fetch all the Doe's #} +{% set users = craft.users() + .lastName('Doe') + .all() %} +``` + +```php +// Fetch all the Doe's +$users = \craft\elements\User::find() + ->lastName('Doe') + ->one(); +``` +::: + + +#### `limit` + +Determines the number of users that should be returned. + + + +::: code +```twig +{# Fetch up to 10 users #} +{% set users = craft.users() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 users +$users = \craft\elements\User::find() + ->limit(10) + ->all(); +``` +::: + + +#### `offset` + +Determines how many users should be skipped in the results. + + + +::: code +```twig +{# Fetch all users except for the first 3 #} +{% set users = craft.users() + .offset(3) + .all() %} +``` + +```php +// Fetch all users except for the first 3 +$users = \craft\elements\User::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) + + + +::: code +```twig +{# Fetch all users in order of date created #} +{% set users = craft.users() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all users in order of date created +$users = \craft\elements\User::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique users from Site A, or Site B if they don’t exist in Site A #} +{% set users = craft.users() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique users from Site A, or Site B if they don’t exist in Site A +$users = \craft\elements\User::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `relatedTo` + +Narrows the query results to only users that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all users that are related to myCategory #} +{% set users = craft.users() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all users that are related to $myCategory +$users = \craft\elements\User::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only users that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all users that match the search query #} +{% set users = craft.users() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all users that match the search query +$users = \craft\elements\User::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the users’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches users… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the user by its ID in the elements_sites table #} +{% set user = craft.users() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the user by its ID in the elements_sites table +$user = \craft\elements\User::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the users’ statuses. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'inactive'` | with inactive accounts. +| `'active'` | with active accounts. +| `'pending'` | with accounts that are still pending activation. +| `'credentialed'` | with either active or pending accounts. +| `'suspended'` | with suspended accounts. +| `'locked'` | with locked accounts (regardless of whether they’re active or suspended). +| `['active', 'suspended']` | with active or suspended accounts. +| `['not', 'active', 'suspended']` | without active or suspended accounts. + + + +::: code +```twig +{# Fetch active and locked users #} +{% set users = craft.users() + .status(['active', 'locked']) + .all() %} +``` + +```php +// Fetch active and locked users +$users = \craft\elements\User::find() + ->status(['active', 'locked']) + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only users that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed users #} +{% set users = craft.users() + .trashed() + .all() %} +``` + +```php +// Fetch trashed users +$users = \craft\elements\User::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the users’ UIDs. + + + + + +::: code +```twig +{# Fetch the user by its UID #} +{% set user = craft.users() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the user by its UID +$user = \craft\elements\User::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `username` + +Narrows the query results based on the users’ usernames. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'foo'` | with a username of `foo`. +| `'not foo'` | not with a username of `foo`. + + + +::: code +```twig +{# Get the requested username #} +{% set requestedUsername = craft.app.request.getSegment(2) %} + +{# Fetch that user #} +{% set user = craft.users() + .username(requestedUsername|literal) + .one() %} +``` + +```php +// Get the requested username +$requestedUsername = \Craft::$app->request->getSegment(2); + +// Fetch that user +$user = \craft\elements\User::find() + ->username(\craft\helpers\Db::escapeParam($requestedUsername)) + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching users eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch users eager-loaded with the "Related" field’s relations #} +{% set users = craft.users() + .with(['related']) + .all() %} +``` + +```php +// Fetch users eager-loaded with the "Related" field’s relations +$users = \craft\elements\User::find() + ->with(['related']) + ->all(); +``` +::: + + +#### `withGroups` + +Causes the query to return matching users eager-loaded with their user groups. + +Possible values include: + +| Value | Fetches users… +| - | - +| `'>= 2018-04-01'` | that last logged-in on or after 2018-04-01. +| `'< 2018-05-01'` | that last logged-in before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that last logged-in between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# fetch users with their user groups #} +{% set users = craft.users() + .withGroups() + .all() %} +``` + +```php +// fetch users with their user groups +$users = \craft\elements\User::find() + ->withGroups() + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/commerce/2.x/order-queries.md b/docs/.artifacts/commerce/2.x/order-queries.md new file mode 100644 index 000000000..f6ac85416 --- /dev/null +++ b/docs/.artifacts/commerce/2.x/order-queries.md @@ -0,0 +1,1039 @@ + + + + +- [anyStatus](#anystatus) +- [asArray](#asarray) +- [customer](#customer) +- [customerId](#customerid) +- [dateCreated](#datecreated) +- [dateOrdered](#dateordered) +- [datePaid](#datepaid) +- [dateUpdated](#dateupdated) +- [email](#email) +- [expiryDate](#expirydate) +- [fixedOrder](#fixedorder) +- [gateway](#gateway) +- [gatewayId](#gatewayid) +- [hasPurchasables](#haspurchasables) +- [hasTransactions](#hastransactions) +- [id](#id) +- [ignorePlaceholders](#ignoreplaceholders) +- [inReverse](#inreverse) +- [isCompleted](#iscompleted) +- [isPaid](#ispaid) +- [isUnpaid](#isunpaid) +- [limit](#limit) +- [number](#number) +- [offset](#offset) +- [orderBy](#orderby) +- [orderStatus](#orderstatus) +- [orderStatusId](#orderstatusid) +- [preferSites](#prefersites) +- [reference](#reference) +- [relatedTo](#relatedto) +- [search](#search) +- [shortNumber](#shortnumber) +- [trashed](#trashed) +- [uid](#uid) +- [user](#user) +- [with](#with) + +### `anyStatus` + +Clears out the [status()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. + + + + + +::: code +```twig +{# Fetch all orders, regardless of status #} +{% set orders = craft.orders() + .anyStatus() + .all() %} +``` + +```php +// Fetch all orders, regardless of status +$orders = \craft\commerce\elements\Order::find() + ->anyStatus() + ->all(); +``` +::: + + +### `asArray` + +Causes the query to return matching orders as arrays of data, rather than [Order](commerce2:craft\commerce\elements\Order) objects. + + + + + +::: code +```twig +{# Fetch orders as arrays #} +{% set orders = craft.orders() + .asArray() + .all() %} +``` + +```php +// Fetch orders as arrays +$orders = \craft\commerce\elements\Order::find() + ->asArray() + ->all(); +``` +::: + + +### `customer` + +Narrows the query results based on the customer. + +Possible values include: + +| Value | Fetches orders… +| - | - +| a [Customer](commerce2:craft\commerce\models\Customer) object | with a customer represented by the object. + + + +::: code +```twig +{# Fetch the current user's orders #} +{% set orders = craft.orders() + .customer(currentUser.customerFieldHandle) + .all() %} +``` + +```php +// Fetch the current user's orders +$user = Craft::$app->user->getIdentity(); +$orders = \craft\commerce\elements\Order::find() + ->customer($user->customerFieldHandle) + ->all(); +``` +::: + + +### `customerId` + +Narrows the query results based on the customer, per their ID. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a customer with an ID of 1. +| `'not 1'` | not with a customer with an ID of 1. +| `[1, 2]` | with a customer with an ID of 1 or 2. +| `['not', 1, 2]` | not with a customer with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the current user's orders #} +{% set orders = craft.orders() + .customerId(currentUser.customerFieldHandle.id) + .all() %} +``` + +```php +// Fetch the current user's orders +$user = Craft::$app->user->getIdentity(); +$orders = \craft\commerce\elements\Order::find() + ->customerId($user->customerFieldHandle->id) + ->all(); +``` +::: + + +### `dateCreated` + +Narrows the query results based on the orders’ creation dates. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set orders = craft.orders() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch orders created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +### `dateOrdered` + +Narrows the query results based on the orders’ completion dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were completed on or after 2018-04-01. +| `'< 2018-05-01'` | that were completed before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders that were completed recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set orders = craft.orders() + .dateOrdered(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch orders that were completed recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateOrdered(">= {$aWeekAgo}") + ->all(); +``` +::: + + +### `datePaid` + +Narrows the query results based on the orders’ paid dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were paid on or after 2018-04-01. +| `'< 2018-05-01'` | that were paid before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders that were paid for recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set orders = craft.orders() + .datePaid(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch orders that were paid for recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->datePaid(">= {$aWeekAgo}") + ->all(); +``` +::: + + +### `dateUpdated` + +Narrows the query results based on the orders’ last-updated dates. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set orders = craft.orders() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch orders updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +### `email` + +Narrows the query results based on the customers’ email addresses. + +Possible values include: + +| Value | Fetches orders with customers… +| - | - +| `'foo@bar.baz'` | with an email of `foo@bar.baz`. +| `'not foo@bar.baz'` | not with an email of `foo@bar.baz`. +| `'*@bar.baz'` | with an email that ends with `@bar.baz`. + + + +::: code +```twig +{# Fetch orders from customers with a .co.uk domain on their email address #} +{% set orders = craft.orders() + .email('*.co.uk') + .all() %} +``` + +```php +// Fetch orders from customers with a .co.uk domain on their email address +$orders = \craft\commerce\elements\Order::find() + ->email('*.co.uk') + ->all(); +``` +::: + + +### `expiryDate` + +Narrows the query results based on the orders’ expiry dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. +| `'< 2020-05-01'` | that will expire before 2020-05-01 +| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. + + + +::: code +```twig +{# Fetch orders expiring this month #} +{% set nextMonth = date('first day of next month')|atom %} + +{% set orders = craft.orders() + .expiryDate("< #{nextMonth}") + .all() %} +``` + +```php +// Fetch orders expiring this month +$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->expiryDate("< {$nextMonth}") + ->all(); +``` +::: + + +### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + + + +::: code +```twig +{# Fetch orders in a specific order #} +{% set orders = craft.orders() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch orders in a specific order +$orders = \craft\commerce\elements\Order::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +### `gateway` + +Narrows the query results based on the gateway. + +Possible values include: + +| Value | Fetches orders… +| - | - +| a [Gateway](commerce2:craft\commerce\base\Gateway) object | with a gateway represented by the object. + + + + +### `gatewayId` + +Narrows the query results based on the gateway, per its ID. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a gateway with an ID of 1. +| `'not 1'` | not with a gateway with an ID of 1. +| `[1, 2]` | with a gateway with an ID of 1 or 2. +| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. + + + + +### `hasPurchasables` + +Narrows the query results to only orders that have certain purchasables. + +Possible values include: + +| Value | Fetches orders… +| - | - +| a [PurchasableInterface](commerce2:craft\commerce\base\PurchasableInterface) object | with a purchasable represented by the object. +| an array of [PurchasableInterface](commerce2:craft\commerce\base\PurchasableInterface) objects | with all the purchasables represented by the objects. + + + + +### `hasTransactions` + +Narrows the query results to only carts that have at least one transaction. + + + +::: code +```twig +{# Fetch carts that have attempted payments #} +{% set orders = craft.orders() + .hasTransactions() + .all() %} +``` + +```php +// Fetch carts that have attempted payments +$orders = \craft\commerce\elements\Order::find() + ->hasTransactions() + ->all(); +``` +::: + + +### `id` + +Narrows the query results based on the orders’ IDs. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the order by its ID #} +{% set order = craft.orders() + .id(1) + .one() %} +``` + +```php +// Fetch the order by its ID +$order = \craft\commerce\elements\Order::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +### `ignorePlaceholders` + +Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch orders in reverse #} +{% set orders = craft.orders() + .inReverse() + .all() %} +``` + +```php +// Fetch orders in reverse +$orders = \craft\commerce\elements\Order::find() + ->inReverse() + ->all(); +``` +::: + + +### `isCompleted` + +Narrows the query results to only orders that are completed. + + + +::: code +```twig +{# Fetch completed orders #} +{% set orders = craft.orders() + .isCompleted() + .all() %} +``` + +```php +// Fetch completed orders +$orders = \craft\commerce\elements\Order::find() + ->isCompleted() + ->all(); +``` +::: + + +### `isPaid` + +Narrows the query results to only orders that are paid. + + + +::: code +```twig +{# Fetch paid orders #} +{% set orders = craft.orders() + .isPaid() + .all() %} +``` + +```php +// Fetch paid orders +$orders = \craft\commerce\elements\Order::find() + ->isPaid() + ->all(); +``` +::: + + +### `isUnpaid` + +Narrows the query results to only orders that are not paid. + + + +::: code +```twig +{# Fetch unpaid orders #} +{% set orders = craft.orders() + .isUnpaid() + .all() %} +``` + +```php +// Fetch unpaid orders +$orders = \craft\commerce\elements\Order::find() + ->isUnpaid() + ->all(); +``` +::: + + +### `limit` + +Determines the number of orders that should be returned. + + + +::: code +```twig +{# Fetch up to 10 orders #} +{% set orders = craft.orders() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 orders +$orders = \craft\commerce\elements\Order::find() + ->limit(10) + ->all(); +``` +::: + + +### `number` + +Narrows the query results based on the order number. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'` | with a matching order number + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderNumber = craft.app.request.getQueryParam('number') %} +{% set order = craft.orders() + .number(orderNumber) + .one() %} +``` + +```php +// Fetch the requested order +$orderNumber = Craft::$app->request->getQueryParam('number'); +$order = \craft\commerce\elements\Order::find() + ->number($orderNumber) + ->one(); +``` +::: + + +### `offset` + +Determines how many orders should be skipped in the results. + + + +::: code +```twig +{# Fetch all orders except for the first 3 #} +{% set orders = craft.orders() + .offset(3) + .all() %} +``` + +```php +// Fetch all orders except for the first 3 +$orders = \craft\commerce\elements\Order::find() + ->offset(3) + ->all(); +``` +::: + + +### `orderBy` + +Determines the order that the orders should be returned in. + + + +::: code +```twig +{# Fetch all orders in order of date created #} +{% set orders = craft.orders() + .orderBy('dateCreated asc') + .all() %} +``` + +```php +// Fetch all orders in order of date created +$orders = \craft\commerce\elements\Order::find() + ->orderBy('dateCreated asc') + ->all(); +``` +::: + + +### `orderStatus` + +Narrows the query results based on the order statuses. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'foo'` | with an order status with a handle of `foo`. +| `'not foo'` | not with an order status with a handle of `foo`. +| `['foo', 'bar']` | with an order status with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not with an order status with a handle of `foo` or `bar`. +| a [OrderStatus](commerce2:craft\commerce\models\OrderStatus) object | with an order status represented by the object. + + + +::: code +```twig +{# Fetch shipped orders #} +{% set orders = craft.orders() + .orderStatus('shipped') + .all() %} +``` + +```php +// Fetch shipped orders +$orders = \craft\commerce\elements\Order::find() + ->orderStatus('shipped') + ->all(); +``` +::: + + +### `orderStatusId` + +Narrows the query results based on the order statuses, per their IDs. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an order status with an ID of 1. +| `'not 1'` | not with an order status with an ID of 1. +| `[1, 2]` | with an order status with an ID of 1 or 2. +| `['not', 1, 2]` | not with an order status with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch orders with an order status with an ID of 1 #} +{% set orders = craft.orders() + .authorGroupId(1) + .all() %} +``` + +```php +// Fetch orders with an order status with an ID of 1 +$orders = \craft\commerce\elements\Order::find() + ->authorGroupId(1) + ->all(); +``` +::: + + +### `preferSites` + +If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned +for Site B. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique orders from Site A, or Site B if they don’t exist in Site A #} +{% set orders = craft.orders() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique orders from Site A, or Site B if they don’t exist in Site A +$orders = \craft\commerce\elements\Order::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +### `reference` + +Narrows the query results based on the order reference. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'xxxx'` | with a matching order reference + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderReference = craft.app.request.getQueryParam('ref') %} +{% set order = craft.orders() + .reference(orderReference) + .one() %} +``` + +```php +// Fetch the requested order +$orderReference = Craft::$app->request->getQueryParam('ref'); +$order = \craft\commerce\elements\Order::find() + ->reference($orderReference) + ->one(); +``` +::: + + +### `relatedTo` + +Narrows the query results to only orders that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all orders that are related to myCategory #} +{% set orders = craft.orders() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all orders that are related to $myCategory +$orders = \craft\commerce\elements\Order::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +### `search` + +Narrows the query results to only orders that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all orders that match the search query #} +{% set orders = craft.orders() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all orders that match the search query +$orders = \craft\commerce\elements\Order::find() + ->search($searchQuery) + ->all(); +``` +::: + + +### `shortNumber` + +Narrows the query results based on the order short number. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'xxxxxxx'` | with a matching order number + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderNumber = craft.app.request.getQueryParam('shortNumber') %} +{% set order = craft.orders() + .shortNumber(orderNumber) + .one() %} +``` + +```php +// Fetch the requested order +$orderNumber = Craft::$app->request->getQueryParam('shortNumber'); +$order = \craft\commerce\elements\Order::find() + ->shortNumber($orderNumber) + ->one(); +``` +::: + + +### `trashed` + +Narrows the query results to only orders that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed orders #} +{% set orders = craft.orders() + .trashed() + .all() %} +``` + +```php +// Fetch trashed orders +$orders = \craft\commerce\elements\Order::find() + ->trashed() + ->all(); +``` +::: + + +### `uid` + +Narrows the query results based on the orders’ UIDs. + + + + + +::: code +```twig +{# Fetch the order by its UID #} +{% set order = craft.orders() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the order by its UID +$order = \craft\commerce\elements\Order::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +### `user` + +Narrows the query results based on the customer’s user account. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a customer with a user account ID of 1. +| a [User](https://docs.craftcms.com/api/v3/craft-elements-user.html) object | with a customer with a user account represented by the object. + + + +::: code +```twig +{# Fetch the current user's orders #} +{% set orders = craft.orders() + .user(currentUser) + .all() %} +``` + +```php +// Fetch the current user's orders +$user = Craft::$app->user->getIdentity(); +$orders = \craft\commerce\elements\Order::find() + ->user($user) + ->all(); +``` +::: + + +### `with` + +Causes the query to return matching orders eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch orders eager-loaded with the "Related" field’s relations #} +{% set orders = craft.orders() + .with(['related']) + .all() %} +``` + +```php +// Fetch orders eager-loaded with the "Related" field’s relations +$orders = \craft\commerce\elements\Order::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/commerce/2.x/product-queries.md b/docs/.artifacts/commerce/2.x/product-queries.md new file mode 100644 index 000000000..f29320e6e --- /dev/null +++ b/docs/.artifacts/commerce/2.x/product-queries.md @@ -0,0 +1,1008 @@ + + + + +- [after](#after) +- [anyStatus](#anystatus) +- [asArray](#asarray) +- [availableForPurchase](#availableforpurchase) +- [before](#before) +- [dateCreated](#datecreated) +- [dateUpdated](#dateupdated) +- [expiryDate](#expirydate) +- [fixedOrder](#fixedorder) +- [hasVariant](#hasvariant) +- [id](#id) +- [ignorePlaceholders](#ignoreplaceholders) +- [inReverse](#inreverse) +- [limit](#limit) +- [offset](#offset) +- [orderBy](#orderby) +- [postDate](#postdate) +- [preferSites](#prefersites) +- [relatedTo](#relatedto) +- [search](#search) +- [site](#site) +- [siteId](#siteid) +- [slug](#slug) +- [status](#status) +- [title](#title) +- [trashed](#trashed) +- [type](#type) +- [typeId](#typeid) +- [uid](#uid) +- [unique](#unique) +- [uri](#uri) +- [with](#with) + +### `after` + +Narrows the query results to only products that were posted on or after a certain date. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'2018-04-01'` | that were posted after 2018-04-01. +| a [DateTime](http://php.net/class.datetime) object | that were posted after the date represented by the object. + + + +::: code +```twig +{# Fetch products posted this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set products = craft.products() + .after(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch products posted this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$products = \craft\commerce\elements\Product::find() + ->after($firstDayOfMonth) + ->all(); +``` +::: + + +### `anyStatus` + +Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. + + + + + +::: code +```twig +{# Fetch all products, regardless of status #} +{% set products = craft.products() + .anyStatus() + .all() %} +``` + +```php +// Fetch all products, regardless of status +$products = \craft\commerce\elements\Product::find() + ->anyStatus() + ->all(); +``` +::: + + +### `asArray` + +Causes the query to return matching products as arrays of data, rather than [Product](commerce2:craft\commerce\elements\Product) objects. + + + + + +::: code +```twig +{# Fetch products as arrays #} +{% set products = craft.products() + .asArray() + .all() %} +``` + +```php +// Fetch products as arrays +$products = \craft\commerce\elements\Product::find() + ->asArray() + ->all(); +``` +::: + + +### `availableForPurchase` + +Narrows the query results to only products that are available for purchase. + + + +::: code +```twig +{# Fetch products that are available for purchase #} +{% set products = craft.products() + .availableForPurchase() + .all() %} +``` + +```php +// Fetch products that are available for purchase +$products = \craft\commerce\elements\Product::find() + ->availableForPurchase() + ->all(); +``` +::: + + +### `before` + +Narrows the query results to only products that were posted before a certain date. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'2018-04-01'` | that were posted before 2018-04-01. +| a [DateTime](http://php.net/class.datetime) object | that were posted before the date represented by the object. + + + +::: code +```twig +{# Fetch products posted before this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set products = craft.products() + .before(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch products posted before this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$products = \craft\commerce\elements\Product::find() + ->before($firstDayOfMonth) + ->all(); +``` +::: + + +### `dateCreated` + +Narrows the query results based on the products’ creation dates. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch products created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set products = craft.products() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch products created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +### `dateUpdated` + +Narrows the query results based on the products’ last-updated dates. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch products updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set products = craft.products() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch products updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +### `expiryDate` + +Narrows the query results based on the products’ expiry dates. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. +| `'< 2020-05-01'` | that will expire before 2020-05-01 +| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. + + + +::: code +```twig +{# Fetch products expiring this month #} +{% set nextMonth = date('first day of next month')|atom %} + +{% set products = craft.products() + .expiryDate("< #{nextMonth}") + .all() %} +``` + +```php +// Fetch products expiring this month +$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->expiryDate("< {$nextMonth}") + ->all(); +``` +::: + + +### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + + + +::: code +```twig +{# Fetch products in a specific order #} +{% set products = craft.products() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch products in a specific order +$products = \craft\commerce\elements\Product::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +### `hasVariant` + +Narrows the query results to only products that have certain variants. + +Possible values include: + +| Value | Fetches products… +| - | - +| a [VariantQuery](commerce2:craft\commerce\elements\db\VariantQuery) object | with variants that match the query. + + + + +### `id` + +Narrows the query results based on the products’ IDs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the product by its ID #} +{% set product = craft.products() + .id(1) + .one() %} +``` + +```php +// Fetch the product by its ID +$product = \craft\commerce\elements\Product::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +### `ignorePlaceholders` + +Causes the query to return matching products as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch products in reverse #} +{% set products = craft.products() + .inReverse() + .all() %} +``` + +```php +// Fetch products in reverse +$products = \craft\commerce\elements\Product::find() + ->inReverse() + ->all(); +``` +::: + + +### `limit` + +Determines the number of products that should be returned. + + + +::: code +```twig +{# Fetch up to 10 products #} +{% set products = craft.products() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 products +$products = \craft\commerce\elements\Product::find() + ->limit(10) + ->all(); +``` +::: + + +### `offset` + +Determines how many products should be skipped in the results. + + + +::: code +```twig +{# Fetch all products except for the first 3 #} +{% set products = craft.products() + .offset(3) + .all() %} +``` + +```php +// Fetch all products except for the first 3 +$products = \craft\commerce\elements\Product::find() + ->offset(3) + ->all(); +``` +::: + + +### `orderBy` + +Determines the order that the products should be returned in. + + + +::: code +```twig +{# Fetch all products in order of date created #} +{% set products = craft.products() + .orderBy('dateCreated asc') + .all() %} +``` + +```php +// Fetch all products in order of date created +$products = \craft\commerce\elements\Product::find() + ->orderBy('dateCreated asc') + ->all(); +``` +::: + + +### `postDate` + +Narrows the query results based on the products’ post dates. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. +| `'< 2018-05-01'` | that were posted before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch products posted last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set products = craft.products() + .postDate(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch products posted last month +$start = new \DateTime('first day of next month')->format(\DateTime::ATOM); +$end = new \DateTime('first day of this month')->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->postDate(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned +for Site B. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique products from Site A, or Site B if they don’t exist in Site A #} +{% set products = craft.products() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique products from Site A, or Site B if they don’t exist in Site A +$products = \craft\commerce\elements\Product::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +### `relatedTo` + +Narrows the query results to only products that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all products that are related to myCategory #} +{% set products = craft.products() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all products that are related to $myCategory +$products = \craft\commerce\elements\Product::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +### `search` + +Narrows the query results to only products that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all products that match the search query #} +{% set products = craft.products() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all products that match the search query +$products = \craft\commerce\elements\Product::find() + ->search($searchQuery) + ->all(); +``` +::: + + +### `site` + +Determines which site(s) the products should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a `\craft\commerce\elements\db\Site` object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch products from the Foo site #} +{% set products = craft.products() + .site('foo') + .all() %} +``` + +```php +// Fetch products from the Foo site +$products = \craft\commerce\elements\Product::find() + ->site('foo') + ->all(); +``` +::: + + +### `siteId` + +Determines which site(s) the products should be queried in, per the site’s ID. + + + +The current site will be used by default. + + + +::: code +```twig +{# Fetch products from the site with an ID of 1 #} +{% set products = craft.products() + .siteId(1) + .all() %} +``` + +```php +// Fetch products from the site with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->siteId(1) + ->all(); +``` +::: + + +### `slug` + +Narrows the query results based on the products’ slugs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | with a slug of `foo`. +| `'foo*'` | with a slug that begins with `foo`. +| `'*foo'` | with a slug that ends with `foo`. +| `'*foo*'` | with a slug that contains `foo`. +| `'not *foo*'` | with a slug that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested product slug from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the product with that slug #} +{% set product = craft.products() + .slug(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested product slug from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the product with that slug +$product = \craft\commerce\elements\Product::find() + ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +### `status` + +Narrows the query results based on the products’ statuses. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'live'` _(default)_ | that are live. +| `'pending'` | that are pending (enabled with a Post Date in the future). +| `'expired'` | that are expired (enabled with an Expiry Date in the past). +| `'disabled'` | that are disabled. +| `['live', 'pending']` | that are live or pending. + + + +::: code +```twig +{# Fetch disabled products #} +{% set products = craft.products() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled products +$products = \craft\commerce\elements\Product::find() + ->status('disabled') + ->all(); +``` +::: + + +### `title` + +Narrows the query results based on the products’ titles. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch products with a title that contains "Foo" #} +{% set products = craft.products() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch products with a title that contains "Foo" +$products = \craft\commerce\elements\Product::find() + ->title('*Foo*') + ->all(); +``` +::: + + +### `trashed` + +Narrows the query results to only products that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed products #} +{% set products = craft.products() + .trashed() + .all() %} +``` + +```php +// Fetch trashed products +$products = \craft\commerce\elements\Product::find() + ->trashed() + ->all(); +``` +::: + + +### `type` + +Narrows the query results based on the products’ types. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | of a type with a handle of `foo`. +| `'not foo'` | not of a type with a handle of `foo`. +| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. +| an [ProductType](commerce2:craft\commerce\models\ProductType) object | of a type represented by the object. + + + +::: code +```twig +{# Fetch products with a Foo product type #} +{% set products = craft.products() + .type('foo') + .all() %} +``` + +```php +// Fetch products with a Foo product type +$products = \craft\commerce\elements\Product::find() + ->type('foo') + ->all(); +``` +::: + + +### `typeId` + +Narrows the query results based on the products’ types, per the types’ IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with an ID of 1. +| `'not 1'` | not of a type with an ID of 1. +| `[1, 2]` | of a type with an ID of 1 or 2. +| `['not', 1, 2]` | not of a type with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch products of the product type with an ID of 1 #} +{% set products = craft.products() + .typeId(1) + .all() %} +``` + +```php +// Fetch products of the product type with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->typeId(1) + ->all(); +``` +::: + + +### `uid` + +Narrows the query results based on the products’ UIDs. + + + + + +::: code +```twig +{# Fetch the product by its UID #} +{% set product = craft.products() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the product by its UID +$product = \craft\commerce\elements\Product::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique products across all sites #} +{% set products = craft.products() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique products across all sites +$products = \craft\commerce\elements\Product::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +### `uri` + +Narrows the query results based on the products’ URIs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the product with that URI #} +{% set product = craft.products() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the product with that URI +$product = \craft\commerce\elements\Product::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +### `with` + +Causes the query to return matching products eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch products eager-loaded with the "Related" field’s relations #} +{% set products = craft.products() + .with(['related']) + .all() %} +``` + +```php +// Fetch products eager-loaded with the "Related" field’s relations +$products = \craft\commerce\elements\Product::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/commerce/2.x/subscription-queries.md b/docs/.artifacts/commerce/2.x/subscription-queries.md new file mode 100644 index 000000000..8c2f89656 --- /dev/null +++ b/docs/.artifacts/commerce/2.x/subscription-queries.md @@ -0,0 +1,959 @@ + + + + +- [anyStatus](#anystatus) +- [asArray](#asarray) +- [dateCanceled](#datecanceled) +- [dateCreated](#datecreated) +- [dateExpired](#dateexpired) +- [dateSuspended](#datesuspended) +- [dateUpdated](#dateupdated) +- [fixedOrder](#fixedorder) +- [gatewayId](#gatewayid) +- [hasStarted](#hasstarted) +- [id](#id) +- [ignorePlaceholders](#ignoreplaceholders) +- [inReverse](#inreverse) +- [isCanceled](#iscanceled) +- [isExpired](#isexpired) +- [isSuspended](#issuspended) +- [limit](#limit) +- [nextPaymentDate](#nextpaymentdate) +- [offset](#offset) +- [onTrial](#ontrial) +- [orderBy](#orderby) +- [orderId](#orderid) +- [plan](#plan) +- [planId](#planid) +- [preferSites](#prefersites) +- [reference](#reference) +- [relatedTo](#relatedto) +- [search](#search) +- [status](#status) +- [trashed](#trashed) +- [trialDays](#trialdays) +- [uid](#uid) +- [user](#user) +- [userId](#userid) +- [with](#with) + +### `anyStatus` + +Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. + + + + + +::: code +```twig +{# Fetch all subscriptions, regardless of status #} +{% set subscriptions = craft.subscriptions() + .anyStatus() + .all() %} +``` + +```php +// Fetch all subscriptions, regardless of status +$subscriptions = \craft\commerce\elements\Subscription::find() + ->anyStatus() + ->all(); +``` +::: + + +### `asArray` + +Causes the query to return matching subscriptions as arrays of data, rather than `\craft\commerce\elements\Subscription` objects. + + + + + +::: code +```twig +{# Fetch subscriptions as arrays #} +{% set subscriptions = craft.subscriptions() + .asArray() + .all() %} +``` + +```php +// Fetch subscriptions as arrays +$subscriptions = \craft\commerce\elements\Subscription::find() + ->asArray() + ->all(); +``` +::: + + +### `dateCanceled` + +Narrows the query results based on the subscriptions’ cancellation date. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that were canceled on or after 2018-04-01. +| `'< 2018-05-01'` | that were canceled before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were canceled between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch subscriptions that were canceled recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateCanceled(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch subscriptions that were canceled recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateCanceled(">= {$aWeekAgo}") + ->all(); +``` +::: + + +### `dateCreated` + +Narrows the query results based on the subscriptions’ creation dates. + + + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch subscriptions created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch subscriptions created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +### `dateExpired` + +Narrows the query results based on the subscriptions’ expiration date. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that expired on or after 2018-04-01. +| `'< 2018-05-01'` | that expired before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that expired between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch subscriptions that expired recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateExpired(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch subscriptions that expired recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateExpired(">= {$aWeekAgo}") + ->all(); +``` +::: + + +### `dateSuspended` + +Narrows the query results based on the subscriptions’ suspension date. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that were suspended on or after 2018-04-01. +| `'< 2018-05-01'` | that were suspended before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were suspended between 2018-04-01 and 2018-05-01. + + +::: code +```twig +{# Fetch subscriptions that were suspended recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateSuspended(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch subscriptions that were suspended recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateSuspended(">= {$aWeekAgo}") + ->all(); +``` +::: + + +### `dateUpdated` + +Narrows the query results based on the subscriptions’ last-updated dates. + + + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch subscriptions updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch subscriptions updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + + + +::: code +```twig +{# Fetch subscriptions in a specific order #} +{% set subscriptions = craft.subscriptions() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch subscriptions in a specific order +$subscriptions = \craft\commerce\elements\Subscription::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +### `gatewayId` + +Narrows the query results based on the gateway, per its ID. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | with a gateway with an ID of 1. +| `'not 1'` | not with a gateway with an ID of 1. +| `[1, 2]` | with a gateway with an ID of 1 or 2. +| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. + + + + +### `hasStarted` + +Narrows the query results to only subscriptions that have started. + + + +::: code +```twig +{# Fetch started subscriptions #} +{% set subscriptions = craft.subscriptions() + .hasStarted() + .all() %} +``` + +```php +// Fetch started subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->hasStarted() + ->all(); +``` +::: + + +### `id` + +Narrows the query results based on the subscriptions’ IDs. + + + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the subscription by its ID #} +{% set subscription = craft.subscriptions() + .id(1) + .one() %} +``` + +```php +// Fetch the subscription by its ID +$subscription = \craft\commerce\elements\Subscription::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +### `ignorePlaceholders` + +Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch subscriptions in reverse #} +{% set subscriptions = craft.subscriptions() + .inReverse() + .all() %} +``` + +```php +// Fetch subscriptions in reverse +$subscriptions = \craft\commerce\elements\Subscription::find() + ->inReverse() + ->all(); +``` +::: + + +### `isCanceled` + +Narrows the query results to only subscriptions that are canceled. + + + +::: code +```twig +{# Fetch canceled subscriptions #} +{% set subscriptions = craft.subscriptions() + .isCanceled() + .all() %} +``` + +```php +// Fetch canceled subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->isCanceled() + ->all(); +``` +::: + + +### `isExpired` + +Narrows the query results to only subscriptions that have expired. + + + +::: code +```twig +{# Fetch expired subscriptions #} +{% set subscriptions = craft.subscriptions() + .isExpired() + .all() %} +``` + +```php +// Fetch expired subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->isExpired() + ->all(); +``` +::: + + +### `isSuspended` + +Narrows the query results to only subscriptions that are suspended. + + + +::: code +```twig +{# Fetch suspended subscriptions #} +{% set subscriptions = craft.subscriptions() + .isSuspended() + .all() %} +``` + +```php +// Fetch suspended subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->isSuspended() + ->all(); +``` +::: + + +### `limit` + +Determines the number of subscriptions that should be returned. + + + +::: code +```twig +{# Fetch up to 10 subscriptions #} +{% set subscriptions = craft.subscriptions() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->limit(10) + ->all(); +``` +::: + + +### `nextPaymentDate` + +Narrows the query results based on the subscriptions’ next payment dates. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | with a next payment on or after 2018-04-01. +| `'< 2018-05-01'` | with a next payment before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | with a next payment between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch subscriptions with a payment due soon #} +{% set aWeekFromNow = date('+7 days')|atom %} + +{% set subscriptions = craft.subscriptions() + .nextPaymentDate("< #{aWeekFromNow}") + .all() %} +``` + +```php +// Fetch subscriptions with a payment due soon +$aWeekFromNow = new \DateTime('+7 days')->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->nextPaymentDate("< {$aWeekFromNow}") + ->all(); +``` +::: + + +### `offset` + +Determines how many subscriptions should be skipped in the results. + + + +::: code +```twig +{# Fetch all subscriptions except for the first 3 #} +{% set subscriptions = craft.subscriptions() + .offset(3) + .all() %} +``` + +```php +// Fetch all subscriptions except for the first 3 +$subscriptions = \craft\commerce\elements\Subscription::find() + ->offset(3) + ->all(); +``` +::: + + +### `onTrial` + +Narrows the query results to only subscriptions that are on trial. + + + +::: code +```twig +{# Fetch trialed subscriptions #} +{% set subscriptions = craft.subscriptions() + .onTrial() + .all() %} +``` + +```php +// Fetch trialed subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->isPaid() + ->all(); +``` +::: + + +### `orderBy` + +Determines the order that the subscriptions should be returned in. + + + +::: code +```twig +{# Fetch all subscriptions in order of date created #} +{% set subscriptions = craft.subscriptions() + .orderBy('dateCreated asc') + .all() %} +``` + +```php +// Fetch all subscriptions in order of date created +$subscriptions = \craft\commerce\elements\Subscription::find() + ->orderBy('dateCreated asc') + ->all(); +``` +::: + + +### `orderId` + +Narrows the query results based on the order, per its ID. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | with an order with an ID of 1. +| `'not 1'` | not with an order with an ID of 1. +| `[1, 2]` | with an order with an ID of 1 or 2. +| `['not', 1, 2]` | not with an order with an ID of 1 or 2. + + + + +### `plan` + +Narrows the query results based on the subscription plan. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'foo'` | for a plan with a handle of `foo`. +| `['foo', 'bar']` | for plans with a handle of `foo` or `bar`. +| a [Plan](commerce2:craft\commerce\base\Plan) object | for a plan represented by the object. + + + +::: code +```twig +{# Fetch Supporter plan subscriptions #} +{% set subscriptions = craft.subscriptions() + .plan('supporter') + .all() %} +``` + +```php +// Fetch Supporter plan subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->plan('supporter') + ->all(); +``` +::: + + +### `planId` + +Narrows the query results based on the subscription plans’ IDs. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | for a plan with an ID of 1. +| `[1, 2]` | for plans with an ID of 1 or 2. +| `['not', 1, 2]` | for plans not with an ID of 1 or 2. + + + + +### `preferSites` + +If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned +for Site B. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A #} +{% set subscriptions = craft.subscriptions() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A +$subscriptions = \craft\commerce\elements\Subscription::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +### `reference` + +Narrows the query results based on the reference. + + + + + + +### `relatedTo` + +Narrows the query results to only subscriptions that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all subscriptions that are related to myCategory #} +{% set subscriptions = craft.subscriptions() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all subscriptions that are related to $myCategory +$subscriptions = \craft\commerce\elements\Subscription::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +### `search` + +Narrows the query results to only subscriptions that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all subscriptions that match the search query #} +{% set subscriptions = craft.subscriptions() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all subscriptions that match the search query +$subscriptions = \craft\commerce\elements\Subscription::find() + ->search($searchQuery) + ->all(); +``` +::: + + +### `status` + +Narrows the query results based on the subscriptions’ statuses. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'active'` _(default)_ | that are active. +| `'expired'` | that have expired. + + + +::: code +```twig +{# Fetch expired subscriptions #} +{% set subscriptions = craft.subscriptions() + .status('expired') + .all() %} +``` + +```php +// Fetch expired subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->status('expired') + ->all(); +``` +::: + + +### `trashed` + +Narrows the query results to only subscriptions that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed subscriptions #} +{% set subscriptions = craft.subscriptions() + .trashed() + .all() %} +``` + +```php +// Fetch trashed subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->trashed() + ->all(); +``` +::: + + +### `trialDays` + +Narrows the query results based on the number of trial days. + + + + + + +### `uid` + +Narrows the query results based on the subscriptions’ UIDs. + + + + + +::: code +```twig +{# Fetch the subscription by its UID #} +{% set subscription = craft.subscriptions() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the subscription by its UID +$subscription = \craft\commerce\elements\Subscription::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +### `user` + +Narrows the query results based on the subscriptions’ user accounts. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'foo'` | for a user account with a username of `foo` +| `['foo', 'bar']` | for user accounts with a username of `foo` or `bar`. +| a [User](https://docs.craftcms.com/api/v3/craft-elements-user.html) object | for a user account represented by the object. + + + +::: code +```twig +{# Fetch the current user's subscriptions #} +{% set subscriptions = craft.subscriptions() + .user(currentUser) + .all() %} +``` + +```php +// Fetch the current user's subscriptions +$user = Craft::$app->user->getIdentity(); +$subscriptions = \craft\commerce\elements\Subscription::find() + ->user($user) + ->all(); +``` +::: + + +### `userId` + +Narrows the query results based on the subscriptions’ user accounts’ IDs. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | for a user account with an ID of 1. +| `[1, 2]` | for user accounts with an ID of 1 or 2. +| `['not', 1, 2]` | for user accounts not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the current user's subscriptions #} +{% set subscriptions = craft.subscriptions() + .userId(currentUser.id) + .all() %} +``` + +```php +// Fetch the current user's subscriptions +$user = Craft::$app->user->getIdentity(); +$subscriptions = \craft\commerce\elements\Subscription::find() + ->userId($user->id) + ->all(); +``` +::: + + +### `with` + +Causes the query to return matching subscriptions eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch subscriptions eager-loaded with the "Related" field’s relations #} +{% set subscriptions = craft.subscriptions() + .with(['related']) + .all() %} +``` + +```php +// Fetch subscriptions eager-loaded with the "Related" field’s relations +$subscriptions = \craft\commerce\elements\Subscription::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/commerce/2.x/variant-queries.md b/docs/.artifacts/commerce/2.x/variant-queries.md new file mode 100644 index 000000000..b53fe1bfd --- /dev/null +++ b/docs/.artifacts/commerce/2.x/variant-queries.md @@ -0,0 +1,890 @@ + + + + +- [anyStatus](#anystatus) +- [asArray](#asarray) +- [dateCreated](#datecreated) +- [dateUpdated](#dateupdated) +- [fixedOrder](#fixedorder) +- [hasProduct](#hasproduct) +- [hasSales](#hassales) +- [hasStock](#hasstock) +- [id](#id) +- [ignorePlaceholders](#ignoreplaceholders) +- [inReverse](#inreverse) +- [isDefault](#isdefault) +- [limit](#limit) +- [maxQty](#maxqty) +- [minQty](#minqty) +- [offset](#offset) +- [orderBy](#orderby) +- [preferSites](#prefersites) +- [price](#price) +- [product](#product) +- [productId](#productid) +- [relatedTo](#relatedto) +- [search](#search) +- [site](#site) +- [siteId](#siteid) +- [sku](#sku) +- [status](#status) +- [stock](#stock) +- [title](#title) +- [trashed](#trashed) +- [typeId](#typeid) +- [uid](#uid) +- [unique](#unique) +- [with](#with) + +### `anyStatus` + +Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. + + + + + +::: code +```twig +{# Fetch all variants, regardless of status #} +{% set variants = craft.variants() + .anyStatus() + .all() %} +``` + +```php +// Fetch all variants, regardless of status +$variants = \craft\commerce\elements\Variant::find() + ->anyStatus() + ->all(); +``` +::: + + +### `asArray` + +Causes the query to return matching variants as arrays of data, rather than [Variant](commerce2:craft\commerce\elements\Variant) objects. + + + + + +::: code +```twig +{# Fetch variants as arrays #} +{% set variants = craft.variants() + .asArray() + .all() %} +``` + +```php +// Fetch variants as arrays +$variants = \craft\commerce\elements\Variant::find() + ->asArray() + ->all(); +``` +::: + + +### `dateCreated` + +Narrows the query results based on the variants’ creation dates. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch variants created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set variants = craft.variants() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch variants created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$variants = \craft\commerce\elements\Variant::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +### `dateUpdated` + +Narrows the query results based on the variants’ last-updated dates. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch variants updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set variants = craft.variants() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch variants updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$variants = \craft\commerce\elements\Variant::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + + + +::: code +```twig +{# Fetch variants in a specific order #} +{% set variants = craft.variants() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch variants in a specific order +$variants = \craft\commerce\elements\Variant::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +### `hasProduct` + +Narrows the query results to only variants for certain products. + +Possible values include: + +| Value | Fetches variants… +| - | - +| a [ProductQuery](commerce2:craft\commerce\elements\db\ProductQuery) object | for products that match the query. + + + + +### `hasSales` + +Narrows the query results to only variants that are on sale. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `true` | on sale +| `false` | not on sale + + + + +### `hasStock` + +Narrows the query results to only variants that have stock. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `true` | with stock. +| `false` | with no stock. + + + + +### `id` + +Narrows the query results based on the variants’ IDs. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the variant by its ID #} +{% set variant = craft.variants() + .id(1) + .one() %} +``` + +```php +// Fetch the variant by its ID +$variant = \craft\commerce\elements\Variant::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +### `ignorePlaceholders` + +Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch variants in reverse #} +{% set variants = craft.variants() + .inReverse() + .all() %} +``` + +```php +// Fetch variants in reverse +$variants = \craft\commerce\elements\Variant::find() + ->inReverse() + ->all(); +``` +::: + + +### `isDefault` + +Narrows the query results to only default variants. + + + +::: code +```twig +{# Fetch default variants #} +{% set variants = craft.variants() + .isDefault() + .all() %} +``` + +```php +// Fetch default variants +$variants = \craft\commerce\elements\Variant::find() + ->isDefault() + ->all(); +``` +::: + + +### `limit` + +Determines the number of variants that should be returned. + + + +::: code +```twig +{# Fetch up to 10 variants #} +{% set variants = craft.variants() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 variants +$variants = \craft\commerce\elements\Variant::find() + ->limit(10) + ->all(); +``` +::: + + +### `maxQty` + +Narrows the query results based on the variants’ max quantity. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a maxQty of 100. +| `'>= 100'` | with a maxQty of at least 100. +| `'< 100'` | with a maxQty of less than 100. + + + + +### `minQty` + +Narrows the query results based on the variants’ min quantity. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a minQty of 100. +| `'>= 100'` | with a minQty of at least 100. +| `'< 100'` | with a minQty of less than 100. + + + + +### `offset` + +Determines how many variants should be skipped in the results. + + + +::: code +```twig +{# Fetch all variants except for the first 3 #} +{% set variants = craft.variants() + .offset(3) + .all() %} +``` + +```php +// Fetch all variants except for the first 3 +$variants = \craft\commerce\elements\Variant::find() + ->offset(3) + ->all(); +``` +::: + + +### `orderBy` + +Determines the order that the variants should be returned in. + + + +::: code +```twig +{# Fetch all variants in order of date created #} +{% set variants = craft.variants() + .orderBy('dateCreated asc') + .all() %} +``` + +```php +// Fetch all variants in order of date created +$variants = \craft\commerce\elements\Variant::find() + ->orderBy('dateCreated asc') + ->all(); +``` +::: + + +### `preferSites` + +If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned +for Site B. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique variants from Site A, or Site B if they don’t exist in Site A #} +{% set variants = craft.variants() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique variants from Site A, or Site B if they don’t exist in Site A +$variants = \craft\commerce\elements\Variant::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +### `price` + +Narrows the query results based on the variants’ price. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a price of 100. +| `'>= 100'` | with a price of at least 100. +| `'< 100'` | with a price of less than 100. + + + + +### `product` + +Narrows the query results based on the variants’ product. + +Possible values include: + +| Value | Fetches variants… +| - | - +| a [Product](commerce2:craft\commerce\elements\Product) object | for a product represented by the object. + + + + +### `productId` + +Narrows the query results based on the variants’ products’ IDs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | for a product with an ID of 1. +| `[1, 2]` | for product with an ID of 1 or 2. +| `['not', 1, 2]` | for product not with an ID of 1 or 2. + + + + +### `relatedTo` + +Narrows the query results to only variants that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all variants that are related to myCategory #} +{% set variants = craft.variants() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all variants that are related to $myCategory +$variants = \craft\commerce\elements\Variant::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +### `search` + +Narrows the query results to only variants that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all variants that match the search query #} +{% set variants = craft.variants() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all variants that match the search query +$variants = \craft\commerce\elements\Variant::find() + ->search($searchQuery) + ->all(); +``` +::: + + +### `site` + +Determines which site(s) the variants should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a `\craft\commerce\elements\db\Site` object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch variants from the Foo site #} +{% set variants = craft.variants() + .site('foo') + .all() %} +``` + +```php +// Fetch variants from the Foo site +$variants = \craft\commerce\elements\Variant::find() + ->site('foo') + ->all(); +``` +::: + + +### `siteId` + +Determines which site(s) the variants should be queried in, per the site’s ID. + + + +The current site will be used by default. + + + +::: code +```twig +{# Fetch variants from the site with an ID of 1 #} +{% set variants = craft.variants() + .siteId(1) + .all() %} +``` + +```php +// Fetch variants from the site with an ID of 1 +$variants = \craft\commerce\elements\Variant::find() + ->siteId(1) + ->all(); +``` +::: + + +### `sku` + +Narrows the query results based on the variants’ SKUs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'foo'` | with a SKU of `foo`. +| `'foo*'` | with a SKU that begins with `foo`. +| `'*foo'` | with a SKU that ends with `foo`. +| `'*foo*'` | with a SKU that contains `foo`. +| `'not *foo*'` | with a SKU that doesn’t contain `foo`. +| `['*foo*', '*bar*'` | with a SKU that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a SKU that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested variant SKU from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the variant with that slug #} +{% set variant = craft.variants() + .sku(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested variant SKU from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the variant with that slug +$variant = \craft\commerce\elements\Variant::find() + ->sku(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +### `status` + +Narrows the query results based on the variants’ statuses. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'enabled'` _(default)_ | that are enabled. +| `'disabled'` | that are disabled. + + + +::: code +```twig +{# Fetch disabled variants #} +{% set variants = craft.variants() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled variants +$variants = \craft\commerce\elements\Variant::find() + ->status('disabled') + ->all(); +``` +::: + + +### `stock` + +Narrows the query results based on the variants’ stock. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `0` | with no stock. +| `'>= 5'` | with a stock of at least 5. +| `'< 10'` | with a stock of less than 10. + + + + +### `title` + +Narrows the query results based on the variants’ titles. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch variants with a title that contains "Foo" #} +{% set variants = craft.variants() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch variants with a title that contains "Foo" +$variants = \craft\commerce\elements\Variant::find() + ->title('*Foo*') + ->all(); +``` +::: + + +### `trashed` + +Narrows the query results to only variants that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed variants #} +{% set variants = craft.variants() + .trashed() + .all() %} +``` + +```php +// Fetch trashed variants +$variants = \craft\commerce\elements\Variant::find() + ->trashed() + ->all(); +``` +::: + + +### `typeId` + +Narrows the query results based on the variants’ product types, per their IDs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | for a product of a type with an ID of 1. +| `[1, 2]` | for product of a type with an ID of 1 or 2. +| `['not', 1, 2]` | for product of a type not with an ID of 1 or 2. + + + + +### `uid` + +Narrows the query results based on the variants’ UIDs. + + + + + +::: code +```twig +{# Fetch the variant by its UID #} +{% set variant = craft.variants() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the variant by its UID +$variant = \craft\commerce\elements\Variant::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +### `unique` + +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique variants across all sites #} +{% set variants = craft.variants() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique variants across all sites +$variants = \craft\commerce\elements\Variant::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +### `with` + +Causes the query to return matching variants eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch variants eager-loaded with the "Related" field’s relations #} +{% set variants = craft.variants() + .with(['related']) + .all() %} +``` + +```php +// Fetch variants eager-loaded with the "Related" field’s relations +$variants = \craft\commerce\elements\Variant::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/commerce/3.x/config.md b/docs/.artifacts/commerce/3.x/config.md new file mode 100644 index 000000000..ab163cd7f --- /dev/null +++ b/docs/.artifacts/commerce/3.x/config.md @@ -0,0 +1,788 @@ + + + + +## System + +### `defaultView` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'commerce/orders'` + +Defined by +: [Settings::$defaultView](commerce3:craft\commerce\models\Settings::$defaultView) + +Since +: 2.2 + +
+ +Commerce’s default control panel view. (Defaults to order index.) + + + +### `emailSenderAddress` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `null` + +Defined by +: [Settings::$emailSenderAddress](commerce3:craft\commerce\models\Settings::$emailSenderAddress) + +
+ +Default email address Commerce system messages should be sent from. + +If `null` (default), Craft’s [MailSettings::$fromEmail](craft3:craft\models\MailSettings::$fromEmail) will be used. + + + +### `emailSenderAddressPlaceholder` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `null` + +Defined by +: [Settings::$emailSenderAddressPlaceholder](commerce3:craft\commerce\models\Settings::$emailSenderAddressPlaceholder) + +
+ +Placeholder value displayed for the sender address control panel settings field. + +If `null` (default), Craft’s [MailSettings::$fromEmail](craft3:craft\models\MailSettings::$fromEmail) will be used. + + + +### `emailSenderName` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `null` + +Defined by +: [Settings::$emailSenderName](commerce3:craft\commerce\models\Settings::$emailSenderName) + +
+ +Default from name used for Commerce system emails. + +If `null` (default), Craft’s [MailSettings::$fromName](craft3:craft\models\MailSettings::$fromName) will be used. + + + +### `emailSenderNamePlaceholder` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `null` + +Defined by +: [Settings::$emailSenderNamePlaceholder](commerce3:craft\commerce\models\Settings::$emailSenderNamePlaceholder) + +
+ +Placeholder value displayed for the sender name control panel settings field. + +If `null` (default), Craft’s [MailSettings::$fromName](craft3:craft\models\MailSettings::$fromName) will be used. + + + +### `showCustomerInfoTab` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [Settings::$showCustomerInfoTab](commerce3:craft\commerce\models\Settings::$showCustomerInfoTab) + +Since +: 3.0 + +
+ +Whether the [customer info tab](customers.md#user-customer-info-tab) should be shown when viewing users in the control panel. + + + +## Cart + +### `activeCartDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `3600` (1 hour) + +Defined by +: [Settings::$activeCartDuration](commerce3:craft\commerce\models\Settings::$activeCartDuration) + +Since +: 2.2 + +
+ +How long a cart should go without being updated before it’s considered inactive. + +See [craft\helpers\ConfigHelper::durationInSeconds()](craft3:craft\helpers\ConfigHelper::durationInSeconds()) for a list of supported value types. + + + +### `allowCheckoutWithoutPayment` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$allowCheckoutWithoutPayment](commerce3:craft\commerce\models\Settings::$allowCheckoutWithoutPayment) + +Since +: 3.3 + +
+ +Whether carts are can be marked as completed without a payment. + + + +### `allowEmptyCartOnCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$allowEmptyCartOnCheckout](commerce3:craft\commerce\models\Settings::$allowEmptyCartOnCheckout) + +Since +: 2.2 + +
+ +Whether carts are allowed to be empty on checkout. + + + +### `autoSetCartShippingMethodOption` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$autoSetCartShippingMethodOption](commerce3:craft\commerce\models\Settings::$autoSetCartShippingMethodOption) + +
+ +Whether the first available shipping method option should be set automatically on carts. + + + +### `autoSetNewCartAddresses` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [Settings::$autoSetNewCartAddresses](commerce3:craft\commerce\models\Settings::$autoSetNewCartAddresses) + +
+ +Whether the customer’s primary shipping and billing addresses should be set automatically on new carts. + + + +### `cartVariable` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'cart'` + +Defined by +: [Settings::$cartVariable](commerce3:craft\commerce\models\Settings::$cartVariable) + +
+ +Key to be used when returning cart information in a response. + + + +### `loadCartRedirectUrl` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [Settings::$loadCartRedirectUrl](commerce3:craft\commerce\models\Settings::$loadCartRedirectUrl) + +Since +: 3.1 + +
+ +Default URL to be loaded after using the [load cart controller action](orders-carts.md#loading-a-cart). + +If `null` (default), Craft’s default [`siteUrl`](config3:siteUrl) will be used. + + + +### `purgeInactiveCarts` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [Settings::$purgeInactiveCarts](commerce3:craft\commerce\models\Settings::$purgeInactiveCarts) + +
+ +Whether inactive carts should automatically be deleted from the database during garbage collection. + +::: tip +You can control how long a cart should go without being updated before it gets deleted [`purgeInactiveCartsDuration`](#purgeinactivecartsduration) setting. +::: + + + +### `purgeInactiveCartsDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `7776000` (90 days) + +Defined by +: [Settings::$purgeInactiveCartsDuration](commerce3:craft\commerce\models\Settings::$purgeInactiveCartsDuration) + +
+ +Default length of time before inactive carts are purged. (Defaults to 90 days.) + +See [craft\helpers\ConfigHelper::durationInSeconds()](craft3:craft\helpers\ConfigHelper::durationInSeconds()) for a list of supported value types. + + + +### `updateCartSearchIndexes` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [Settings::$updateCartSearchIndexes](commerce3:craft\commerce\models\Settings::$updateCartSearchIndexes) + +Since +: 3.1.5 + +
+ +Whether the search index for a cart should be updated when saving the cart via `commerce/cart/*` controller actions. + +May be set to `false` to reduce performance impact on high-traffic sites. + +::: warning +Setting this to `false` will result in fewer index update queue jobs, but you’ll need to manually re-index orders to ensure up-to-date cart search results in the control panel. +::: + + + +### `validateCartCustomFieldsOnSubmission` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$validateCartCustomFieldsOnSubmission](commerce3:craft\commerce\models\Settings::$validateCartCustomFieldsOnSubmission) + +Since +: 3.0.12 + +
+ +Whether to validate custom fields when a cart is updated. + +Set to `true` to allow custom content fields to return validation errors when a cart is updated. + + + +## Orders + +### `freeOrderPaymentStrategy` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'complete'` + +Defined by +: [Settings::$freeOrderPaymentStrategy](commerce3:craft\commerce\models\Settings::$freeOrderPaymentStrategy) + +
+ +How Commerce should handle free orders. + +The default `'complete'` setting automatically completes zero-balance orders without forwarding them to the payment gateway. + +The `'process'` setting forwards zero-balance orders to the payment gateway for processing. This can be useful if the customer’s balance +needs to be updated or otherwise adjusted by the payment gateway. + + + +### `minimumTotalPriceStrategy` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'default'` + +Defined by +: [Settings::$minimumTotalPriceStrategy](commerce3:craft\commerce\models\Settings::$minimumTotalPriceStrategy) + +
+ +How Commerce should handle minimum total price for an order. + +Options: + +- `'default'` [rounds](commerce3:\craft\commerce\helpers\Currency::round()) the sum of the item subtotal and adjustments. +- `'zero'` returns `0` if the result from `'default'` would’ve been negative; minimum order total is `0`. +- `'shipping'` returns the total shipping cost if the `'default'` result would’ve been negative; minimum order total equals shipping amount. + + + +### `orderReferenceFormat` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'{{number[:7]}}'` + +Defined by +: [Settings::$orderReferenceFormat](commerce3:craft\commerce\models\Settings::$orderReferenceFormat) + +
+ +Human-friendly reference number format for orders. Result must be unique. + +See [Order Numbers](orders-carts.md#order-numbers). + + + +### `pdfAllowRemoteImages` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$pdfAllowRemoteImages](commerce3:craft\commerce\models\Settings::$pdfAllowRemoteImages) + +
+ +Whether to allow non-local images in generated order PDFs. + + + +### `pdfPaperOrientation` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'portrait'` + +Defined by +: [Settings::$pdfPaperOrientation](commerce3:craft\commerce\models\Settings::$pdfPaperOrientation) + +
+ +The orientation of the paper to use for generated order PDF files. + +Options are `'portrait'` and `'landscape'`. + + + +### `pdfPaperSize` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'letter'` + +Defined by +: [Settings::$pdfPaperSize](commerce3:craft\commerce\models\Settings::$pdfPaperSize) + +
+ +The size of the paper to use for generated order PDFs. + +The full list of supported paper sizes can be found [in the dompdf library](https://github.com/dompdf/dompdf/blob/master/src/Adapter/CPDF.php#L45). + + + +### `requireBillingAddressAtCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$requireBillingAddressAtCheckout](commerce3:craft\commerce\models\Settings::$requireBillingAddressAtCheckout) + +
+ +Whether a billing address is required before making payment on an order. + + + +### `requireShippingAddressAtCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$requireShippingAddressAtCheckout](commerce3:craft\commerce\models\Settings::$requireShippingAddressAtCheckout) + +
+ +Whether a shipping address is required before making payment on an order. + + + +### `requireShippingMethodSelectionAtCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$requireShippingMethodSelectionAtCheckout](commerce3:craft\commerce\models\Settings::$requireShippingMethodSelectionAtCheckout) + +
+ +Whether shipping method selection is required before making payment on an order. + + + +### `updateBillingDetailsUrl` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [Settings::$updateBillingDetailsUrl](commerce3:craft\commerce\models\Settings::$updateBillingDetailsUrl) + +
+ +URL for a user to resolve billing issues with their subscription. + +::: tip +The example templates include [a template for this page](https://github.com/craftcms/commerce/tree/main/example-templates/dist/shop/plans/update-billing-details.twig). +::: + + + +### `useBillingAddressForTax` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$useBillingAddressForTax](commerce3:craft\commerce\models\Settings::$useBillingAddressForTax) + +
+ +Whether taxes should be calculated based on the billing address instead of the shipping address. + + + +### `validateBusinessTaxIdAsVatId` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$validateBusinessTaxIdAsVatId](commerce3:craft\commerce\models\Settings::$validateBusinessTaxIdAsVatId) + +
+ +Whether to enable validation requiring the `businessTaxId` to be a valid VAT ID. + +When set to `false`, no validation is applied to `businessTaxId`. + +When set to `true`, `businessTaxId` must contain a valid VAT ID. + +::: tip +This setting strictly toggles input validation and has no impact on tax configuration or behavior elsewhere in the system. +::: + + + +## Payments + +### `allowPartialPaymentOnCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$allowPartialPaymentOnCheckout](commerce3:craft\commerce\models\Settings::$allowPartialPaymentOnCheckout) + +
+ +Whether [partial payment](making-payments.md#checkout-with-partial-payment) can be made from the front end when the gateway allows them. + +The `false` default does not allow partial payments on the front end. + + + +### `gatewayPostRedirectTemplate` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [Settings::$gatewayPostRedirectTemplate](commerce3:craft\commerce\models\Settings::$gatewayPostRedirectTemplate) + +
+ +The path to the template that should be used to perform POST requests to offsite payment gateways. + +The template must contain a form that posts to the URL supplied by the `actionUrl` variable and outputs all hidden inputs with +the `inputs` variable. + +```twig + + + + + Redirecting... + + +
+

Redirecting to payment page...

+

+ {{ inputs|raw }} + +

+
+ + +``` + +::: tip +Since this template is simply used for redirecting, it only appears for a few seconds, so we suggest making it load fast with minimal +images and inline styles to reduce HTTP requests. +::: + +If empty (default), each gateway will decide how to handle after-payment redirects. + + + +### `paymentCurrency` + +
+ +Allowed types +: [array](https://php.net/language.types.array) + +Default value +: `null` + +Defined by +: [Settings::$paymentCurrency](commerce3:craft\commerce\models\Settings::$paymentCurrency) + +
+ +ISO codes for supported payment currencies. + +See [Payment Currencies](payment-currencies.md). + + + +## Units + +### `dimensionUnits` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'mm'` + +Defined by +: [Settings::$dimensionUnits](commerce3:craft\commerce\models\Settings::$dimensionUnits) + +
+ +Unit type for dimension measurements. + +Options: + +- `'mm'` +- `'cm'` +- `'m'` +- `'ft'` +- `'in'` + + + +### `weightUnits` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'g'` + +Defined by +: [Settings::$weightUnits](commerce3:craft\commerce\models\Settings::$weightUnits) + +
+ +Units to be used for weight measurements. + +Options: + +- `'g'` +- `'kg'` +- `'lb'` + + + + + diff --git a/docs/commerce/3.x/event-data/events.json b/docs/.artifacts/commerce/3.x/events.json similarity index 100% rename from docs/commerce/3.x/event-data/events.json rename to docs/.artifacts/commerce/3.x/events.json diff --git a/docs/.artifacts/commerce/3.x/orders-carts.md b/docs/.artifacts/commerce/3.x/orders-carts.md new file mode 100644 index 000000000..9f3ab0dfa --- /dev/null +++ b/docs/.artifacts/commerce/3.x/orders-carts.md @@ -0,0 +1,1395 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only orders that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. +| [asArray](#asarray) | Causes the query to return matching orders as arrays of data, rather than [Order](commerce3:craft\commerce\elements\Order) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [customer](#customer) | Narrows the query results based on the customer. +| [customerId](#customerid) | Narrows the query results based on the customer, per their ID. +| [dateAuthorized](#dateauthorized) | Narrows the query results based on the orders’ authorized dates. +| [dateCreated](#datecreated) | Narrows the query results based on the orders’ creation dates. +| [dateOrdered](#dateordered) | Narrows the query results based on the orders’ completion dates. +| [datePaid](#datepaid) | Narrows the query results based on the orders’ paid dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the orders’ last-updated dates. +| [email](#email) | Narrows the query results based on the customers’ email addresses. +| [expiryDate](#expirydate) | Narrows the query results based on the orders’ expiry dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [gateway](#gateway) | Narrows the query results based on the gateway. +| [gatewayId](#gatewayid) | Narrows the query results based on the gateway, per its ID. +| [hasLineItems](#haslineitems) | Narrows the query results to only orders that have line items. +| [hasPurchasables](#haspurchasables) | Narrows the query results to only orders that have certain purchasables. +| [hasTransactions](#hastransactions) | Narrows the query results to only carts that have at least one transaction. +| [id](#id) | Narrows the query results based on the orders’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [isCompleted](#iscompleted) | Narrows the query results to only orders that are completed. +| [isPaid](#ispaid) | Narrows the query results to only orders that are paid. +| [isUnpaid](#isunpaid) | Narrows the query results to only orders that are not paid. +| [limit](#limit) | Determines the number of orders that should be returned. +| [number](#number) | Narrows the query results based on the order number. +| [offset](#offset) | Determines how many orders should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the orders should be returned in. (If empty, defaults to `id ASC`.) +| [orderLanguage](#orderlanguage) | Narrows the query results based on the order language, per the language string provided. +| [orderSiteId](#ordersiteid) | Narrows the query results based on the order language, per the language string provided. +| [orderStatus](#orderstatus) | Narrows the query results based on the order statuses. +| [orderStatusId](#orderstatusid) | Narrows the query results based on the order statuses, per their IDs. +| [origin](#origin) | Narrows the query results based on the origin. +| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. +| [reference](#reference) | Narrows the query results based on the order reference. +| [relatedTo](#relatedto) | Narrows the query results to only orders that are related to certain other elements. +| [search](#search) | Narrows the query results to only orders that match a search query. +| [shortNumber](#shortnumber) | Narrows the query results based on the order short number. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the orders’ IDs in the `elements_sites` table. +| [trashed](#trashed) | Narrows the query results to only orders that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the orders’ UIDs. +| [user](#user) | Narrows the query results based on the customer’s user account. +| [with](#with) | Causes the query to return matching orders eager-loaded with related elements. +| [withAddresses](#withaddresses) | Eager loads the the shipping and billing addressees on the resulting orders. +| [withAdjustments](#withadjustments) | Eager loads the order adjustments on the resulting orders. +| [withAll](#withall) | Eager loads all relational data (addresses, adjustents, customers, line items, transactions) for the resulting orders. +| [withCustomer](#withcustomer) | Eager loads the customer (and related user) on the resulting orders. +| [withLineItems](#withlineitems) | Eager loads the line items on the resulting orders. +| [withTransactions](#withtransactions) | Eager loads the transactions on the resulting orders. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only orders that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all orders that are related to myCategoryA and myCategoryB #} +{% set orders = craft.orders() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all orders that are related to $myCategoryA and $myCategoryB +$orders = \craft\commerce\elements\Order::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all orders, regardless of status #} +{% set orders = craft.orders() + .anyStatus() + .all() %} +``` + +```php +// Fetch all orders, regardless of status +$orders = \craft\commerce\elements\Order::find() + ->anyStatus() + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching orders as arrays of data, rather than [Order](commerce3:craft\commerce\elements\Order) objects. + + + + + +::: code +```twig +{# Fetch orders as arrays #} +{% set orders = craft.orders() + .asArray() + .all() %} +``` + +```php +// Fetch orders as arrays +$orders = \craft\commerce\elements\Order::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `customer` + +Narrows the query results based on the customer. + +Possible values include: + +| Value | Fetches orders… +| - | - +| a [Customer](commerce3:craft\commerce\models\Customer) object | with a customer represented by the object. + + + +::: code +```twig +{# Fetch the current user's orders #} +{% set orders = craft.orders() + .customer(currentUser.customerFieldHandle) + .all() %} +``` + +```php +// Fetch the current user's orders +$user = Craft::$app->user->getIdentity(); +$orders = \craft\commerce\elements\Order::find() + ->customer($user->customerFieldHandle) + ->all(); +``` +::: + + +#### `customerId` + +Narrows the query results based on the customer, per their ID. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a customer with an ID of 1. +| `'not 1'` | not with a customer with an ID of 1. +| `[1, 2]` | with a customer with an ID of 1 or 2. +| `['not', 1, 2]` | not with a customer with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the current user's orders #} +{% set orders = craft.orders() + .customerId(currentUser.customerFieldHandle.id) + .all() %} +``` + +```php +// Fetch the current user's orders +$user = Craft::$app->user->getIdentity(); +$orders = \craft\commerce\elements\Order::find() + ->customerId($user->customerFieldHandle->id) + ->all(); +``` +::: + + +#### `dateAuthorized` + +Narrows the query results based on the orders’ authorized dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were authorized on or after 2018-04-01. +| `'< 2018-05-01'` | that were authorized before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders that were authorized recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set orders = craft.orders() + .dateAuthorized(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch orders that were authorized recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateAuthorized(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `dateCreated` + +Narrows the query results based on the orders’ creation dates. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set orders = craft.orders() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch orders created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateOrdered` + +Narrows the query results based on the orders’ completion dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were completed on or after 2018-04-01. +| `'< 2018-05-01'` | that were completed before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders that were completed recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set orders = craft.orders() + .dateOrdered(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch orders that were completed recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateOrdered(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `datePaid` + +Narrows the query results based on the orders’ paid dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were paid on or after 2018-04-01. +| `'< 2018-05-01'` | that were paid before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders that were paid for recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set orders = craft.orders() + .datePaid(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch orders that were paid for recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->datePaid(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the orders’ last-updated dates. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set orders = craft.orders() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch orders updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `email` + +Narrows the query results based on the customers’ email addresses. + +Possible values include: + +| Value | Fetches orders with customers… +| - | - +| `'foo@bar.baz'` | with an email of `foo@bar.baz`. +| `'not foo@bar.baz'` | not with an email of `foo@bar.baz`. +| `'*@bar.baz'` | with an email that ends with `@bar.baz`. + + + +::: code +```twig +{# Fetch orders from customers with a .co.uk domain on their email address #} +{% set orders = craft.orders() + .email('*.co.uk') + .all() %} +``` + +```php +// Fetch orders from customers with a .co.uk domain on their email address +$orders = \craft\commerce\elements\Order::find() + ->email('*.co.uk') + ->all(); +``` +::: + + +#### `expiryDate` + +Narrows the query results based on the orders’ expiry dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. +| `'< 2020-05-01'` | that will expire before 2020-05-01 +| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. + + + +::: code +```twig +{# Fetch orders expiring this month #} +{% set nextMonth = date('first day of next month')|atom %} + +{% set orders = craft.orders() + .expiryDate("< #{nextMonth}") + .all() %} +``` + +```php +// Fetch orders expiring this month +$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->expiryDate("< {$nextMonth}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + + + +::: code +```twig +{# Fetch orders in a specific order #} +{% set orders = craft.orders() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch orders in a specific order +$orders = \craft\commerce\elements\Order::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `gateway` + +Narrows the query results based on the gateway. + +Possible values include: + +| Value | Fetches orders… +| - | - +| a [Gateway](commerce3:craft\commerce\base\Gateway) object | with a gateway represented by the object. + + + + +#### `gatewayId` + +Narrows the query results based on the gateway, per its ID. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a gateway with an ID of 1. +| `'not 1'` | not with a gateway with an ID of 1. +| `[1, 2]` | with a gateway with an ID of 1 or 2. +| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. + + + + +#### `hasLineItems` + +Narrows the query results to only orders that have line items. + + + +::: code +```twig +{# Fetch orders that do or do not have line items #} +{% set orders = craft.orders() + .hasLineItems() + .all() %} +``` + +```php +// Fetch unpaid orders +$orders = \craft\commerce\elements\Order::find() + ->hasLineItems() + ->all(); +``` +::: + + +#### `hasPurchasables` + +Narrows the query results to only orders that have certain purchasables. + +Possible values include: + +| Value | Fetches orders… +| - | - +| a [PurchasableInterface](commerce3:craft\commerce\base\PurchasableInterface) object | with a purchasable represented by the object. +| an array of [PurchasableInterface](commerce3:craft\commerce\base\PurchasableInterface) objects | with all the purchasables represented by the objects. + + + + +#### `hasTransactions` + +Narrows the query results to only carts that have at least one transaction. + + + +::: code +```twig +{# Fetch carts that have attempted payments #} +{% set orders = craft.orders() + .hasTransactions() + .all() %} +``` + +```php +// Fetch carts that have attempted payments +$orders = \craft\commerce\elements\Order::find() + ->hasTransactions() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the orders’ IDs. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the order by its ID #} +{% set order = craft.orders() + .id(1) + .one() %} +``` + +```php +// Fetch the order by its ID +$order = \craft\commerce\elements\Order::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch orders in reverse #} +{% set orders = craft.orders() + .inReverse() + .all() %} +``` + +```php +// Fetch orders in reverse +$orders = \craft\commerce\elements\Order::find() + ->inReverse() + ->all(); +``` +::: + + +#### `isCompleted` + +Narrows the query results to only orders that are completed. + + + +::: code +```twig +{# Fetch completed orders #} +{% set orders = craft.orders() + .isCompleted() + .all() %} +``` + +```php +// Fetch completed orders +$orders = \craft\commerce\elements\Order::find() + ->isCompleted() + ->all(); +``` +::: + + +#### `isPaid` + +Narrows the query results to only orders that are paid. + + + +::: code +```twig +{# Fetch paid orders #} +{% set orders = craft.orders() + .isPaid() + .all() %} +``` + +```php +// Fetch paid orders +$orders = \craft\commerce\elements\Order::find() + ->isPaid() + ->all(); +``` +::: + + +#### `isUnpaid` + +Narrows the query results to only orders that are not paid. + + + +::: code +```twig +{# Fetch unpaid orders #} +{% set orders = craft.orders() + .isUnpaid() + .all() %} +``` + +```php +// Fetch unpaid orders +$orders = \craft\commerce\elements\Order::find() + ->isUnpaid() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of orders that should be returned. + + + +::: code +```twig +{# Fetch up to 10 orders #} +{% set orders = craft.orders() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 orders +$orders = \craft\commerce\elements\Order::find() + ->limit(10) + ->all(); +``` +::: + + +#### `number` + +Narrows the query results based on the order number. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'` | with a matching order number + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderNumber = craft.app.request.getQueryParam('number') %} +{% set order = craft.orders() + .number(orderNumber) + .one() %} +``` + +```php +// Fetch the requested order +$orderNumber = Craft::$app->request->getQueryParam('number'); +$order = \craft\commerce\elements\Order::find() + ->number($orderNumber) + ->one(); +``` +::: + + +#### `offset` + +Determines how many orders should be skipped in the results. + + + +::: code +```twig +{# Fetch all orders except for the first 3 #} +{% set orders = craft.orders() + .offset(3) + .all() %} +``` + +```php +// Fetch all orders except for the first 3 +$orders = \craft\commerce\elements\Order::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the orders should be returned in. (If empty, defaults to `id ASC`.) + + + +::: code +```twig +{# Fetch all orders in order of date created #} +{% set orders = craft.orders() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all orders in order of date created +$orders = \craft\commerce\elements\Order::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `orderLanguage` + +Narrows the query results based on the order language, per the language string provided. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `en` | with an order language that is `'en'`. +| `'not en'` | not with an order language that is not `'en'`. +| `['en', 'en-us']` | with an order language that is `'en'` or `'en-us'`. +| `['not', 'en']` | not with an order language that is not `'en'`. + + + +::: code +```twig +{# Fetch orders with an order status with an ID of 1 #} +{% set orders = craft.orders() + .orderLanguage('en') + .all() %} +``` + +```php +// Fetch orders with an order status with an ID of 1 +$orders = \craft\commerce\elements\Order::find() + ->orderLanguage('en') + ->all(); +``` +::: + + +#### `orderSiteId` + +Narrows the query results based on the order language, per the language string provided. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an order site ID of 1. +| `'not 1'` | not with an order site ID that is no 1. +| `[1, 2]` | with an order site ID of 1 or 2. +| `['not', 1, 2]` | not with an order site ID of 1 or 2. + + + +::: code +```twig +{# Fetch orders with an order site ID of 1 #} +{% set orders = craft.orders() + .orderSiteId(1) + .all() %} +``` + +```php +// Fetch orders with an order site ID of 1 +$orders = \craft\commerce\elements\Order::find() + ->orderSiteId(1) + ->all(); +``` +::: + + +#### `orderStatus` + +Narrows the query results based on the order statuses. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'foo'` | with an order status with a handle of `foo`. +| `'not foo'` | not with an order status with a handle of `foo`. +| `['foo', 'bar']` | with an order status with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not with an order status with a handle of `foo` or `bar`. +| a [OrderStatus](commerce3:craft\commerce\models\OrderStatus) object | with an order status represented by the object. + + + +::: code +```twig +{# Fetch shipped orders #} +{% set orders = craft.orders() + .orderStatus('shipped') + .all() %} +``` + +```php +// Fetch shipped orders +$orders = \craft\commerce\elements\Order::find() + ->orderStatus('shipped') + ->all(); +``` +::: + + +#### `orderStatusId` + +Narrows the query results based on the order statuses, per their IDs. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an order status with an ID of 1. +| `'not 1'` | not with an order status with an ID of 1. +| `[1, 2]` | with an order status with an ID of 1 or 2. +| `['not', 1, 2]` | not with an order status with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch orders with an order status with an ID of 1 #} +{% set orders = craft.orders() + .orderStatusId(1) + .all() %} +``` + +```php +// Fetch orders with an order status with an ID of 1 +$orders = \craft\commerce\elements\Order::find() + ->orderStatusId(1) + ->all(); +``` +::: + + +#### `origin` + +Narrows the query results based on the origin. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'web'` | with an origin of `web`. +| `'not remote'` | not with an origin of `remote`. +| `['web', 'cp']` | with an order origin of `web` or `cp`. +| `['not', 'remote', 'cp']` | not with an origin of `web` or `cp`. + + + +::: code +```twig +{# Fetch shipped orders #} +{% set orders = craft.orders() + .origin('web') + .all() %} +``` + +```php +// Fetch shipped orders +$orders = \craft\commerce\elements\Order::find() + ->origin('web') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned +for Site B. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique orders from Site A, or Site B if they don’t exist in Site A #} +{% set orders = craft.orders() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique orders from Site A, or Site B if they don’t exist in Site A +$orders = \craft\commerce\elements\Order::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `reference` + +Narrows the query results based on the order reference. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'xxxx'` | with a matching order reference + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderReference = craft.app.request.getQueryParam('ref') %} +{% set order = craft.orders() + .reference(orderReference) + .one() %} +``` + +```php +// Fetch the requested order +$orderReference = Craft::$app->request->getQueryParam('ref'); +$order = \craft\commerce\elements\Order::find() + ->reference($orderReference) + ->one(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only orders that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all orders that are related to myCategory #} +{% set orders = craft.orders() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all orders that are related to $myCategory +$orders = \craft\commerce\elements\Order::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only orders that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all orders that match the search query #} +{% set orders = craft.orders() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all orders that match the search query +$orders = \craft\commerce\elements\Order::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `shortNumber` + +Narrows the query results based on the order short number. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'xxxxxxx'` | with a matching order number + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderNumber = craft.app.request.getQueryParam('shortNumber') %} +{% set order = craft.orders() + .shortNumber(orderNumber) + .one() %} +``` + +```php +// Fetch the requested order +$orderNumber = Craft::$app->request->getQueryParam('shortNumber'); +$order = \craft\commerce\elements\Order::find() + ->shortNumber($orderNumber) + ->one(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the orders’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the order by its ID in the elements_sites table #} +{% set order = craft.orders() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the order by its ID in the elements_sites table +$order = \craft\commerce\elements\Order::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `trashed` + +Narrows the query results to only orders that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed orders #} +{% set orders = craft.orders() + .trashed() + .all() %} +``` + +```php +// Fetch trashed orders +$orders = \craft\commerce\elements\Order::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the orders’ UIDs. + + + + + +::: code +```twig +{# Fetch the order by its UID #} +{% set order = craft.orders() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the order by its UID +$order = \craft\commerce\elements\Order::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `user` + +Narrows the query results based on the customer’s user account. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a customer with a user account ID of 1. +| a [User](https://docs.craftcms.com/api/v3/craft-elements-user.html) object | with a customer with a user account represented by the object. + + + +::: code +```twig +{# Fetch the current user's orders #} +{% set orders = craft.orders() + .user(currentUser) + .all() %} +``` + +```php +// Fetch the current user's orders +$user = Craft::$app->user->getIdentity(); +$orders = \craft\commerce\elements\Order::find() + ->user($user) + ->all(); +``` +::: + + +#### `with` + +Causes the query to return matching orders eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch orders eager-loaded with the "Related" field’s relations #} +{% set orders = craft.orders() + .with(['related']) + .all() %} +``` + +```php +// Fetch orders eager-loaded with the "Related" field’s relations +$orders = \craft\commerce\elements\Order::find() + ->with(['related']) + ->all(); +``` +::: + + +#### `withAddresses` + +Eager loads the the shipping and billing addressees on the resulting orders. + +Possible values include: + +| Value | Fetches addresses +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withAdjustments` + +Eager loads the order adjustments on the resulting orders. + +Possible values include: + +| Value | Fetches adjustments +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withAll` + +Eager loads all relational data (addresses, adjustents, customers, line items, transactions) for the resulting orders. + +Possible values include: + +| Value | Fetches addresses, adjustents, customers, line items, transactions +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withCustomer` + +Eager loads the customer (and related user) on the resulting orders. + +Possible values include: + +| Value | Fetches adjustments +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withLineItems` + +Eager loads the line items on the resulting orders. + +Possible values include: + +| Value | Fetches line items… +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withTransactions` + +Eager loads the transactions on the resulting orders. + +Possible values include: + +| Value | Fetches transactions… +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + + + diff --git a/docs/.artifacts/commerce/3.x/products-variants.md b/docs/.artifacts/commerce/3.x/products-variants.md new file mode 100644 index 000000000..ba8edfa75 --- /dev/null +++ b/docs/.artifacts/commerce/3.x/products-variants.md @@ -0,0 +1,2577 @@ + + +## Product Query Parameters + +Product queries support the following parameters: + + + + + + + +| Param | Description +| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [after](#product-after) | Narrows the query results to only products that were posted on or after a certain date. +| [afterPopulate](#product-afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#product-andrelatedto) | Narrows the query results to only products that are related to certain other elements. +| [anyStatus](#product-anystatus) | Removes element filters based on their statuses. +| [asArray](#product-asarray) | Causes the query to return matching products as arrays of data, rather than [Product](commerce3:craft\commerce\elements\Product) objects. +| [availableForPurchase](#product-availableforpurchase) | Narrows the query results to only products that are available for purchase. +| [before](#product-before) | Narrows the query results to only products that were posted before a certain date. +| [cache](#product-cache) | Enables query cache for this Query. +| [clearCachedResult](#product-clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#product-datecreated) | Narrows the query results based on the products’ creation dates. +| [dateUpdated](#product-dateupdated) | Narrows the query results based on the products’ last-updated dates. +| [defaultHeight](#product-defaultheight) | Narrows the query results based on the products’ default variant height dimension IDs. +| [defaultLength](#product-defaultlength) | Narrows the query results based on the products’ default variant length dimension IDs. +| [defaultPrice](#product-defaultprice) | Narrows the query results based on the products’ default variant price. +| [defaultSku](#product-defaultsku) | Narrows the query results based on the default productvariants defaultSku +| [defaultWeight](#product-defaultweight) | Narrows the query results based on the products’ default variant weight dimension IDs. +| [defaultWidth](#product-defaultwidth) | Narrows the query results based on the products’ default variant width dimension IDs. +| [expiryDate](#product-expirydate) | Narrows the query results based on the products’ expiry dates. +| [fixedOrder](#product-fixedorder) | Causes the query results to be returned in the order specified by [id](#product-id). +| [hasVariant](#product-hasvariant) | Narrows the query results to only products that have certain variants. +| [id](#product-id) | Narrows the query results based on the products’ IDs. +| [ignorePlaceholders](#product-ignoreplaceholders) | Causes the query to return matching products as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#product-inreverse) | Causes the query results to be returned in reverse order. +| [limit](#product-limit) | Determines the number of products that should be returned. +| [offset](#product-offset) | Determines how many products should be skipped in the results. +| [orderBy](#product-orderby) | Determines the order that the products should be returned in. (If empty, defaults to `postDate DESC`.) +| [postDate](#product-postdate) | Narrows the query results based on the products’ post dates. +| [preferSites](#product-prefersites) | If [unique](#product-unique) is set, this determines which site should be selected when querying multi-site elements. +| [relatedTo](#product-relatedto) | Narrows the query results to only products that are related to certain other elements. +| [search](#product-search) | Narrows the query results to only products that match a search query. +| [site](#product-site) | Determines which site(s) the products should be queried in. +| [siteId](#product-siteid) | Determines which site(s) the products should be queried in, per the site’s ID. +| [siteSettingsId](#product-sitesettingsid) | Narrows the query results based on the products’ IDs in the `elements_sites` table. +| [slug](#product-slug) | Narrows the query results based on the products’ slugs. +| [status](#product-status) | Narrows the query results based on the products’ statuses. +| [title](#product-title) | Narrows the query results based on the products’ titles. +| [trashed](#product-trashed) | Narrows the query results to only products that have been soft-deleted. +| [type](#product-type) | Narrows the query results based on the products’ types. +| [typeId](#product-typeid) | Narrows the query results based on the products’ types, per the types’ IDs. +| [uid](#product-uid) | Narrows the query results based on the products’ UIDs. +| [unique](#product-unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uri](#product-uri) | Narrows the query results based on the products’ URIs. +| [with](#product-with) | Causes the query to return matching products eager-loaded with related elements. + + + + + +

# after

+ +Narrows the query results to only products that were posted on or after a certain date. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'2018-04-01'` | that were posted after 2018-04-01. +| a [DateTime](https://php.net/class.datetime) object | that were posted after the date represented by the object. + + + +::: code +```twig +{# Fetch products posted this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set products = craft.products() + .after(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch products posted this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$products = \craft\commerce\elements\Product::find() + ->after($firstDayOfMonth) + ->all(); +``` +::: + + +

# afterPopulate

+ +Performs any post-population processing on elements. + + + + + + + + + + +

# andRelatedTo

+ +Narrows the query results to only products that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all products that are related to myCategoryA and myCategoryB #} +{% set products = craft.products() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all products that are related to $myCategoryA and $myCategoryB +$products = \craft\commerce\elements\Product::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +

# anyStatus

+ +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all products, regardless of status #} +{% set products = craft.products() + .anyStatus() + .all() %} +``` + +```php +// Fetch all products, regardless of status +$products = \craft\commerce\elements\Product::find() + ->anyStatus() + ->all(); +``` +::: + + +

# asArray

+ +Causes the query to return matching products as arrays of data, rather than [Product](commerce3:craft\commerce\elements\Product) objects. + + + + + +::: code +```twig +{# Fetch products as arrays #} +{% set products = craft.products() + .asArray() + .all() %} +``` + +```php +// Fetch products as arrays +$products = \craft\commerce\elements\Product::find() + ->asArray() + ->all(); +``` +::: + + +

# availableForPurchase

+ +Narrows the query results to only products that are available for purchase. + + + +::: code +```twig +{# Fetch products that are available for purchase #} +{% set products = craft.products() + .availableForPurchase() + .all() %} +``` + +```php +// Fetch products that are available for purchase +$products = \craft\commerce\elements\Product::find() + ->availableForPurchase() + ->all(); +``` +::: + + +

# before

+ +Narrows the query results to only products that were posted before a certain date. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'2018-04-01'` | that were posted before 2018-04-01. +| a [DateTime](https://php.net/class.datetime) object | that were posted before the date represented by the object. + + + +::: code +```twig +{# Fetch products posted before this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set products = craft.products() + .before(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch products posted before this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$products = \craft\commerce\elements\Product::find() + ->before($firstDayOfMonth) + ->all(); +``` +::: + + +

# cache

+ +Enables query cache for this Query. + + + + + + + + + + +

# clearCachedResult

+ +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +

# dateCreated

+ +Narrows the query results based on the products’ creation dates. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch products created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set products = craft.products() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch products created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +

# dateUpdated

+ +Narrows the query results based on the products’ last-updated dates. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch products updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set products = craft.products() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch products updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +

# defaultHeight

+ +Narrows the query results based on the products’ default variant height dimension IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with a dimension of 1. +| `'not 1'` | not a dimension of 1. +| `[1, 2]` | of a a dimension 1 or 2. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product default dimension of 1 #} +{% set products = craft.products() + .defaultHeight(1) + .all() %} +``` + +```php +// Fetch products of the product default dimension of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultHeight(1) + ->all(); +``` +::: + + +

# defaultLength

+ +Narrows the query results based on the products’ default variant length dimension IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with a dimension of 1. +| `'not 1'` | not a dimension of 1. +| `[1, 2]` | of a a dimension 1 or 2. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product default dimension of 1 #} +{% set products = craft.products() + .defaulLength(1) + .all() %} +``` + +```php +// Fetch products of the product default dimension of 1 +$products = \craft\commerce\elements\Product::find() + ->defaulLength(1) + ->all(); +``` +::: + + +

# defaultPrice

+ +Narrows the query results based on the products’ default variant price. + +Possible values include: + +| Value | Fetches products… +| - | - +| `10` | of a price of 10. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a default variant price between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product type with an ID of 1 #} +{% set products = craft.products() + .defaultPrice(1) + .all() %} +``` + +```php +// Fetch products of the product type with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultPrice(1) + ->all(); +``` +::: + + +

# defaultSku

+ +Narrows the query results based on the default productvariants defaultSku + +Possible values include: + +| Value | Fetches products… +| - | - +| `xxx-001` | of products defaukt SKU of `xxx-001`. +| `'not xxx-001'` | not a defaukt SKU of `xxx-001`. +| `['not xxx-001', 'not xxx-002']` | of a default SKU of xxx-001 or xxx-002. +| `['not', `xxx-001`, `xxx-002`]` | not a product defaukt SKU of `xxx-001` or `xxx-001`. + + + +::: code +```twig +{# Fetch products of the product defaukt SKU of `xxx-001` #} +{% set products = craft.products() + .defaultSku('xxx-001') + .all() %} +``` + +```php +// Fetch products of the product defaukt SKU of `xxx-001` +$products = \craft\commerce\elements\Product::find() + ->defaultSku('xxx-001') + ->all(); +``` +::: + + +

# defaultWeight

+ +Narrows the query results based on the products’ default variant weight dimension IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with a dimension of 1. +| `'not 1'` | not a dimension of 1. +| `[1, 2]` | of a a dimension 1 or 2. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product default dimension of 1 #} +{% set products = craft.products() + .defaultWeight(1) + .all() %} +``` + +```php +// Fetch products of the product default dimension of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultWeight(1) + ->all(); +``` +::: + + +

# defaultWidth

+ +Narrows the query results based on the products’ default variant width dimension IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with a dimension of 1. +| `'not 1'` | not a dimension of 1. +| `[1, 2]` | of a a dimension 1 or 2. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product default dimension of 1 #} +{% set products = craft.products() + .defaultWidth(1) + .all() %} +``` + +```php +// Fetch products of the product default dimension of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultWidth(1) + ->all(); +``` +::: + + +

# expiryDate

+ +Narrows the query results based on the products’ expiry dates. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. +| `'< 2020-05-01'` | that will expire before 2020-05-01 +| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. + + + +::: code +```twig +{# Fetch products expiring this month #} +{% set nextMonth = date('first day of next month')|atom %} + +{% set products = craft.products() + .expiryDate("< #{nextMonth}") + .all() %} +``` + +```php +// Fetch products expiring this month +$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->expiryDate("< {$nextMonth}") + ->all(); +``` +::: + + +

# fixedOrder

+ +Causes the query results to be returned in the order specified by [id](#product-id). + + + + + +::: code +```twig +{# Fetch products in a specific order #} +{% set products = craft.products() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch products in a specific order +$products = \craft\commerce\elements\Product::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +

# hasVariant

+ +Narrows the query results to only products that have certain variants. + +Possible values include: + +| Value | Fetches products… +| - | - +| a [VariantQuery](commerce3:craft\commerce\elements\db\VariantQuery) object | with variants that match the query. + + + + +

# id

+ +Narrows the query results based on the products’ IDs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the product by its ID #} +{% set product = craft.products() + .id(1) + .one() %} +``` + +```php +// Fetch the product by its ID +$product = \craft\commerce\elements\Product::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#product-fixedorder) if you want the results to be returned in a specific order. +::: + + +

# ignorePlaceholders

+ +Causes the query to return matching products as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +

# inReverse

+ +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch products in reverse #} +{% set products = craft.products() + .inReverse() + .all() %} +``` + +```php +// Fetch products in reverse +$products = \craft\commerce\elements\Product::find() + ->inReverse() + ->all(); +``` +::: + + +

# limit

+ +Determines the number of products that should be returned. + + + +::: code +```twig +{# Fetch up to 10 products #} +{% set products = craft.products() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 products +$products = \craft\commerce\elements\Product::find() + ->limit(10) + ->all(); +``` +::: + + +

# offset

+ +Determines how many products should be skipped in the results. + + + +::: code +```twig +{# Fetch all products except for the first 3 #} +{% set products = craft.products() + .offset(3) + .all() %} +``` + +```php +// Fetch all products except for the first 3 +$products = \craft\commerce\elements\Product::find() + ->offset(3) + ->all(); +``` +::: + + +

# orderBy

+ +Determines the order that the products should be returned in. (If empty, defaults to `postDate DESC`.) + + + +::: code +```twig +{# Fetch all products in order of date created #} +{% set products = craft.products() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all products in order of date created +$products = \craft\commerce\elements\Product::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +

# postDate

+ +Narrows the query results based on the products’ post dates. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. +| `'< 2018-05-01'` | that were posted before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch products posted last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set products = craft.products() + .postDate(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch products posted last month +$start = new \DateTime('first day of next month')->format(\DateTime::ATOM); +$end = new \DateTime('first day of this month')->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->postDate(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +

# preferSites

+ +If [unique](#product-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned +for Site B. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique products from Site A, or Site B if they don’t exist in Site A #} +{% set products = craft.products() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique products from Site A, or Site B if they don’t exist in Site A +$products = \craft\commerce\elements\Product::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +

# relatedTo

+ +Narrows the query results to only products that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all products that are related to myCategory #} +{% set products = craft.products() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all products that are related to $myCategory +$products = \craft\commerce\elements\Product::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + + + +Narrows the query results to only products that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all products that match the search query #} +{% set products = craft.products() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all products that match the search query +$products = \craft\commerce\elements\Product::find() + ->search($searchQuery) + ->all(); +``` +::: + + +

# site

+ +Determines which site(s) the products should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](https://docs.craftcms.com/api/v3/craft-models-site.html) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#product-unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch products from the Foo site #} +{% set products = craft.products() + .site('foo') + .all() %} +``` + +```php +// Fetch products from the Foo site +$products = \craft\commerce\elements\Product::find() + ->site('foo') + ->all(); +``` +::: + + +

# siteId

+ +Determines which site(s) the products should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch products from the site with an ID of 1 #} +{% set products = craft.products() + .siteId(1) + .all() %} +``` + +```php +// Fetch products from the site with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->siteId(1) + ->all(); +``` +::: + + +

# siteSettingsId

+ +Narrows the query results based on the products’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the product by its ID in the elements_sites table #} +{% set product = craft.products() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the product by its ID in the elements_sites table +$product = \craft\commerce\elements\Product::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +

# slug

+ +Narrows the query results based on the products’ slugs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | with a slug of `foo`. +| `'foo*'` | with a slug that begins with `foo`. +| `'*foo'` | with a slug that ends with `foo`. +| `'*foo*'` | with a slug that contains `foo`. +| `'not *foo*'` | with a slug that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested product slug from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the product with that slug #} +{% set product = craft.products() + .slug(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested product slug from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the product with that slug +$product = \craft\commerce\elements\Product::find() + ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +

# status

+ +Narrows the query results based on the products’ statuses. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'live'` _(default)_ | that are live. +| `'pending'` | that are pending (enabled with a Post Date in the future). +| `'expired'` | that are expired (enabled with an Expiry Date in the past). +| `'disabled'` | that are disabled. +| `['live', 'pending']` | that are live or pending. + + + +::: code +```twig +{# Fetch disabled products #} +{% set products = craft.products() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled products +$products = \craft\commerce\elements\Product::find() + ->status('disabled') + ->all(); +``` +::: + + +

# title

+ +Narrows the query results based on the products’ titles. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch products with a title that contains "Foo" #} +{% set products = craft.products() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch products with a title that contains "Foo" +$products = \craft\commerce\elements\Product::find() + ->title('*Foo*') + ->all(); +``` +::: + + +

# trashed

+ +Narrows the query results to only products that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed products #} +{% set products = craft.products() + .trashed() + .all() %} +``` + +```php +// Fetch trashed products +$products = \craft\commerce\elements\Product::find() + ->trashed() + ->all(); +``` +::: + + +

# type

+ +Narrows the query results based on the products’ types. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | of a type with a handle of `foo`. +| `'not foo'` | not of a type with a handle of `foo`. +| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. +| an [ProductType](commerce3:craft\commerce\models\ProductType) object | of a type represented by the object. + + + +::: code +```twig +{# Fetch products with a Foo product type #} +{% set products = craft.products() + .type('foo') + .all() %} +``` + +```php +// Fetch products with a Foo product type +$products = \craft\commerce\elements\Product::find() + ->type('foo') + ->all(); +``` +::: + + +

# typeId

+ +Narrows the query results based on the products’ types, per the types’ IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with an ID of 1. +| `'not 1'` | not of a type with an ID of 1. +| `[1, 2]` | of a type with an ID of 1 or 2. +| `['not', 1, 2]` | not of a type with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch products of the product type with an ID of 1 #} +{% set products = craft.products() + .typeId(1) + .all() %} +``` + +```php +// Fetch products of the product type with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->typeId(1) + ->all(); +``` +::: + + +

# uid

+ +Narrows the query results based on the products’ UIDs. + + + + + +::: code +```twig +{# Fetch the product by its UID #} +{% set product = craft.products() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the product by its UID +$product = \craft\commerce\elements\Product::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +

# unique

+ +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique products across all sites #} +{% set products = craft.products() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique products across all sites +$products = \craft\commerce\elements\Product::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +

# uri

+ +Narrows the query results based on the products’ URIs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the product with that URI #} +{% set product = craft.products() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the product with that URI +$product = \craft\commerce\elements\Product::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +

# with

+ +Causes the query to return matching products eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch products eager-loaded with the "Related" field’s relations #} +{% set products = craft.products() + .with(['related']) + .all() %} +``` + +```php +// Fetch products eager-loaded with the "Related" field’s relations +$products = \craft\commerce\elements\Product::find() + ->with(['related']) + ->all(); +``` +::: + + + + + +## Variants + +A variant describes the individual properties of a product as an item that may be purchased. + +Those properties inclue a SKU, price, and dimensions. Even if a product doesn’t appear to have any variants in the control panel, it still uses one *default variant* behind the scenes. + +Let’s compare examples of a single-variant an multi-variant product: a paperback book and a t-shirt. + +A book sold in only one format does not have meaningful variations for the customer to choose, but it would still have a specific SKU, price, weight, and dimensions. A single, implicit default variant needs to exist and that’s what would be added to the cart. + +A t-shirt, on the other hand, would have at least one variant for each available color and size combination. You wouldn’t sell the t-shirt without a specific color and size, so multiple variants would be necessary. If the shirt came in “small” and “large” sizes and “red” or “blue” colors, four unique variants could exist: + +- small, red +- small, blue +- large, red +- large, blue + +### Variant Properties + +Each variant includes the following unique properties: + +| Property | Type | Required? | +| ------------- | ------------------- | -------------- | +| SKU | string | | +| Price | number | | +| Stock | number or unlimited | | +| Allowed Qty | range | | +| Dimensions | number (l × w × h) | | +| Weight | number | | +| Related Sales | relationship (Sale) | | + +Each variant may also have any number of custom fields to allow other distinguishing traits. + +Commerce does not automatically create every possible unique variant for you—that’s up to the store manager. + +### Default Variant + +Every product has a default variant. Whenever a product is created, a default variant will be created as well. + +If a product type has multiple variants enabled, the author can choose which one should be used by default. Products that do not have multiple variants still have a default variant, but the author can’t add additional variants. + +For a single-variant product, variant details are shown in a unified view with custom product fields: + +![Single-Variant Product](./images/single-variant.png) + +When a product supports multiple variants, the default variant will be identified in a **Variants** field where more variants can be added: + +![Multi-Variant Product](./images/multi-variant.png) + +### Variant Stock + +Variants can have unlimited stock or a specific quantity. + +A finite stock amount will automatically be reduced whenever someone completes an order, until the stock amount reaches zero. At that point the variant’s “Available for purchase” setting won’t be changed, but zero-stock variants cannot be added to a cart. + +For returns or refunds that aren’t ultimately delivered to the customer, you’ll need to either manually update product stock or use [the `orderStatusChange` event](extend/events.md#orderstatuschange) to automate further stock adjustments. + +## Querying Variants + +You can fetch variants using **variant queries**. + +::: code +```twig +{# Create a new variant query #} +{% set myVariantQuery = craft.variants() %} +``` +```php +// Create a new variant query +$myVariantQuery = \craft\commerce\elements\Variant::find(); +``` +```graphql +# Create a new variant query +{ + variants { + # ... + } +} +``` +::: + +Once you’ve created a variant query, you can set [parameters](#variant-query-parameters) on it to narrow down the results, and then [execute it](https://craftcms.com/docs/3.x/element-queries.html#executing-element-queries) by calling `.all()`. An array of [Variant](commerce3:craft\commerce\elements\Variant) objects will be returned. + +You can also fetch only the number of items a query might return, which is better for performance when you don’t need the variant data. + +::: code +```twig +{# Count all enabled variants #} +{% set myVariantCount = craft.variants() + .status('enabled') + .count() %} +``` +```php +use craft\commerce\elements\Variant; + +// Count all enabled variants +$myVariantCount = Variant::find() + ->status(Variant::STATUS_ENABLED) + ->count(); +``` +```graphql +# Count all enabled variants +{ + variantCount(status: "enabled") +} +``` +::: + +::: tip +See [Element Queries](https://craftcms.com/docs/3.x/element-queries.html) in the Craft docs to learn about how element queries work. +::: + +### Example + +We can display a specific variant by its ID in Twig by doing the following: + +1. Create a variant query with `craft.variants()`. +2. Set the [`id`](#id) parameter on it. +3. Fetch the variant with `.one()`. +4. Output information about the variant as HTML. + +```twig +{# Get the requested variant ID from the query string #} +{% set variantId = craft.app.request.getQueryParam('id') %} + +{# Create a variant query with the 'id' parameter #} +{% set myVariantQuery = craft.variants() + .id(variantId) %} + +{# Fetch the variant #} +{% set variant = myVariantQuery.one() %} + +{# Make sure it exists #} +{% if not variant %} + {% exit 404 %} +{% endif %} + +{# Display the variant #} +

{{ variant.title }}

+ +``` + +Fetching the equivalent with GraphQL could look like this: + +```graphql +# Fetch variant having ID = 46 +{ + variants(id: 46) { + title + } +} +``` + +## Variant Query Parameters + +Variant queries support the following parameters: + + + + + + + +| Param | Description +| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#variant-afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#variant-andrelatedto) | Narrows the query results to only variants that are related to certain other elements. +| [anyStatus](#variant-anystatus) | Removes element filters based on their statuses. +| [asArray](#variant-asarray) | Causes the query to return matching variants as arrays of data, rather than [Variant](commerce3:craft\commerce\elements\Variant) objects. +| [cache](#variant-cache) | Enables query cache for this Query. +| [clearCachedResult](#variant-clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). +| [dateCreated](#variant-datecreated) | Narrows the query results based on the variants’ creation dates. +| [dateUpdated](#variant-dateupdated) | Narrows the query results based on the variants’ last-updated dates. +| [fixedOrder](#variant-fixedorder) | Causes the query results to be returned in the order specified by [id](#variant-id). +| [hasProduct](#variant-hasproduct) | Narrows the query results to only variants for certain products. +| [hasSales](#variant-hassales) | Narrows the query results to only variants that are on sale. +| [hasStock](#variant-hasstock) | Narrows the query results to only variants that have stock. +| [hasUnlimitedStock](#variant-hasunlimitedstock) | Narrows the query results to only variants that have been set to unlimited stock. +| [height](#variant-height) | Narrows the query results based on the variants’ height dimension. +| [id](#variant-id) | Narrows the query results based on the variants’ IDs. +| [ignorePlaceholders](#variant-ignoreplaceholders) | Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#variant-inreverse) | Causes the query results to be returned in reverse order. +| [isDefault](#variant-isdefault) | Narrows the query results to only default variants. +| [length](#variant-length) | Narrows the query results based on the variants’ length dimension. +| [limit](#variant-limit) | Determines the number of variants that should be returned. +| [maxQty](#variant-maxqty) | Narrows the query results based on the variants’ max quantity. +| [minQty](#variant-minqty) | Narrows the query results based on the variants’ min quantity. +| [offset](#variant-offset) | Determines how many variants should be skipped in the results. +| [orderBy](#variant-orderby) | Determines the order that the variants should be returned in. (If empty, defaults to `sortOrder ASC`.) +| [preferSites](#variant-prefersites) | If [unique](#variant-unique) is set, this determines which site should be selected when querying multi-site elements. +| [price](#variant-price) | Narrows the query results based on the variants’ price. +| [product](#variant-product) | Narrows the query results based on the variants’ product. +| [productId](#variant-productid) | Narrows the query results based on the variants’ products’ IDs. +| [relatedTo](#variant-relatedto) | Narrows the query results to only variants that are related to certain other elements. +| [search](#variant-search) | Narrows the query results to only variants that match a search query. +| [site](#variant-site) | Determines which site(s) the variants should be queried in. +| [siteId](#variant-siteid) | Determines which site(s) the variants should be queried in, per the site’s ID. +| [siteSettingsId](#variant-sitesettingsid) | Narrows the query results based on the variants’ IDs in the `elements_sites` table. +| [sku](#variant-sku) | Narrows the query results based on the variants’ SKUs. +| [status](#variant-status) | Narrows the query results based on the variants’ statuses. +| [stock](#variant-stock) | Narrows the query results based on the variants’ stock. +| [title](#variant-title) | Narrows the query results based on the variants’ titles. +| [trashed](#variant-trashed) | Narrows the query results to only variants that have been soft-deleted. +| [typeId](#variant-typeid) | Narrows the query results based on the variants’ product types, per their IDs. +| [uid](#variant-uid) | Narrows the query results based on the variants’ UIDs. +| [unique](#variant-unique) | Determines whether only elements with unique IDs should be returned by the query. +| [weight](#variant-weight) | Narrows the query results based on the variants’ weight dimension. +| [width](#variant-width) | Narrows the query results based on the variants’ width dimension. +| [with](#variant-with) | Causes the query to return matching variants eager-loaded with related elements. + + + + + +

# afterPopulate

+ +Performs any post-population processing on elements. + + + + + + + + + + +

# andRelatedTo

+ +Narrows the query results to only variants that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all variants that are related to myCategoryA and myCategoryB #} +{% set variants = craft.variants() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all variants that are related to $myCategoryA and $myCategoryB +$variants = \craft\commerce\elements\Variant::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +

# anyStatus

+ +Removes element filters based on their statuses. + + + + + +::: code +```twig +{# Fetch all variants, regardless of status #} +{% set variants = craft.variants() + .anyStatus() + .all() %} +``` + +```php +// Fetch all variants, regardless of status +$variants = \craft\commerce\elements\Variant::find() + ->anyStatus() + ->all(); +``` +::: + + +

# asArray

+ +Causes the query to return matching variants as arrays of data, rather than [Variant](commerce3:craft\commerce\elements\Variant) objects. + + + + + +::: code +```twig +{# Fetch variants as arrays #} +{% set variants = craft.variants() + .asArray() + .all() %} +``` + +```php +// Fetch variants as arrays +$variants = \craft\commerce\elements\Variant::find() + ->asArray() + ->all(); +``` +::: + + +

# cache

+ +Enables query cache for this Query. + + + + + + + + + + +

# clearCachedResult

+ +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +

# dateCreated

+ +Narrows the query results based on the variants’ creation dates. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch variants created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set variants = craft.variants() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch variants created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$variants = \craft\commerce\elements\Variant::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +

# dateUpdated

+ +Narrows the query results based on the variants’ last-updated dates. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch variants updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set variants = craft.variants() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch variants updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$variants = \craft\commerce\elements\Variant::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +

# fixedOrder

+ +Causes the query results to be returned in the order specified by [id](#variant-id). + + + + + +::: code +```twig +{# Fetch variants in a specific order #} +{% set variants = craft.variants() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch variants in a specific order +$variants = \craft\commerce\elements\Variant::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +

# hasProduct

+ +Narrows the query results to only variants for certain products. + +Possible values include: + +| Value | Fetches variants… +| - | - +| a [ProductQuery](commerce3:craft\commerce\elements\db\ProductQuery) object | for products that match the query. + + + + +

# hasSales

+ +Narrows the query results to only variants that are on sale. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `true` | on sale +| `false` | not on sale + + + + +

# hasStock

+ +Narrows the query results to only variants that have stock. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `true` | with stock. +| `false` | with no stock. + + + + +

# hasUnlimitedStock

+ +Narrows the query results to only variants that have been set to unlimited stock. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `true` | with unlimited stock checked. +| `false` | with unlimited stock not checked. + + + + +

# height

+ +Narrows the query results based on the variants’ height dimension. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a height of 100. +| `'>= 100'` | with a height of at least 100. +| `'< 100'` | with a height of less than 100. + + + + +

# id

+ +Narrows the query results based on the variants’ IDs. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the variant by its ID #} +{% set variant = craft.variants() + .id(1) + .one() %} +``` + +```php +// Fetch the variant by its ID +$variant = \craft\commerce\elements\Variant::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#variant-fixedorder) if you want the results to be returned in a specific order. +::: + + +

# ignorePlaceholders

+ +Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +

# inReverse

+ +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch variants in reverse #} +{% set variants = craft.variants() + .inReverse() + .all() %} +``` + +```php +// Fetch variants in reverse +$variants = \craft\commerce\elements\Variant::find() + ->inReverse() + ->all(); +``` +::: + + +

# isDefault

+ +Narrows the query results to only default variants. + + + +::: code +```twig +{# Fetch default variants #} +{% set variants = craft.variants() + .isDefault() + .all() %} +``` + +```php +// Fetch default variants +$variants = \craft\commerce\elements\Variant::find() + ->isDefault() + ->all(); +``` +::: + + +

# length

+ +Narrows the query results based on the variants’ length dimension. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a length of 100. +| `'>= 100'` | with a length of at least 100. +| `'< 100'` | with a length of less than 100. + + + + +

# limit

+ +Determines the number of variants that should be returned. + + + +::: code +```twig +{# Fetch up to 10 variants #} +{% set variants = craft.variants() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 variants +$variants = \craft\commerce\elements\Variant::find() + ->limit(10) + ->all(); +``` +::: + + +

# maxQty

+ +Narrows the query results based on the variants’ max quantity. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a maxQty of 100. +| `'>= 100'` | with a maxQty of at least 100. +| `'< 100'` | with a maxQty of less than 100. + + + + +

# minQty

+ +Narrows the query results based on the variants’ min quantity. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a minQty of 100. +| `'>= 100'` | with a minQty of at least 100. +| `'< 100'` | with a minQty of less than 100. + + + + +

# offset

+ +Determines how many variants should be skipped in the results. + + + +::: code +```twig +{# Fetch all variants except for the first 3 #} +{% set variants = craft.variants() + .offset(3) + .all() %} +``` + +```php +// Fetch all variants except for the first 3 +$variants = \craft\commerce\elements\Variant::find() + ->offset(3) + ->all(); +``` +::: + + +

# orderBy

+ +Determines the order that the variants should be returned in. (If empty, defaults to `sortOrder ASC`.) + + + +::: code +```twig +{# Fetch all variants in order of date created #} +{% set variants = craft.variants() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all variants in order of date created +$variants = \craft\commerce\elements\Variant::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +

# preferSites

+ +If [unique](#variant-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned +for Site B. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique variants from Site A, or Site B if they don’t exist in Site A #} +{% set variants = craft.variants() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique variants from Site A, or Site B if they don’t exist in Site A +$variants = \craft\commerce\elements\Variant::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +

# price

+ +Narrows the query results based on the variants’ price. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a price of 100. +| `'>= 100'` | with a price of at least 100. +| `'< 100'` | with a price of less than 100. + + + + +

# product

+ +Narrows the query results based on the variants’ product. + +Possible values include: + +| Value | Fetches variants… +| - | - +| a [Product](commerce3:craft\commerce\elements\Product) object | for a product represented by the object. + + + + +

# productId

+ +Narrows the query results based on the variants’ products’ IDs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | for a product with an ID of 1. +| `[1, 2]` | for product with an ID of 1 or 2. +| `['not', 1, 2]` | for product not with an ID of 1 or 2. + + + + +

# relatedTo

+ +Narrows the query results to only variants that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all variants that are related to myCategory #} +{% set variants = craft.variants() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all variants that are related to $myCategory +$variants = \craft\commerce\elements\Variant::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + + + +Narrows the query results to only variants that match a search query. + + + +See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all variants that match the search query #} +{% set variants = craft.variants() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all variants that match the search query +$variants = \craft\commerce\elements\Variant::find() + ->search($searchQuery) + ->all(); +``` +::: + + +

# site

+ +Determines which site(s) the variants should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](https://docs.craftcms.com/api/v3/craft-models-site.html) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#variant-unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch variants from the Foo site #} +{% set variants = craft.variants() + .site('foo') + .all() %} +``` + +```php +// Fetch variants from the Foo site +$variants = \craft\commerce\elements\Variant::find() + ->site('foo') + ->all(); +``` +::: + + +

# siteId

+ +Determines which site(s) the variants should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch variants from the site with an ID of 1 #} +{% set variants = craft.variants() + .siteId(1) + .all() %} +``` + +```php +// Fetch variants from the site with an ID of 1 +$variants = \craft\commerce\elements\Variant::find() + ->siteId(1) + ->all(); +``` +::: + + +

# siteSettingsId

+ +Narrows the query results based on the variants’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the variant by its ID in the elements_sites table #} +{% set variant = craft.variants() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the variant by its ID in the elements_sites table +$variant = \craft\commerce\elements\Variant::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +

# sku

+ +Narrows the query results based on the variants’ SKUs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'foo'` | with a SKU of `foo`. +| `'foo*'` | with a SKU that begins with `foo`. +| `'*foo'` | with a SKU that ends with `foo`. +| `'*foo*'` | with a SKU that contains `foo`. +| `'not *foo*'` | with a SKU that doesn’t contain `foo`. +| `['*foo*', '*bar*'` | with a SKU that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a SKU that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested variant SKU from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the variant with that slug #} +{% set variant = craft.variants() + .sku(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested variant SKU from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the variant with that slug +$variant = \craft\commerce\elements\Variant::find() + ->sku(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +

# status

+ +Narrows the query results based on the variants’ statuses. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'enabled'` _(default)_ | that are enabled. +| `'disabled'` | that are disabled. +| `['not', 'disabled']` | that are not disabled. + + + +::: code +```twig +{# Fetch disabled variants #} +{% set variants = craft.variants() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled variants +$variants = \craft\commerce\elements\Variant::find() + ->status('disabled') + ->all(); +``` +::: + + +

# stock

+ +Narrows the query results based on the variants’ stock. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `0` | with no stock. +| `'>= 5'` | with a stock of at least 5. +| `'< 10'` | with a stock of less than 10. + + + + +

# title

+ +Narrows the query results based on the variants’ titles. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch variants with a title that contains "Foo" #} +{% set variants = craft.variants() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch variants with a title that contains "Foo" +$variants = \craft\commerce\elements\Variant::find() + ->title('*Foo*') + ->all(); +``` +::: + + +

# trashed

+ +Narrows the query results to only variants that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed variants #} +{% set variants = craft.variants() + .trashed() + .all() %} +``` + +```php +// Fetch trashed variants +$variants = \craft\commerce\elements\Variant::find() + ->trashed() + ->all(); +``` +::: + + +

# typeId

+ +Narrows the query results based on the variants’ product types, per their IDs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | for a product of a type with an ID of 1. +| `[1, 2]` | for product of a type with an ID of 1 or 2. +| `['not', 1, 2]` | for product of a type not with an ID of 1 or 2. + + + + +

# uid

+ +Narrows the query results based on the variants’ UIDs. + + + + + +::: code +```twig +{# Fetch the variant by its UID #} +{% set variant = craft.variants() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the variant by its UID +$variant = \craft\commerce\elements\Variant::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +

# unique

+ +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique variants across all sites #} +{% set variants = craft.variants() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique variants across all sites +$variants = \craft\commerce\elements\Variant::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +

# weight

+ +Narrows the query results based on the variants’ weight dimension. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a weight of 100. +| `'>= 100'` | with a weight of at least 100. +| `'< 100'` | with a weight of less than 100. + + + + +

# width

+ +Narrows the query results based on the variants’ width dimension. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a width of 100. +| `'>= 100'` | with a width of at least 100. +| `'< 100'` | with a width of less than 100. + + + + +

# with

+ +Causes the query to return matching variants eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch variants eager-loaded with the "Related" field’s relations #} +{% set variants = craft.variants() + .with(['related']) + .all() %} +``` + +```php +// Fetch variants eager-loaded with the "Related" field’s relations +$variants = \craft\commerce\elements\Variant::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/commerce/3.x/dev/element-queries/subscription-queries.md b/docs/.artifacts/commerce/3.x/subscriptions.md similarity index 83% rename from docs/commerce/3.x/dev/element-queries/subscription-queries.md rename to docs/.artifacts/commerce/3.x/subscriptions.md index f47e99982..96635f6ac 100644 --- a/docs/commerce/3.x/dev/element-queries/subscription-queries.md +++ b/docs/.artifacts/commerce/3.x/subscriptions.md @@ -1,65 +1,19 @@ -# Subscription Queries + -You can fetch subscriptions in your templates or PHP code using **subscription queries**. - -::: code -```twig -{# Create a new subscription query #} -{% set mySubscriptionQuery = craft.subscriptions() %} -``` -```php -// Create a new subscription query -$mySubscriptionQuery = \craft\commerce\elements\Subscription::find(); -``` -::: - -Once you’ve created a subscription query, you can set [parameters](#parameters) on it to narrow down the results, and then [execute it](https://craftcms.com/docs/3.x/element-queries.html#executing-element-queries) by calling `.all()`. An array of [Subscription](commerce3:craft\commerce\elements\Subscription) objects will be returned. - -::: tip -See [Element Queries](https://craftcms.com/docs/3.x/element-queries.html) in the Craft docs to learn about how element queries work. -::: - -## Example - -We can display all of the current user’s subscriptions by doing the following: - -1. Create a subscription query with `craft.subscriptions()`. -2. Set the [user](#user) parameter on it. -3. Fetch the subscriptions with `.all()`. -4. Loop through the subscriptions using a [for](https://twig.symfony.com/doc/2.x/tags/for.html) tag to output their HTML. - -```twig -{# Make sure someone is logged in #} -{% requireLogin %} - -{# Create a subscription query with the 'user' parameter #} -{% set mySubscriptionQuery = craft.subscriptions() - .user(currentUser) %} - -{# Fetch the subscriptions #} -{% set subscriptions = mySubscriptionQuery.all() %} - -{# Display the subscriptions #} -{% for subscription in subscriptions %} - -{% endfor %} -``` + -## Parameters -Subscription queries support the following parameters: - + | Param | Description | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [anyStatus](#anystatus) | Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only subscriptions that are related to certain other elements. +| [anyStatus](#anystatus) | Removes element filters based on their statuses. | [asArray](#asarray) | Causes the query to return matching subscriptions as arrays of data, rather than [Subscription](commerce3:craft\commerce\elements\Subscription) objects. -| [clearCachedResult](#clearcachedresult) | Clears the cached result. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). | [dateCanceled](#datecanceled) | Narrows the query results based on the subscriptions’ cancellation date. | [dateCreated](#datecreated) | Narrows the query results based on the subscriptions’ creation dates. | [dateExpired](#dateexpired) | Narrows the query results based on the subscriptions’ expiration date. @@ -86,6 +40,7 @@ Subscription queries support the following parameters: | [reference](#reference) | Narrows the query results based on the reference. | [relatedTo](#relatedto) | Narrows the query results to only subscriptions that are related to certain other elements. | [search](#search) | Narrows the query results to only subscriptions that match a search query. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the subscriptions’ IDs in the `elements_sites` table. | [status](#status) | Narrows the query results based on the subscriptions’ statuses. | [trashed](#trashed) | Narrows the query results to only subscriptions that have been soft-deleted. | [trialDays](#trialdays) | Narrows the query results based on the number of trial days. @@ -94,9 +49,55 @@ Subscription queries support the following parameters: | [userId](#userid) | Narrows the query results based on the subscriptions’ user accounts’ IDs. | [with](#with) | Causes the query to return matching subscriptions eager-loaded with related elements. -### `anyStatus` -Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only subscriptions that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all subscriptions that are related to myCategoryA and myCategoryB #} +{% set subscriptions = craft.subscriptions() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all subscriptions that are related to $myCategoryA and $myCategoryB +$subscriptions = \craft\commerce\elements\Subscription::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `anyStatus` + +Removes element filters based on their statuses. @@ -106,8 +107,8 @@ Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.co ```twig {# Fetch all subscriptions, regardless of status #} {% set subscriptions = craft.subscriptions() - .anyStatus() - .all() %} + .anyStatus() + .all() %} ``` ```php @@ -119,7 +120,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `asArray` +#### `asArray` Causes the query to return matching subscriptions as arrays of data, rather than [Subscription](commerce3:craft\commerce\elements\Subscription) objects. @@ -131,8 +132,8 @@ Causes the query to return matching subscriptions as arrays of data, rather than ```twig {# Fetch subscriptions as arrays #} {% set subscriptions = craft.subscriptions() - .asArray() - .all() %} + .asArray() + .all() %} ``` ```php @@ -144,16 +145,29 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `clearCachedResult` +#### `cache` + +Enables query cache for this Query. -Clears the cached result. -### `dateCanceled` + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). + + + + + + +#### `dateCanceled` Narrows the query results based on the subscriptions’ cancellation date. @@ -173,8 +187,8 @@ Possible values include: {% set aWeekAgo = date('7 days ago')|atom %} {% set subscriptions = craft.subscriptions() - .dateCanceled(">= #{aWeekAgo}") - .all() %} + .dateCanceled(">= #{aWeekAgo}") + .all() %} ``` ```php @@ -188,7 +202,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `dateCreated` +#### `dateCreated` Narrows the query results based on the subscriptions’ creation dates. @@ -211,8 +225,8 @@ Possible values include: {% set end = date('first day of this month')|atom %} {% set subscriptions = craft.subscriptions() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} ``` ```php @@ -227,7 +241,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `dateExpired` +#### `dateExpired` Narrows the query results based on the subscriptions’ expiration date. @@ -247,8 +261,8 @@ Possible values include: {% set aWeekAgo = date('7 days ago')|atom %} {% set subscriptions = craft.subscriptions() - .dateExpired(">= #{aWeekAgo}") - .all() %} + .dateExpired(">= #{aWeekAgo}") + .all() %} ``` ```php @@ -262,7 +276,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `dateSuspended` +#### `dateSuspended` Narrows the query results based on the subscriptions’ suspension date. @@ -281,8 +295,8 @@ Possible values include: {% set aWeekAgo = date('7 days ago')|atom %} {% set subscriptions = craft.subscriptions() - .dateSuspended(">= #{aWeekAgo}") - .all() %} + .dateSuspended(">= #{aWeekAgo}") + .all() %} ``` ```php @@ -296,7 +310,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `dateUpdated` +#### `dateUpdated` Narrows the query results based on the subscriptions’ last-updated dates. @@ -318,8 +332,8 @@ Possible values include: {% set lastWeek = date('1 week ago')|atom %} {% set subscriptions = craft.subscriptions() - .dateUpdated(">= #{lastWeek}") - .all() %} + .dateUpdated(">= #{lastWeek}") + .all() %} ``` ```php @@ -333,7 +347,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `fixedOrder` +#### `fixedOrder` Causes the query results to be returned in the order specified by [id](#id). @@ -345,9 +359,9 @@ Causes the query results to be returned in the order specified by [id](#id). ```twig {# Fetch subscriptions in a specific order #} {% set subscriptions = craft.subscriptions() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} ``` ```php @@ -360,7 +374,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `gatewayId` +#### `gatewayId` Narrows the query results based on the gateway, per its ID. @@ -376,7 +390,7 @@ Possible values include: -### `hasStarted` +#### `hasStarted` Narrows the query results to only subscriptions that have started. @@ -386,8 +400,8 @@ Narrows the query results to only subscriptions that have started. ```twig {# Fetch started subscriptions #} {% set subscriptions = craft.subscriptions() - .hasStarted() - .all() %} + .hasStarted() + .all() %} ``` ```php @@ -399,7 +413,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `id` +#### `id` Narrows the query results based on the subscriptions’ IDs. @@ -420,8 +434,8 @@ Possible values include: ```twig {# Fetch the subscription by its ID #} {% set subscription = craft.subscriptions() - .id(1) - .one() %} + .id(1) + .one() %} ``` ```php @@ -439,7 +453,7 @@ This can be combined with [fixedOrder](#fixedorder) if you want the results to b ::: -### `ignorePlaceholders` +#### `ignorePlaceholders` Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). @@ -453,7 +467,7 @@ elements that were set by [craft\services\Elements::setPlaceholderElement()](htt -### `inReverse` +#### `inReverse` Causes the query results to be returned in reverse order. @@ -465,8 +479,8 @@ Causes the query results to be returned in reverse order. ```twig {# Fetch subscriptions in reverse #} {% set subscriptions = craft.subscriptions() - .inReverse() - .all() %} + .inReverse() + .all() %} ``` ```php @@ -478,7 +492,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `isCanceled` +#### `isCanceled` Narrows the query results to only subscriptions that are canceled. @@ -488,8 +502,8 @@ Narrows the query results to only subscriptions that are canceled. ```twig {# Fetch canceled subscriptions #} {% set subscriptions = craft.subscriptions() - .isCanceled() - .all() %} + .isCanceled() + .all() %} ``` ```php @@ -501,7 +515,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `isExpired` +#### `isExpired` Narrows the query results to only subscriptions that have expired. @@ -511,8 +525,8 @@ Narrows the query results to only subscriptions that have expired. ```twig {# Fetch expired subscriptions #} {% set subscriptions = craft.subscriptions() - .isExpired() - .all() %} + .isExpired() + .all() %} ``` ```php @@ -524,7 +538,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `isSuspended` +#### `isSuspended` Narrows the query results to only subscriptions that are suspended. @@ -534,8 +548,8 @@ Narrows the query results to only subscriptions that are suspended. ```twig {# Fetch suspended subscriptions #} {% set subscriptions = craft.subscriptions() - .isSuspended() - .all() %} + .isSuspended() + .all() %} ``` ```php @@ -547,7 +561,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `limit` +#### `limit` Determines the number of subscriptions that should be returned. @@ -557,8 +571,8 @@ Determines the number of subscriptions that should be returned. ```twig {# Fetch up to 10 subscriptions #} {% set subscriptions = craft.subscriptions() - .limit(10) - .all() %} + .limit(10) + .all() %} ``` ```php @@ -570,7 +584,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `nextPaymentDate` +#### `nextPaymentDate` Narrows the query results based on the subscriptions’ next payment dates. @@ -590,8 +604,8 @@ Possible values include: {% set aWeekFromNow = date('+7 days')|atom %} {% set subscriptions = craft.subscriptions() - .nextPaymentDate("< #{aWeekFromNow}") - .all() %} + .nextPaymentDate("< #{aWeekFromNow}") + .all() %} ``` ```php @@ -605,7 +619,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `offset` +#### `offset` Determines how many subscriptions should be skipped in the results. @@ -615,8 +629,8 @@ Determines how many subscriptions should be skipped in the results. ```twig {# Fetch all subscriptions except for the first 3 #} {% set subscriptions = craft.subscriptions() - .offset(3) - .all() %} + .offset(3) + .all() %} ``` ```php @@ -628,7 +642,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `onTrial` +#### `onTrial` Narrows the query results to only subscriptions that are on trial. @@ -638,8 +652,8 @@ Narrows the query results to only subscriptions that are on trial. ```twig {# Fetch trialed subscriptions #} {% set subscriptions = craft.subscriptions() - .onTrial() - .all() %} + .onTrial() + .all() %} ``` ```php @@ -651,7 +665,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `orderBy` +#### `orderBy` Determines the order that the subscriptions should be returned in. (If empty, defaults to `dateCreated DESC`.) @@ -661,8 +675,8 @@ Determines the order that the subscriptions should be returned in. (If empty, de ```twig {# Fetch all subscriptions in order of date created #} {% set subscriptions = craft.subscriptions() - .orderBy('dateCreated ASC') - .all() %} + .orderBy('dateCreated ASC') + .all() %} ``` ```php @@ -674,7 +688,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `orderId` +#### `orderId` Narrows the query results based on the order, per its ID. @@ -690,7 +704,7 @@ Possible values include: -### `plan` +#### `plan` Narrows the query results based on the subscription plan. @@ -708,8 +722,8 @@ Possible values include: ```twig {# Fetch Supporter plan subscriptions #} {% set subscriptions = craft.subscriptions() - .plan('supporter') - .all() %} + .plan('supporter') + .all() %} ``` ```php @@ -721,7 +735,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `planId` +#### `planId` Narrows the query results based on the subscription plans’ IDs. @@ -736,7 +750,7 @@ Possible values include: -### `preferSites` +#### `preferSites` If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. @@ -754,10 +768,10 @@ If this isn’t set, then preference goes to the current site. ```twig {# Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A #} {% set subscriptions = craft.subscriptions() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} ``` ```php @@ -771,7 +785,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `reference` +#### `reference` Narrows the query results based on the reference. @@ -780,7 +794,7 @@ Narrows the query results based on the reference. -### `relatedTo` +#### `relatedTo` Narrows the query results to only subscriptions that are related to certain other elements. @@ -794,8 +808,8 @@ See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explana ```twig {# Fetch all subscriptions that are related to myCategory #} {% set subscriptions = craft.subscriptions() - .relatedTo(myCategory) - .all() %} + .relatedTo(myCategory) + .all() %} ``` ```php @@ -807,7 +821,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `search` +#### `search` Narrows the query results to only subscriptions that match a search query. @@ -824,8 +838,8 @@ See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explana {# Fetch all subscriptions that match the search query #} {% set subscriptions = craft.subscriptions() - .search(searchQuery) - .all() %} + .search(searchQuery) + .all() %} ``` ```php @@ -840,7 +854,41 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `status` +#### `siteSettingsId` + +Narrows the query results based on the subscriptions’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the subscription by its ID in the elements_sites table #} +{% set subscription = craft.subscriptions() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the subscription by its ID in the elements_sites table +$subscription = \craft\commerce\elements\Subscription::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `status` Narrows the query results based on the subscriptions’ statuses. @@ -857,8 +905,8 @@ Possible values include: ```twig {# Fetch expired subscriptions #} {% set subscriptions = craft.subscriptions() - .status('expired') - .all() %} + .status('expired') + .all() %} ``` ```php @@ -870,7 +918,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `trashed` +#### `trashed` Narrows the query results to only subscriptions that have been soft-deleted. @@ -882,8 +930,8 @@ Narrows the query results to only subscriptions that have been soft-deleted. ```twig {# Fetch trashed subscriptions #} {% set subscriptions = craft.subscriptions() - .trashed() - .all() %} + .trashed() + .all() %} ``` ```php @@ -895,7 +943,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `trialDays` +#### `trialDays` Narrows the query results based on the number of trial days. @@ -904,7 +952,7 @@ Narrows the query results based on the number of trial days. -### `uid` +#### `uid` Narrows the query results based on the subscriptions’ UIDs. @@ -916,8 +964,8 @@ Narrows the query results based on the subscriptions’ UIDs. ```twig {# Fetch the subscription by its UID #} {% set subscription = craft.subscriptions() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} ``` ```php @@ -929,7 +977,7 @@ $subscription = \craft\commerce\elements\Subscription::find() ::: -### `user` +#### `user` Narrows the query results based on the subscriptions’ user accounts. @@ -947,8 +995,8 @@ Possible values include: ```twig {# Fetch the current user's subscriptions #} {% set subscriptions = craft.subscriptions() - .user(currentUser) - .all() %} + .user(currentUser) + .all() %} ``` ```php @@ -961,7 +1009,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `userId` +#### `userId` Narrows the query results based on the subscriptions’ user accounts’ IDs. @@ -979,8 +1027,8 @@ Possible values include: ```twig {# Fetch the current user's subscriptions #} {% set subscriptions = craft.subscriptions() - .userId(currentUser.id) - .all() %} + .userId(currentUser.id) + .all() %} ``` ```php @@ -993,7 +1041,7 @@ $subscriptions = \craft\commerce\elements\Subscription::find() ::: -### `with` +#### `with` Causes the query to return matching subscriptions eager-loaded with related elements. @@ -1007,8 +1055,8 @@ See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-ele ```twig {# Fetch subscriptions eager-loaded with the "Related" field’s relations #} {% set subscriptions = craft.subscriptions() - .with(['related']) - .all() %} + .with(['related']) + .all() %} ``` ```php diff --git a/docs/.artifacts/commerce/4.x/config.md b/docs/.artifacts/commerce/4.x/config.md new file mode 100644 index 000000000..3f8318290 --- /dev/null +++ b/docs/.artifacts/commerce/4.x/config.md @@ -0,0 +1,810 @@ + + + + +## System + +### `defaultView` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'commerce/orders'` + +Defined by +: [Settings::$defaultView](commerce4:craft\commerce\models\Settings::$defaultView) + +Since +: 2.2 + +
+ +Commerce’s default control panel view. (Defaults to order index.) + + + +### `emailSenderAddress` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [Settings::$emailSenderAddress](commerce4:craft\commerce\models\Settings::$emailSenderAddress) + +
+ +Default email address Commerce system messages should be sent from. + +If `null` (default), Craft’s [MailSettings::$fromEmail](craft4:craft\models\MailSettings::$fromEmail) will be used. + + + +### `emailSenderAddressPlaceholder` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [Settings::$emailSenderAddressPlaceholder](commerce4:craft\commerce\models\Settings::$emailSenderAddressPlaceholder) + +
+ +Placeholder value displayed for the sender address control panel settings field. + +If `null` (default), Craft’s [MailSettings::$fromEmail](craft4:craft\models\MailSettings::$fromEmail) will be used. + + + +### `emailSenderName` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [Settings::$emailSenderName](commerce4:craft\commerce\models\Settings::$emailSenderName) + +
+ +Default from name used for Commerce system emails. + +If `null` (default), Craft’s [MailSettings::$fromName](craft4:craft\models\MailSettings::$fromName) will be used. + + + +### `emailSenderNamePlaceholder` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [Settings::$emailSenderNamePlaceholder](commerce4:craft\commerce\models\Settings::$emailSenderNamePlaceholder) + +
+ +Placeholder value displayed for the sender name control panel settings field. + +If `null` (default), Craft’s [MailSettings::$fromName](craft4:craft\models\MailSettings::$fromName) will be used. + + + +### `showEditUserCommerceTab` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [Settings::$showEditUserCommerceTab](commerce4:craft\commerce\models\Settings::$showEditUserCommerceTab) + +Since +: 4.0 + +
+ +Whether the [Commerce Tab](customers.md#user-customer-info-tab) should be shown when viewing users in the control panel. + + + +## Cart + +### `activeCartDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `3600` (1 hour) + +Defined by +: [Settings::$activeCartDuration](commerce4:craft\commerce\models\Settings::$activeCartDuration) + +Since +: 2.2 + +
+ +How long a cart should go without being updated before it’s considered inactive. + +See [craft\helpers\ConfigHelper::durationInSeconds()](craft4:craft\helpers\ConfigHelper::durationInSeconds()) for a list of supported value types. + + + +### `allowCheckoutWithoutPayment` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$allowCheckoutWithoutPayment](commerce4:craft\commerce\models\Settings::$allowCheckoutWithoutPayment) + +Since +: 3.3 + +
+ +Whether carts are can be marked as completed without a payment. + + + +### `allowEmptyCartOnCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$allowEmptyCartOnCheckout](commerce4:craft\commerce\models\Settings::$allowEmptyCartOnCheckout) + +Since +: 2.2 + +
+ +Whether carts are allowed to be empty on checkout. + + + +### `autoSetCartShippingMethodOption` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$autoSetCartShippingMethodOption](commerce4:craft\commerce\models\Settings::$autoSetCartShippingMethodOption) + +
+ +Whether the first available shipping method option should be set automatically on carts. + + + +### `autoSetNewCartAddresses` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [Settings::$autoSetNewCartAddresses](commerce4:craft\commerce\models\Settings::$autoSetNewCartAddresses) + +
+ +Whether the user’s primary shipping and billing addresses should be set automatically on new carts. + + + +### `autoSetPaymentSource` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$autoSetPaymentSource](commerce4:craft\commerce\models\Settings::$autoSetPaymentSource) + +Since +: 4.2 + +
+ +Whether the user’s primary payment source should be set automatically on new carts. + + + +### `cartVariable` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'cart'` + +Defined by +: [Settings::$cartVariable](commerce4:craft\commerce\models\Settings::$cartVariable) + +
+ +Key to be used when returning cart information in a response. + + + +### `loadCartRedirectUrl` + +
+ +Allowed types +: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [Settings::$loadCartRedirectUrl](commerce4:craft\commerce\models\Settings::$loadCartRedirectUrl) + +Since +: 3.1 + +
+ +Default URL to be loaded after using the [load cart controller action](orders-carts.md#loading-a-cart). + +If `null` (default), Craft’s default [`siteUrl`](config4:siteUrl) will be used. + + + +### `purgeInactiveCarts` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [Settings::$purgeInactiveCarts](commerce4:craft\commerce\models\Settings::$purgeInactiveCarts) + +
+ +Whether inactive carts should automatically be deleted from the database during garbage collection. + +::: tip +You can control how long a cart should go without being updated before it gets deleted [`purgeInactiveCartsDuration`](#purgeinactivecartsduration) setting. +::: + + + +### `purgeInactiveCartsDuration` + +
+ +Allowed types +: `mixed` + +Default value +: `7776000` (90 days) + +Defined by +: [Settings::$purgeInactiveCartsDuration](commerce4:craft\commerce\models\Settings::$purgeInactiveCartsDuration) + +
+ +Default length of time before inactive carts are purged. (Defaults to 90 days.) + +See [craft\helpers\ConfigHelper::durationInSeconds()](craft4:craft\helpers\ConfigHelper::durationInSeconds()) for a list of supported value types. + + + +### `updateCartSearchIndexes` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `true` + +Defined by +: [Settings::$updateCartSearchIndexes](commerce4:craft\commerce\models\Settings::$updateCartSearchIndexes) + +Since +: 3.1.5 + +
+ +Whether the search index for a cart should be updated when saving the cart via `commerce/cart/*` controller actions. + +May be set to `false` to reduce performance impact on high-traffic sites. + +::: warning +Setting this to `false` will result in fewer index update queue jobs, but you’ll need to manually re-index orders to ensure up-to-date cart search results in the control panel. +::: + + + +### `validateCartCustomFieldsOnSubmission` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$validateCartCustomFieldsOnSubmission](commerce4:craft\commerce\models\Settings::$validateCartCustomFieldsOnSubmission) + +Since +: 3.0.12 + +
+ +Whether to validate custom fields when a cart is updated. + +Set to `true` to allow custom content fields to return validation errors when a cart is updated. + + + +## Orders + +### `freeOrderPaymentStrategy` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'complete'` + +Defined by +: [Settings::$freeOrderPaymentStrategy](commerce4:craft\commerce\models\Settings::$freeOrderPaymentStrategy) + +
+ +How Commerce should handle free orders. + +The default `'complete'` setting automatically completes zero-balance orders without forwarding them to the payment gateway. + +The `'process'` setting forwards zero-balance orders to the payment gateway for processing. This can be useful if the customer’s balance +needs to be updated or otherwise adjusted by the payment gateway. + + + +### `minimumTotalPriceStrategy` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'default'` + +Defined by +: [Settings::$minimumTotalPriceStrategy](commerce4:craft\commerce\models\Settings::$minimumTotalPriceStrategy) + +
+ +How Commerce should handle minimum total price for an order. + +Options: + +- `'default'` [rounds](commerce4:\craft\commerce\helpers\Currency::round()) the sum of the item subtotal and adjustments. +- `'zero'` returns `0` if the result from `'default'` would’ve been negative; minimum order total is `0`. +- `'shipping'` returns the total shipping cost if the `'default'` result would’ve been negative; minimum order total equals shipping amount. + + + +### `orderReferenceFormat` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'{{number[:7]}}'` + +Defined by +: [Settings::$orderReferenceFormat](commerce4:craft\commerce\models\Settings::$orderReferenceFormat) + +
+ +Human-friendly reference number format for orders. Result must be unique. + +See [Order Numbers](orders-carts.md#order-numbers). + + + +### `pdfAllowRemoteImages` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$pdfAllowRemoteImages](commerce4:craft\commerce\models\Settings::$pdfAllowRemoteImages) + +
+ +Whether to allow non-local images in generated order PDFs. + + + +### `pdfPaperOrientation` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'portrait'` + +Defined by +: [Settings::$pdfPaperOrientation](commerce4:craft\commerce\models\Settings::$pdfPaperOrientation) + +
+ +The orientation of the paper to use for generated order PDF files. + +Options are `'portrait'` and `'landscape'`. + + + +### `pdfPaperSize` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'letter'` + +Defined by +: [Settings::$pdfPaperSize](commerce4:craft\commerce\models\Settings::$pdfPaperSize) + +
+ +The size of the paper to use for generated order PDFs. + +The full list of supported paper sizes can be found [in the dompdf library](https://github.com/dompdf/dompdf/blob/master/src/Adapter/CPDF.php#L45). + + + +### `requireBillingAddressAtCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$requireBillingAddressAtCheckout](commerce4:craft\commerce\models\Settings::$requireBillingAddressAtCheckout) + +
+ +Whether a billing address is required before making payment on an order. + + + +### `requireShippingAddressAtCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$requireShippingAddressAtCheckout](commerce4:craft\commerce\models\Settings::$requireShippingAddressAtCheckout) + +
+ +Whether a shipping address is required before making payment on an order. + + + +### `requireShippingMethodSelectionAtCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$requireShippingMethodSelectionAtCheckout](commerce4:craft\commerce\models\Settings::$requireShippingMethodSelectionAtCheckout) + +
+ +Whether shipping method selection is required before making payment on an order. + + + +### `updateBillingDetailsUrl` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [Settings::$updateBillingDetailsUrl](commerce4:craft\commerce\models\Settings::$updateBillingDetailsUrl) + +
+ +URL for a user to resolve billing issues with their subscription. + +::: tip +The example templates include [a template for this page](https://github.com/craftcms/commerce/tree/main/example-templates/dist/shop/plans/update-billing-details.twig). +::: + + + +### `useBillingAddressForTax` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$useBillingAddressForTax](commerce4:craft\commerce\models\Settings::$useBillingAddressForTax) + +
+ +Whether taxes should be calculated based on the billing address instead of the shipping address. + + + +### `validateBusinessTaxIdAsVatId` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$validateBusinessTaxIdAsVatId](commerce4:craft\commerce\models\Settings::$validateBusinessTaxIdAsVatId) + +
+ +Whether to enable validation requiring the `businessTaxId` to be a valid VAT ID. + +When set to `false`, no validation is applied to `businessTaxId`. + +When set to `true`, `businessTaxId` must contain a valid VAT ID. + +::: tip +This setting strictly toggles input validation and has no impact on tax configuration or behavior elsewhere in the system. +::: + + + +## Payments + +### `allowPartialPaymentOnCheckout` + +
+ +Allowed types +: [boolean](https://php.net/language.types.boolean) + +Default value +: `false` + +Defined by +: [Settings::$allowPartialPaymentOnCheckout](commerce4:craft\commerce\models\Settings::$allowPartialPaymentOnCheckout) + +
+ +Whether [partial payment](making-payments.md#checkout-with-partial-payment) can be made from the front end when the gateway allows them. + +The `false` default does not allow partial payments on the front end. + + + +### `gatewayPostRedirectTemplate` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `''` + +Defined by +: [Settings::$gatewayPostRedirectTemplate](commerce4:craft\commerce\models\Settings::$gatewayPostRedirectTemplate) + +
+ +The path to the template that should be used to perform POST requests to offsite payment gateways. + +The template must contain a form that posts to the URL supplied by the `actionUrl` variable and outputs all hidden inputs with +the `inputs` variable. + +```twig + + + + + Redirecting... + + +
+

Redirecting to payment page...

+

+ {{ inputs|raw }} + +

+
+ + +``` + +::: tip +Since this template is simply used for redirecting, it only appears for a few seconds, so we suggest making it load fast with minimal +images and inline styles to reduce HTTP requests. +::: + +If empty (default), each gateway will decide how to handle after-payment redirects. + + + +### `paymentCurrency` + +
+ +Allowed types +: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) + +Default value +: `null` + +Defined by +: [Settings::$paymentCurrency](commerce4:craft\commerce\models\Settings::$paymentCurrency) + +
+ +ISO codes for supported payment currencies. + +See [Payment Currencies](payment-currencies.md). + + + +## Units + +### `dimensionUnits` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'mm'` + +Defined by +: [Settings::$dimensionUnits](commerce4:craft\commerce\models\Settings::$dimensionUnits) + +
+ +Unit type for dimension measurements. + +Options: + +- `'mm'` +- `'cm'` +- `'m'` +- `'ft'` +- `'in'` + + + +### `weightUnits` + +
+ +Allowed types +: [string](https://php.net/language.types.string) + +Default value +: `'g'` + +Defined by +: [Settings::$weightUnits](commerce4:craft\commerce\models\Settings::$weightUnits) + +
+ +Units to be used for weight measurements. + +Options: + +- `'g'` +- `'kg'` +- `'lb'` + + + + + diff --git a/docs/commerce/4.x/event-data/events.json b/docs/.artifacts/commerce/4.x/events.json similarity index 97% rename from docs/commerce/4.x/event-data/events.json rename to docs/.artifacts/commerce/4.x/events.json index 7e7428424..fcf430cd9 100644 --- a/docs/commerce/4.x/event-data/events.json +++ b/docs/.artifacts/commerce/4.x/events.json @@ -2458,6 +2458,24 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\console\\controllers\\GatewaysController", + "name": "EVENT_DEFINE_ACTIONS", + "type": "craft\\events\\DefineConsoleActionsEvent", + "desc": "The event that is triggered when defining custom actions for this controller." + }, + { + "class": "craft\\commerce\\console\\controllers\\GatewaysController", + "name": "EVENT_BEFORE_ACTION", + "type": "yii\\base\\ActionEvent", + "desc": "an event raised right before executing a controller action. You may set `ActionEvent::isValid` to be false to cancel the action execution." + }, + { + "class": "craft\\commerce\\console\\controllers\\GatewaysController", + "name": "EVENT_AFTER_ACTION", + "type": "yii\\base\\ActionEvent", + "desc": "an event raised right after executing a controller action." + }, { "class": "craft\\commerce\\console\\controllers\\ResetDataController", "name": "EVENT_DEFINE_ACTIONS", @@ -2512,6 +2530,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\BaseAdminController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\BaseAdminController", "name": "EVENT_BEFORE_ACTION", @@ -2524,6 +2548,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\BaseController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\BaseController", "name": "EVENT_BEFORE_ACTION", @@ -2536,6 +2566,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\BaseCpController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\BaseCpController", "name": "EVENT_BEFORE_ACTION", @@ -2554,6 +2590,12 @@ "type": "craft\\commerce\\controllers\\Event", "desc": "The event that’s triggered when a cart is returned as an array for Ajax cart update requests." }, + { + "class": "craft\\commerce\\controllers\\BaseFrontEndController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\BaseFrontEndController", "name": "EVENT_BEFORE_ACTION", @@ -2566,6 +2608,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\BaseShippingSettingsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\BaseShippingSettingsController", "name": "EVENT_BEFORE_ACTION", @@ -2578,6 +2626,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\BaseStoreSettingsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\BaseStoreSettingsController", "name": "EVENT_BEFORE_ACTION", @@ -2590,6 +2644,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\BaseTaxSettingsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\BaseTaxSettingsController", "name": "EVENT_BEFORE_ACTION", @@ -2608,6 +2668,12 @@ "type": "craft\\commerce\\controllers\\Event", "desc": "The event that’s triggered when a cart is returned as an array for Ajax cart update requests." }, + { + "class": "craft\\commerce\\controllers\\CartController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\CartController", "name": "EVENT_BEFORE_ACTION", @@ -2620,6 +2686,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\DiscountsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\DiscountsController", "name": "EVENT_BEFORE_ACTION", @@ -2632,6 +2704,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\DonationsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\DonationsController", "name": "EVENT_BEFORE_ACTION", @@ -2650,6 +2728,12 @@ "type": "craft\\commerce\\controllers\\Event", "desc": "The event that’s triggered when a cart is returned as an array for Ajax cart update requests." }, + { + "class": "craft\\commerce\\controllers\\DownloadsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\DownloadsController", "name": "EVENT_BEFORE_ACTION", @@ -2662,6 +2746,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\EmailPreviewController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\EmailPreviewController", "name": "EVENT_BEFORE_ACTION", @@ -2674,6 +2764,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\EmailsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\EmailsController", "name": "EVENT_BEFORE_ACTION", @@ -2686,6 +2782,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\FormulasController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\FormulasController", "name": "EVENT_BEFORE_ACTION", @@ -2698,6 +2800,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\GatewaysController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\GatewaysController", "name": "EVENT_BEFORE_ACTION", @@ -2710,6 +2818,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\LineItemStatusesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\LineItemStatusesController", "name": "EVENT_BEFORE_ACTION", @@ -2722,6 +2836,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\LiteShippingController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\LiteShippingController", "name": "EVENT_BEFORE_ACTION", @@ -2734,6 +2854,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\LiteTaxController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\LiteTaxController", "name": "EVENT_BEFORE_ACTION", @@ -2746,6 +2872,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\OrderSettingsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\OrderSettingsController", "name": "EVENT_BEFORE_ACTION", @@ -2758,6 +2890,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\OrderStatusesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\OrderStatusesController", "name": "EVENT_BEFORE_ACTION", @@ -2770,6 +2908,18 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\OrdersController", + "name": "EVENT_MODIFY_PURCHASABLES_TABLE_QUERY", + "type": "craft\\commerce\\controllers\\Event", + "desc": "The event that’s triggered when retrieving the purchasables for the add line item table on the order edit page." + }, + { + "class": "craft\\commerce\\controllers\\OrdersController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\OrdersController", "name": "EVENT_BEFORE_ACTION", @@ -2782,6 +2932,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\PaymentCurrenciesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\PaymentCurrenciesController", "name": "EVENT_BEFORE_ACTION", @@ -2800,6 +2956,12 @@ "type": "craft\\commerce\\controllers\\Event", "desc": "The event that’s triggered when a cart is returned as an array for Ajax cart update requests." }, + { + "class": "craft\\commerce\\controllers\\PaymentSourcesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\PaymentSourcesController", "name": "EVENT_BEFORE_ACTION", @@ -2818,6 +2980,12 @@ "type": "craft\\commerce\\controllers\\Event", "desc": "The event that’s triggered when a cart is returned as an array for Ajax cart update requests." }, + { + "class": "craft\\commerce\\controllers\\PaymentsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\PaymentsController", "name": "EVENT_BEFORE_ACTION", @@ -2830,6 +2998,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\PdfsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\PdfsController", "name": "EVENT_BEFORE_ACTION", @@ -2842,6 +3016,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\PlansController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\PlansController", "name": "EVENT_BEFORE_ACTION", @@ -2854,6 +3034,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\ProductTypesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\ProductTypesController", "name": "EVENT_BEFORE_ACTION", @@ -2866,6 +3052,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\ProductsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\ProductsController", "name": "EVENT_BEFORE_ACTION", @@ -2878,6 +3070,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\ProductsPreviewController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\ProductsPreviewController", "name": "EVENT_BEFORE_ACTION", @@ -2890,6 +3088,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\PromotionsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\PromotionsController", "name": "EVENT_BEFORE_ACTION", @@ -2902,6 +3106,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\SalesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\SalesController", "name": "EVENT_BEFORE_ACTION", @@ -2914,6 +3124,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\SettingsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\SettingsController", "name": "EVENT_BEFORE_ACTION", @@ -2926,6 +3142,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\ShippingCategoriesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\ShippingCategoriesController", "name": "EVENT_BEFORE_ACTION", @@ -2938,6 +3160,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\ShippingMethodsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\ShippingMethodsController", "name": "EVENT_BEFORE_ACTION", @@ -2950,6 +3178,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\ShippingRulesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\ShippingRulesController", "name": "EVENT_BEFORE_ACTION", @@ -2962,6 +3196,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\ShippingZonesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\ShippingZonesController", "name": "EVENT_BEFORE_ACTION", @@ -2974,6 +3214,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\StoreController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\StoreController", "name": "EVENT_BEFORE_ACTION", @@ -2986,6 +3232,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\SubscriptionsController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\SubscriptionsController", "name": "EVENT_BEFORE_ACTION", @@ -2998,6 +3250,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\TaxCategoriesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\TaxCategoriesController", "name": "EVENT_BEFORE_ACTION", @@ -3010,6 +3268,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\TaxRatesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\TaxRatesController", "name": "EVENT_BEFORE_ACTION", @@ -3022,6 +3286,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\TaxZonesController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\TaxZonesController", "name": "EVENT_BEFORE_ACTION", @@ -3040,6 +3310,12 @@ "type": "craft\\commerce\\controllers\\Event", "desc": "The event that’s triggered when a cart is returned as an array for Ajax cart update requests." }, + { + "class": "craft\\commerce\\controllers\\UserOrdersController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\UserOrdersController", "name": "EVENT_BEFORE_ACTION", @@ -3052,6 +3328,12 @@ "type": "yii\\base\\ActionEvent", "desc": "an event raised right after executing a controller action." }, + { + "class": "craft\\commerce\\controllers\\WebhooksController", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, { "class": "craft\\commerce\\controllers\\WebhooksController", "name": "EVENT_BEFORE_ACTION", @@ -14881,6 +15163,216 @@ "type": "yii\\base\\Event", "desc": "an event raised at the end of `validate()`" }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductTypeConditionRule", + "name": "EVENT_INIT", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the model's init cycle" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductTypeConditionRule", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductTypeConditionRule", + "name": "EVENT_DEFINE_RULES", + "type": "craft\\events\\DefineRulesEvent", + "desc": "The event that is triggered when defining the model rules" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductTypeConditionRule", + "name": "EVENT_DEFINE_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductTypeConditionRule", + "name": "EVENT_DEFINE_EXTRA_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the extra arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductTypeConditionRule", + "name": "EVENT_BEFORE_VALIDATE", + "type": "yii\\base\\ModelEvent", + "desc": "an event raised at the beginning of `validate()`. You may set `ModelEvent::isValid` to be false to stop the validation." + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductTypeConditionRule", + "name": "EVENT_AFTER_VALIDATE", + "type": "yii\\base\\Event", + "desc": "an event raised at the end of `validate()`" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantHasUnlimitedStockConditionRule", + "name": "EVENT_INIT", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the model's init cycle" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantHasUnlimitedStockConditionRule", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantHasUnlimitedStockConditionRule", + "name": "EVENT_DEFINE_RULES", + "type": "craft\\events\\DefineRulesEvent", + "desc": "The event that is triggered when defining the model rules" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantHasUnlimitedStockConditionRule", + "name": "EVENT_DEFINE_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantHasUnlimitedStockConditionRule", + "name": "EVENT_DEFINE_EXTRA_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the extra arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantHasUnlimitedStockConditionRule", + "name": "EVENT_BEFORE_VALIDATE", + "type": "yii\\base\\ModelEvent", + "desc": "an event raised at the beginning of `validate()`. You may set `ModelEvent::isValid` to be false to stop the validation." + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantHasUnlimitedStockConditionRule", + "name": "EVENT_AFTER_VALIDATE", + "type": "yii\\base\\Event", + "desc": "an event raised at the end of `validate()`" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantPriceConditionRule", + "name": "EVENT_INIT", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the model's init cycle" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantPriceConditionRule", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantPriceConditionRule", + "name": "EVENT_DEFINE_RULES", + "type": "craft\\events\\DefineRulesEvent", + "desc": "The event that is triggered when defining the model rules" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantPriceConditionRule", + "name": "EVENT_DEFINE_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantPriceConditionRule", + "name": "EVENT_DEFINE_EXTRA_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the extra arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantPriceConditionRule", + "name": "EVENT_BEFORE_VALIDATE", + "type": "yii\\base\\ModelEvent", + "desc": "an event raised at the beginning of `validate()`. You may set `ModelEvent::isValid` to be false to stop the validation." + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantPriceConditionRule", + "name": "EVENT_AFTER_VALIDATE", + "type": "yii\\base\\Event", + "desc": "an event raised at the end of `validate()`" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantSkuConditionRule", + "name": "EVENT_INIT", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the model's init cycle" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantSkuConditionRule", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantSkuConditionRule", + "name": "EVENT_DEFINE_RULES", + "type": "craft\\events\\DefineRulesEvent", + "desc": "The event that is triggered when defining the model rules" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantSkuConditionRule", + "name": "EVENT_DEFINE_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantSkuConditionRule", + "name": "EVENT_DEFINE_EXTRA_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the extra arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantSkuConditionRule", + "name": "EVENT_BEFORE_VALIDATE", + "type": "yii\\base\\ModelEvent", + "desc": "an event raised at the beginning of `validate()`. You may set `ModelEvent::isValid` to be false to stop the validation." + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantSkuConditionRule", + "name": "EVENT_AFTER_VALIDATE", + "type": "yii\\base\\Event", + "desc": "an event raised at the end of `validate()`" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantStockConditionRule", + "name": "EVENT_INIT", + "type": "yii\\base\\Event", + "desc": "The event that is triggered after the model's init cycle" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantStockConditionRule", + "name": "EVENT_DEFINE_BEHAVIORS", + "type": "craft\\events\\DefineBehaviorsEvent", + "desc": "The event that is triggered when defining the class behaviors" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantStockConditionRule", + "name": "EVENT_DEFINE_RULES", + "type": "craft\\events\\DefineRulesEvent", + "desc": "The event that is triggered when defining the model rules" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantStockConditionRule", + "name": "EVENT_DEFINE_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantStockConditionRule", + "name": "EVENT_DEFINE_EXTRA_FIELDS", + "type": "craft\\events\\DefineFieldsEvent", + "desc": "The event that is triggered when defining the extra arrayable fields" + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantStockConditionRule", + "name": "EVENT_BEFORE_VALIDATE", + "type": "yii\\base\\ModelEvent", + "desc": "an event raised at the beginning of `validate()`. You may set `ModelEvent::isValid` to be false to stop the validation." + }, + { + "class": "craft\\commerce\\elements\\conditions\\products\\ProductVariantStockConditionRule", + "name": "EVENT_AFTER_VALIDATE", + "type": "yii\\base\\Event", + "desc": "an event raised at the end of `validate()`" + }, { "class": "craft\\commerce\\elements\\conditions\\users\\DiscountGroupConditionRule", "name": "EVENT_INIT", @@ -14974,13 +15466,13 @@ { "class": "craft\\commerce\\elements\\db\\DonationQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\commerce\\elements\\db\\DonationQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -14989,6 +15481,12 @@ "type": "craft\\events\\DefineValueEvent", "desc": "An event that is triggered when defining the cache tags that should be associated with the query." }, + { + "class": "craft\\commerce\\elements\\db\\DonationQuery", + "name": "EVENT_BEFORE_POPULATE_ELEMENT", + "type": "craft\\events\\PopulateElementEvent", + "desc": "The event that is triggered before an element is populated." + }, { "class": "craft\\commerce\\elements\\db\\DonationQuery", "name": "EVENT_AFTER_POPULATE_ELEMENT", @@ -15016,13 +15514,13 @@ { "class": "craft\\commerce\\elements\\db\\OrderQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\commerce\\elements\\db\\OrderQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -15031,6 +15529,12 @@ "type": "craft\\events\\DefineValueEvent", "desc": "An event that is triggered when defining the cache tags that should be associated with the query." }, + { + "class": "craft\\commerce\\elements\\db\\OrderQuery", + "name": "EVENT_BEFORE_POPULATE_ELEMENT", + "type": "craft\\events\\PopulateElementEvent", + "desc": "The event that is triggered before an element is populated." + }, { "class": "craft\\commerce\\elements\\db\\OrderQuery", "name": "EVENT_AFTER_POPULATE_ELEMENT", @@ -15058,13 +15562,13 @@ { "class": "craft\\commerce\\elements\\db\\ProductQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\commerce\\elements\\db\\ProductQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -15073,6 +15577,12 @@ "type": "craft\\events\\DefineValueEvent", "desc": "An event that is triggered when defining the cache tags that should be associated with the query." }, + { + "class": "craft\\commerce\\elements\\db\\ProductQuery", + "name": "EVENT_BEFORE_POPULATE_ELEMENT", + "type": "craft\\events\\PopulateElementEvent", + "desc": "The event that is triggered before an element is populated." + }, { "class": "craft\\commerce\\elements\\db\\ProductQuery", "name": "EVENT_AFTER_POPULATE_ELEMENT", @@ -15100,13 +15610,13 @@ { "class": "craft\\commerce\\elements\\db\\SubscriptionQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\commerce\\elements\\db\\SubscriptionQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -15115,6 +15625,12 @@ "type": "craft\\events\\DefineValueEvent", "desc": "An event that is triggered when defining the cache tags that should be associated with the query." }, + { + "class": "craft\\commerce\\elements\\db\\SubscriptionQuery", + "name": "EVENT_BEFORE_POPULATE_ELEMENT", + "type": "craft\\events\\PopulateElementEvent", + "desc": "The event that is triggered before an element is populated." + }, { "class": "craft\\commerce\\elements\\db\\SubscriptionQuery", "name": "EVENT_AFTER_POPULATE_ELEMENT", @@ -15142,13 +15658,13 @@ { "class": "craft\\commerce\\elements\\db\\VariantQuery", "name": "EVENT_BEFORE_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the beginning of preparing an element query for the query builder." }, { "class": "craft\\commerce\\elements\\db\\VariantQuery", "name": "EVENT_AFTER_PREPARE", - "type": "craft\\elements\\db\\Event", + "type": "craft\\events\\CancelableEvent", "desc": "An event that is triggered at the end of preparing an element query for the query builder." }, { @@ -15157,6 +15673,12 @@ "type": "craft\\events\\DefineValueEvent", "desc": "An event that is triggered when defining the cache tags that should be associated with the query." }, + { + "class": "craft\\commerce\\elements\\db\\VariantQuery", + "name": "EVENT_BEFORE_POPULATE_ELEMENT", + "type": "craft\\events\\PopulateElementEvent", + "desc": "The event that is triggered before an element is populated." + }, { "class": "craft\\commerce\\elements\\db\\VariantQuery", "name": "EVENT_AFTER_POPULATE_ELEMENT", diff --git a/docs/.artifacts/commerce/4.x/orders-carts.md b/docs/.artifacts/commerce/4.x/orders-carts.md new file mode 100644 index 000000000..0fe7b82cb --- /dev/null +++ b/docs/.artifacts/commerce/4.x/orders-carts.md @@ -0,0 +1,1488 @@ + + + + + + + + +| Param | Description +| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only orders that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching orders as arrays of data, rather than [Order](commerce4:craft\commerce\elements\Order) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [customer](#customer) | Narrows the query results based on the customer’s user account. +| [customerId](#customerid) | Narrows the query results based on the customer, per their user ID. +| [dateAuthorized](#dateauthorized) | Narrows the query results based on the orders’ authorized dates. +| [dateCreated](#datecreated) | Narrows the query results based on the orders’ creation dates. +| [dateOrdered](#dateordered) | Narrows the query results based on the orders’ completion dates. +| [datePaid](#datepaid) | Narrows the query results based on the orders’ paid dates. +| [dateUpdated](#dateupdated) | Narrows the query results based on the orders’ last-updated dates. +| [email](#email) | Narrows the query results based on the customers’ email addresses. +| [expiryDate](#expirydate) | Narrows the query results based on the orders’ expiry dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [gateway](#gateway) | Narrows the query results based on the gateway. +| [gatewayId](#gatewayid) | Narrows the query results based on the gateway, per its ID. +| [hasLineItems](#haslineitems) | Narrows the query results to only orders that have line items. +| [hasPurchasables](#haspurchasables) | Narrows the query results to only orders that have certain purchasables. +| [hasTransactions](#hastransactions) | Narrows the query results to only carts that have at least one transaction. +| [id](#id) | +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [isCompleted](#iscompleted) | Narrows the query results to only orders that are completed. +| [isPaid](#ispaid) | Narrows the query results to only orders that are paid. +| [isUnpaid](#isunpaid) | Narrows the query results to only orders that are not paid. +| [itemSubtotal](#itemsubtotal) | Narrows the query results based on the order’s item subtotal. +| [itemTotal](#itemtotal) | Narrows the query results based on the order’s item total. +| [limit](#limit) | Determines the number of orders that should be returned. +| [number](#number) | Narrows the query results based on the order number. +| [offset](#offset) | Determines how many orders should be skipped in the results. +| [orderBy](#orderby) | Determines the order that the orders should be returned in. (If empty, defaults to `id ASC`.) +| [orderLanguage](#orderlanguage) | Narrows the query results based on the order language, per the language string provided. +| [orderSiteId](#ordersiteid) | Narrows the query results based on the order language, per the language string provided. +| [orderStatus](#orderstatus) | Narrows the query results based on the order statuses. +| [orderStatusId](#orderstatusid) | Narrows the query results based on the order statuses, per their IDs. +| [origin](#origin) | Narrows the query results based on the origin. +| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v4/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [reference](#reference) | Narrows the query results based on the order reference. +| [relatedTo](#relatedto) | Narrows the query results to only orders that are related to certain other elements. +| [search](#search) | Narrows the query results to only orders that match a search query. +| [shippingMethodHandle](#shippingmethodhandle) | Narrows the query results based on the shipping method handle. +| [shortNumber](#shortnumber) | Narrows the query results based on the order short number. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the orders’ IDs in the `elements_sites` table. +| [total](#total) | Narrows the query results based on the total. +| [totalDiscount](#totaldiscount) | Narrows the query results based on the total discount. +| [totalPaid](#totalpaid) | Narrows the query results based on the total paid amount. +| [totalPrice](#totalprice) | Narrows the query results based on the total price. +| [totalQty](#totalqty) | Narrows the query results based on the total qty of items. +| [totalTax](#totaltax) | Narrows the query results based on the total tax. +| [trashed](#trashed) | Narrows the query results to only orders that have been soft-deleted. +| [uid](#uid) | Narrows the query results based on the orders’ UIDs. +| [with](#with) | Causes the query to return matching orders eager-loaded with related elements. +| [withAddresses](#withaddresses) | Eager loads the the shipping and billing addressees on the resulting orders. +| [withAdjustments](#withadjustments) | Eager loads the order adjustments on the resulting orders. +| [withAll](#withall) | Eager loads all relational data (addresses, adjustents, customers, line items, transactions) for the resulting orders. +| [withCustomer](#withcustomer) | Eager loads the user on the resulting orders. +| [withLineItems](#withlineitems) | Eager loads the line items on the resulting orders. +| [withTransactions](#withtransactions) | Eager loads the transactions on the resulting orders. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only orders that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all orders that are related to myCategoryA and myCategoryB #} +{% set orders = craft.orders() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all orders that are related to $myCategoryA and $myCategoryB +$orders = \craft\commerce\elements\Order::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching orders as arrays of data, rather than [Order](commerce4:craft\commerce\elements\Order) objects. + + + + + +::: code +```twig +{# Fetch orders as arrays #} +{% set orders = craft.orders() + .asArray() + .all() %} +``` + +```php +// Fetch orders as arrays +$orders = \craft\commerce\elements\Order::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `customer` + +Narrows the query results based on the customer’s user account. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a customer with a user account ID of 1. +| a [User](https://docs.craftcms.com/api/v4/craft-elements-user.html) object | with a customer with a user account represented by the object. +| `'not 1'` | not the user account with an ID 1. +| `[1, 2]` | with an user account ID of 1 or 2. +| `['not', 1, 2]` | not with a user account ID of 1 or 2. + + + +::: code +```twig +{# Fetch the current user's orders #} +{% set orders = craft.orders() + .customer(currentUser) + .all() %} +``` + +```php +// Fetch the current user's orders +$user = Craft::$app->user->getIdentity(); +$orders = \craft\commerce\elements\Order::find() + ->customer($user) + ->all(); +``` +::: + + +#### `customerId` + +Narrows the query results based on the customer, per their user ID. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a user with an ID of 1. +| `'not 1'` | not with a user with an ID of 1. +| `[1, 2]` | with a user with an ID of 1 or 2. +| `['not', 1, 2]` | not with a user with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the current user's orders #} +{% set orders = craft.orders() + .customerId(currentUser.id) + .all() %} +``` + +```php +// Fetch the current user's orders +$user = Craft::$app->user->getIdentity(); +$orders = \craft\commerce\elements\Order::find() + ->customerId($user->id) + ->all(); +``` +::: + + +#### `dateAuthorized` + +Narrows the query results based on the orders’ authorized dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were authorized on or after 2018-04-01. +| `'< 2018-05-01'` | that were authorized before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders that were authorized recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set orders = craft.orders() + .dateAuthorized(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch orders that were authorized recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateAuthorized(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `dateCreated` + +Narrows the query results based on the orders’ creation dates. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch orders created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set orders = craft.orders() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch orders created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateOrdered` + +Narrows the query results based on the orders’ completion dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were completed on or after 2018-04-01. +| `'< 2018-05-01'` | that were completed before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders that were completed recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set orders = craft.orders() + .dateOrdered(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch orders that were completed recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateOrdered(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `datePaid` + +Narrows the query results based on the orders’ paid dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were paid on or after 2018-04-01. +| `'< 2018-05-01'` | that were paid before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch orders that were paid for recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set orders = craft.orders() + .datePaid(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch orders that were paid for recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->datePaid(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the orders’ last-updated dates. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch orders updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set orders = craft.orders() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch orders updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `email` + +Narrows the query results based on the customers’ email addresses. + +Possible values include: + +| Value | Fetches orders with customers… +| - | - +| `'foo@bar.baz'` | with an email of `foo@bar.baz`. +| `'not foo@bar.baz'` | not with an email of `foo@bar.baz`. +| `'*@bar.baz'` | with an email that ends with `@bar.baz`. + + + +::: code +```twig +{# Fetch orders from customers with a .co.uk domain on their email address #} +{% set orders = craft.orders() + .email('*.co.uk') + .all() %} +``` + +```php +// Fetch orders from customers with a .co.uk domain on their email address +$orders = \craft\commerce\elements\Order::find() + ->email('*.co.uk') + ->all(); +``` +::: + + +#### `expiryDate` + +Narrows the query results based on the orders’ expiry dates. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. +| `'< 2020-05-01'` | that will expire before 2020-05-01 +| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. + + + +::: code +```twig +{# Fetch orders expiring this month #} +{% set nextMonth = date('first day of next month')|atom %} + +{% set orders = craft.orders() + .expiryDate("< #{nextMonth}") + .all() %} +``` + +```php +// Fetch orders expiring this month +$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); + +$orders = \craft\commerce\elements\Order::find() + ->expiryDate("< {$nextMonth}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch orders in a specific order #} +{% set orders = craft.orders() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch orders in a specific order +$orders = \craft\commerce\elements\Order::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `gateway` + +Narrows the query results based on the gateway. + +Possible values include: + +| Value | Fetches orders… +| - | - +| a [Gateway](commerce4:craft\commerce\base\Gateway) object | with a gateway represented by the object. + + + + +#### `gatewayId` + +Narrows the query results based on the gateway, per its ID. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with a gateway with an ID of 1. +| `'not 1'` | not with a gateway with an ID of 1. +| `[1, 2]` | with a gateway with an ID of 1 or 2. +| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. + + + + +#### `hasLineItems` + +Narrows the query results to only orders that have line items. + + + +::: code +```twig +{# Fetch orders that do or do not have line items #} +{% set orders = craft.orders() + .hasLineItems() + .all() %} +``` + +```php +// Fetch unpaid orders +$orders = \craft\commerce\elements\Order::find() + ->hasLineItems() + ->all(); +``` +::: + + +#### `hasPurchasables` + +Narrows the query results to only orders that have certain purchasables. + +Possible values include: + +| Value | Fetches orders… +| - | - +| a [PurchasableInterface](commerce4:craft\commerce\base\PurchasableInterface) object | with a purchasable represented by the object. +| an array of [PurchasableInterface](commerce4:craft\commerce\base\PurchasableInterface) objects | with all the purchasables represented by the objects. + + + + +#### `hasTransactions` + +Narrows the query results to only carts that have at least one transaction. + + + +::: code +```twig +{# Fetch carts that have attempted payments #} +{% set orders = craft.orders() + .hasTransactions() + .all() %} +``` + +```php +// Fetch carts that have attempted payments +$orders = \craft\commerce\elements\Order::find() + ->hasTransactions() + ->all(); +``` +::: + + +#### `id` + + + + + + + + +#### `ignorePlaceholders` + +Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch orders in reverse #} +{% set orders = craft.orders() + .inReverse() + .all() %} +``` + +```php +// Fetch orders in reverse +$orders = \craft\commerce\elements\Order::find() + ->inReverse() + ->all(); +``` +::: + + +#### `isCompleted` + +Narrows the query results to only orders that are completed. + + + +::: code +```twig +{# Fetch completed orders #} +{% set orders = craft.orders() + .isCompleted() + .all() %} +``` + +```php +// Fetch completed orders +$orders = \craft\commerce\elements\Order::find() + ->isCompleted() + ->all(); +``` +::: + + +#### `isPaid` + +Narrows the query results to only orders that are paid. + + + +::: code +```twig +{# Fetch paid orders #} +{% set orders = craft.orders() + .isPaid() + .all() %} +``` + +```php +// Fetch paid orders +$orders = \craft\commerce\elements\Order::find() + ->isPaid() + ->all(); +``` +::: + + +#### `isUnpaid` + +Narrows the query results to only orders that are not paid. + + + +::: code +```twig +{# Fetch unpaid orders #} +{% set orders = craft.orders() + .isUnpaid() + .all() %} +``` + +```php +// Fetch unpaid orders +$orders = \craft\commerce\elements\Order::find() + ->isUnpaid() + ->all(); +``` +::: + + +#### `itemSubtotal` + +Narrows the query results based on the order’s item subtotal. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `100` | with an item subtotal of 0. +| `'< 1000000'` | with an item subtotal of less than ,000,000. +| `['>= 10', '< 100']` | with an item subtotal of between and 0. + + + + +#### `itemTotal` + +Narrows the query results based on the order’s item total. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `100` | with an item total of 0. +| `'< 1000000'` | with an item total of less than ,000,000. +| `['>= 10', '< 100']` | with an item total of between and 0. + + + + +#### `limit` + +Determines the number of orders that should be returned. + + + +::: code +```twig +{# Fetch up to 10 orders #} +{% set orders = craft.orders() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 orders +$orders = \craft\commerce\elements\Order::find() + ->limit(10) + ->all(); +``` +::: + + +#### `number` + +Narrows the query results based on the order number. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'` | with a matching order number + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderNumber = craft.app.request.getQueryParam('number') %} +{% set order = craft.orders() + .number(orderNumber) + .one() %} +``` + +```php +// Fetch the requested order +$orderNumber = Craft::$app->request->getQueryParam('number'); +$order = \craft\commerce\elements\Order::find() + ->number($orderNumber) + ->one(); +``` +::: + + +#### `offset` + +Determines how many orders should be skipped in the results. + + + +::: code +```twig +{# Fetch all orders except for the first 3 #} +{% set orders = craft.orders() + .offset(3) + .all() %} +``` + +```php +// Fetch all orders except for the first 3 +$orders = \craft\commerce\elements\Order::find() + ->offset(3) + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the orders should be returned in. (If empty, defaults to `id ASC`.) + + + +::: code +```twig +{# Fetch all orders in order of date created #} +{% set orders = craft.orders() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all orders in order of date created +$orders = \craft\commerce\elements\Order::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `orderLanguage` + +Narrows the query results based on the order language, per the language string provided. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'en'` | with an order language that is `'en'`. +| `'not en'` | not with an order language that is not `'en'`. +| `['en', 'en-us']` | with an order language that is `'en'` or `'en-us'`. +| `['not', 'en']` | not with an order language that is not `'en'`. + + + +::: code +```twig +{# Fetch orders with an order language that is `'en'` #} +{% set orders = craft.orders() + .orderLanguage('en') + .all() %} +``` + +```php +// Fetch orders with an order language that is `'en'` +$orders = \craft\commerce\elements\Order::find() + ->orderLanguage('en') + ->all(); +``` +::: + + +#### `orderSiteId` + +Narrows the query results based on the order language, per the language string provided. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an order site ID of 1. +| `'not 1'` | not with an order site ID that is no 1. +| `[1, 2]` | with an order site ID of 1 or 2. +| `['not', 1, 2]` | not with an order site ID of 1 or 2. + + + +::: code +```twig +{# Fetch orders with an order site ID of 1 #} +{% set orders = craft.orders() + .orderSiteId(1) + .all() %} +``` + +```php +// Fetch orders with an order site ID of 1 +$orders = \craft\commerce\elements\Order::find() + ->orderSiteId(1) + ->all(); +``` +::: + + +#### `orderStatus` + +Narrows the query results based on the order statuses. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'foo'` | with an order status with a handle of `foo`. +| `'not foo'` | not with an order status with a handle of `foo`. +| `['foo', 'bar']` | with an order status with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not with an order status with a handle of `foo` or `bar`. +| a [OrderStatus](commerce4:craft\commerce\models\OrderStatus) object | with an order status represented by the object. + + + +::: code +```twig +{# Fetch shipped orders #} +{% set orders = craft.orders() + .orderStatus('shipped') + .all() %} +``` + +```php +// Fetch shipped orders +$orders = \craft\commerce\elements\Order::find() + ->orderStatus('shipped') + ->all(); +``` +::: + + +#### `orderStatusId` + +Narrows the query results based on the order statuses, per their IDs. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an order status with an ID of 1. +| `'not 1'` | not with an order status with an ID of 1. +| `[1, 2]` | with an order status with an ID of 1 or 2. +| `['not', 1, 2]` | not with an order status with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch orders with an order status with an ID of 1 #} +{% set orders = craft.orders() + .orderStatusId(1) + .all() %} +``` + +```php +// Fetch orders with an order status with an ID of 1 +$orders = \craft\commerce\elements\Order::find() + ->orderStatusId(1) + ->all(); +``` +::: + + +#### `origin` + +Narrows the query results based on the origin. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'web'` | with an origin of `web`. +| `'not remote'` | not with an origin of `remote`. +| `['web', 'cp']` | with an order origin of `web` or `cp`. +| `['not', 'remote', 'cp']` | not with an origin of `web` or `cp`. + + + +::: code +```twig +{# Fetch shipped orders #} +{% set orders = craft.orders() + .origin('web') + .all() %} +``` + +```php +// Fetch shipped orders +$orders = \craft\commerce\elements\Order::find() + ->origin('web') + ->all(); +``` +::: + + +#### `preferSites` + +If [unique()](https://docs.craftcms.com/api/v4/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique orders from Site A, or Site B if they don’t exist in Site A #} +{% set orders = craft.orders() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique orders from Site A, or Site B if they don’t exist in Site A +$orders = \craft\commerce\elements\Order::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `reference` + +Narrows the query results based on the order reference. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'Foo'` | with a reference of `Foo`. +| `'Foo*'` | with a reference that begins with `Foo`. +| `'*Foo'` | with a reference that ends with `Foo`. +| `'*Foo*'` | with a reference that contains `Foo`. +| `'not *Foo*'` | with a reference that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a reference that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a reference that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderReference = craft.app.request.getQueryParam('ref') %} +{% set order = craft.orders() + .reference(orderReference) + .one() %} +``` + +```php +// Fetch the requested order +$orderReference = Craft::$app->request->getQueryParam('ref'); +$order = \craft\commerce\elements\Order::find() + ->reference($orderReference) + ->one(); +``` +::: + + +#### `relatedTo` + +Narrows the query results to only orders that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all orders that are related to myCategory #} +{% set orders = craft.orders() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all orders that are related to $myCategory +$orders = \craft\commerce\elements\Order::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only orders that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all orders that match the search query #} +{% set orders = craft.orders() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all orders that match the search query +$orders = \craft\commerce\elements\Order::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `shippingMethodHandle` + +Narrows the query results based on the shipping method handle. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'foo'` | with a shipping method with a handle of `foo`. +| `'not foo'` | not with a shipping method with a handle of `foo`. +| `['foo', 'bar']` | with a shipping method with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not with a shipping method with a handle of `foo` or `bar`. +| a `\craft\commerce\elements\db\ShippingMethod` object | with a shipping method represented by the object. + + + +::: code +```twig +{# Fetch collection shipping method orders #} +{% set orders = craft.orders() + .shippingMethodHandle('collection') + .all() %} +``` + +```php +// Fetch collection shipping method orders +$orders = \craft\commerce\elements\Order::find() + ->shippingMethodHandle('collection') + ->all(); +``` +::: + + +#### `shortNumber` + +Narrows the query results based on the order short number. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `'xxxxxxx'` | with a matching order number + + + +::: code +```twig +{# Fetch the requested order #} +{% set orderNumber = craft.app.request.getQueryParam('shortNumber') %} +{% set order = craft.orders() + .shortNumber(orderNumber) + .one() %} +``` + +```php +// Fetch the requested order +$orderNumber = Craft::$app->request->getQueryParam('shortNumber'); +$order = \craft\commerce\elements\Order::find() + ->shortNumber($orderNumber) + ->one(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the orders’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches orders… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the order by its ID in the elements_sites table #} +{% set order = craft.orders() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the order by its ID in the elements_sites table +$order = \craft\commerce\elements\Order::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `total` + +Narrows the query results based on the total. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `10` | with a total price of . +| `['and', 10, 20]` | an order with a total of or . + + + + +#### `totalDiscount` + +Narrows the query results based on the total discount. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `10` | with a total discount of 10. +| `[10, 20]` | an order with a total discount of 10 or 20. + + + + +#### `totalPaid` + +Narrows the query results based on the total paid amount. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `10` | with a total paid amount of . +| `['and', 10, 20]` | an order with a total paid amount of or . + + + + +#### `totalPrice` + +Narrows the query results based on the total price. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `10` | with a total price of . +| `['and', 10, 20]` | an order with a total price of or . + + + + +#### `totalQty` + +Narrows the query results based on the total qty of items. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `10` | with a total qty of 10. +| `[10, 20]` | an order with a total qty of 10 or 20. + + + + +#### `totalTax` + +Narrows the query results based on the total tax. + +Possible values include: + +| Value | Fetches orders… +| - | - +| `10` | with a total tax of 10. +| `[10, 20]` | an order with a total tax of 10 or 20. + + + + +#### `trashed` + +Narrows the query results to only orders that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed orders #} +{% set orders = craft.orders() + .trashed() + .all() %} +``` + +```php +// Fetch trashed orders +$orders = \craft\commerce\elements\Order::find() + ->trashed() + ->all(); +``` +::: + + +#### `uid` + +Narrows the query results based on the orders’ UIDs. + + + + + +::: code +```twig +{# Fetch the order by its UID #} +{% set order = craft.orders() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the order by its UID +$order = \craft\commerce\elements\Order::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `with` + +Causes the query to return matching orders eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch orders eager-loaded with the "Related" field’s relations #} +{% set orders = craft.orders() + .with(['related']) + .all() %} +``` + +```php +// Fetch orders eager-loaded with the "Related" field’s relations +$orders = \craft\commerce\elements\Order::find() + ->with(['related']) + ->all(); +``` +::: + + +#### `withAddresses` + +Eager loads the the shipping and billing addressees on the resulting orders. + +Possible values include: + +| Value | Fetches addresses +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withAdjustments` + +Eager loads the order adjustments on the resulting orders. + +Possible values include: + +| Value | Fetches adjustments +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withAll` + +Eager loads all relational data (addresses, adjustents, customers, line items, transactions) for the resulting orders. + +Possible values include: + +| Value | Fetches addresses, adjustents, customers, line items, transactions +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withCustomer` + +Eager loads the user on the resulting orders. + +Possible values include: + +| Value | Fetches adjustments +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withLineItems` + +Eager loads the line items on the resulting orders. + +Possible values include: + +| Value | Fetches line items +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + +#### `withTransactions` + +Eager loads the transactions on the resulting orders. + +Possible values include: + +| Value | Fetches transactions… +| - | - +| bool | `true` to eager-load, `false` to not eager load. + + + + + + diff --git a/docs/.artifacts/commerce/4.x/products-variants.md b/docs/.artifacts/commerce/4.x/products-variants.md new file mode 100644 index 000000000..6b3ed6a74 --- /dev/null +++ b/docs/.artifacts/commerce/4.x/products-variants.md @@ -0,0 +1,2640 @@ + + +## Product Query Parameters + +Product queries support the following parameters: + + + + + + + +| Param | Description +| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [after](#product-after) | Narrows the query results to only products that were posted on or after a certain date. +| [afterPopulate](#product-afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#product-andrelatedto) | Narrows the query results to only products that are related to certain other elements. +| [asArray](#product-asarray) | Causes the query to return matching products as arrays of data, rather than [Product](commerce4:craft\commerce\elements\Product) objects. +| [availableForPurchase](#product-availableforpurchase) | Narrows the query results to only products that are available for purchase. +| [before](#product-before) | Narrows the query results to only products that were posted before a certain date. +| [cache](#product-cache) | Enables query cache for this Query. +| [clearCachedResult](#product-clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [dateCreated](#product-datecreated) | Narrows the query results based on the products’ creation dates. +| [dateUpdated](#product-dateupdated) | Narrows the query results based on the products’ last-updated dates. +| [defaultHeight](#product-defaultheight) | Narrows the query results based on the products’ default variant height dimension IDs. +| [defaultLength](#product-defaultlength) | Narrows the query results based on the products’ default variant length dimension IDs. +| [defaultPrice](#product-defaultprice) | Narrows the query results based on the products’ default variant price. +| [defaultSku](#product-defaultsku) | Narrows the query results based on the default productvariants defaultSku +| [defaultWeight](#product-defaultweight) | Narrows the query results based on the products’ default variant weight dimension IDs. +| [defaultWidth](#product-defaultwidth) | Narrows the query results based on the products’ default variant width dimension IDs. +| [expiryDate](#product-expirydate) | Narrows the query results based on the products’ expiry dates. +| [fixedOrder](#product-fixedorder) | Causes the query results to be returned in the order specified by [id](#product-id). +| [hasVariant](#product-hasvariant) | Narrows the query results to only products that have certain variants. +| [id](#product-id) | Narrows the query results based on the products’ IDs. +| [ignorePlaceholders](#product-ignoreplaceholders) | Causes the query to return matching products as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#product-inreverse) | Causes the query results to be returned in reverse order. +| [limit](#product-limit) | Determines the number of products that should be returned. +| [offset](#product-offset) | Determines how many products should be skipped in the results. +| [orderBy](#product-orderby) | Determines the order that the products should be returned in. (If empty, defaults to `postDate DESC`.) +| [postDate](#product-postdate) | Narrows the query results based on the products’ post dates. +| [preferSites](#product-prefersites) | If [unique](#product-unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#product-preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [relatedTo](#product-relatedto) | Narrows the query results to only products that are related to certain other elements. +| [search](#product-search) | Narrows the query results to only products that match a search query. +| [shippingCategory](#product-shippingcategory) | Narrows the query results based on the products’ shipping category. +| [shippingCategoryId](#product-shippingcategoryid) | Narrows the query results based on the products’ shipping categories, per the shipping categories’ IDs. +| [site](#product-site) | Determines which site(s) the products should be queried in. +| [siteId](#product-siteid) | Determines which site(s) the products should be queried in, per the site’s ID. +| [siteSettingsId](#product-sitesettingsid) | Narrows the query results based on the products’ IDs in the `elements_sites` table. +| [slug](#product-slug) | Narrows the query results based on the products’ slugs. +| [status](#product-status) | Narrows the query results based on the products’ statuses. +| [taxCategory](#product-taxcategory) | Narrows the query results based on the products’ tax category. +| [taxCategoryId](#product-taxcategoryid) | Narrows the query results based on the products’ tax categories, per the tax categories’ IDs. +| [title](#product-title) | Narrows the query results based on the products’ titles. +| [trashed](#product-trashed) | Narrows the query results to only products that have been soft-deleted. +| [type](#product-type) | Narrows the query results based on the products’ types. +| [typeId](#product-typeid) | Narrows the query results based on the products’ types, per the types’ IDs. +| [uid](#product-uid) | Narrows the query results based on the products’ UIDs. +| [unique](#product-unique) | Determines whether only elements with unique IDs should be returned by the query. +| [uri](#product-uri) | Narrows the query results based on the products’ URIs. +| [with](#product-with) | Causes the query to return matching products eager-loaded with related elements. + + + + + +

# after

+ +Narrows the query results to only products that were posted on or after a certain date. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'2018-04-01'` | that were posted after 2018-04-01. +| a [DateTime](https://php.net/class.datetime) object | that were posted after the date represented by the object. + + + +::: code +```twig +{# Fetch products posted this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set products = craft.products() + .after(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch products posted this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$products = \craft\commerce\elements\Product::find() + ->after($firstDayOfMonth) + ->all(); +``` +::: + + +

# afterPopulate

+ +Performs any post-population processing on elements. + + + + + + + + + + +

# andRelatedTo

+ +Narrows the query results to only products that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all products that are related to myCategoryA and myCategoryB #} +{% set products = craft.products() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all products that are related to $myCategoryA and $myCategoryB +$products = \craft\commerce\elements\Product::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +

# asArray

+ +Causes the query to return matching products as arrays of data, rather than [Product](commerce4:craft\commerce\elements\Product) objects. + + + + + +::: code +```twig +{# Fetch products as arrays #} +{% set products = craft.products() + .asArray() + .all() %} +``` + +```php +// Fetch products as arrays +$products = \craft\commerce\elements\Product::find() + ->asArray() + ->all(); +``` +::: + + +

# availableForPurchase

+ +Narrows the query results to only products that are available for purchase. + + + +::: code +```twig +{# Fetch products that are available for purchase #} +{% set products = craft.products() + .availableForPurchase() + .all() %} +``` + +```php +// Fetch products that are available for purchase +$products = \craft\commerce\elements\Product::find() + ->availableForPurchase() + ->all(); +``` +::: + + +

# before

+ +Narrows the query results to only products that were posted before a certain date. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'2018-04-01'` | that were posted before 2018-04-01. +| a [DateTime](https://php.net/class.datetime) object | that were posted before the date represented by the object. + + + +::: code +```twig +{# Fetch products posted before this month #} +{% set firstDayOfMonth = date('first day of this month') %} + +{% set products = craft.products() + .before(firstDayOfMonth) + .all() %} +``` + +```php +// Fetch products posted before this month +$firstDayOfMonth = new \DateTime('first day of this month'); + +$products = \craft\commerce\elements\Product::find() + ->before($firstDayOfMonth) + ->all(); +``` +::: + + +

# cache

+ +Enables query cache for this Query. + + + + + + + + + + +

# clearCachedResult

+ +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +

# dateCreated

+ +Narrows the query results based on the products’ creation dates. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch products created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set products = craft.products() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch products created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +

# dateUpdated

+ +Narrows the query results based on the products’ last-updated dates. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch products updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set products = craft.products() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch products updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +

# defaultHeight

+ +Narrows the query results based on the products’ default variant height dimension IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with a dimension of 1. +| `'not 1'` | not a dimension of 1. +| `[1, 2]` | of a a dimension 1 or 2. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product default dimension of 1 #} +{% set products = craft.products() + .defaultHeight(1) + .all() %} +``` + +```php +// Fetch products of the product default dimension of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultHeight(1) + ->all(); +``` +::: + + +

# defaultLength

+ +Narrows the query results based on the products’ default variant length dimension IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with a dimension of 1. +| `'not 1'` | not a dimension of 1. +| `[1, 2]` | of a a dimension 1 or 2. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product default dimension of 1 #} +{% set products = craft.products() + .defaultLength(1) + .all() %} +``` + +```php +// Fetch products of the product default dimension of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultLength(1) + ->all(); +``` +::: + + +

# defaultPrice

+ +Narrows the query results based on the products’ default variant price. + +Possible values include: + +| Value | Fetches products… +| - | - +| `10` | of a price of 10. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a default variant price between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product type with an ID of 1 #} +{% set products = craft.products() + .defaultPrice(1) + .all() %} +``` + +```php +// Fetch products of the product type with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultPrice(1) + ->all(); +``` +::: + + +

# defaultSku

+ +Narrows the query results based on the default productvariants defaultSku + +Possible values include: + +| Value | Fetches products… +| - | - +| `xxx-001` | of products default SKU of `xxx-001`. +| `'not xxx-001'` | not a default SKU of `xxx-001`. +| `['not xxx-001', 'not xxx-002']` | of a default SKU of xxx-001 or xxx-002. +| `['not', `xxx-001`, `xxx-002`]` | not a product default SKU of `xxx-001` or `xxx-001`. + + + +::: code +```twig +{# Fetch products of the product default SKU of `xxx-001` #} +{% set products = craft.products() + .defaultSku('xxx-001') + .all() %} +``` + +```php +// Fetch products of the product default SKU of `xxx-001` +$products = \craft\commerce\elements\Product::find() + ->defaultSku('xxx-001') + ->all(); +``` +::: + + +

# defaultWeight

+ +Narrows the query results based on the products’ default variant weight dimension IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with a dimension of 1. +| `'not 1'` | not a dimension of 1. +| `[1, 2]` | of a a dimension 1 or 2. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product default dimension of 1 #} +{% set products = craft.products() + .defaultWeight(1) + .all() %} +``` + +```php +// Fetch products of the product default dimension of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultWeight(1) + ->all(); +``` +::: + + +

# defaultWidth

+ +Narrows the query results based on the products’ default variant width dimension IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with a dimension of 1. +| `'not 1'` | not a dimension of 1. +| `[1, 2]` | of a a dimension 1 or 2. +| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 + + + +::: code +```twig +{# Fetch products of the product default dimension of 1 #} +{% set products = craft.products() + .defaultWidth(1) + .all() %} +``` + +```php +// Fetch products of the product default dimension of 1 +$products = \craft\commerce\elements\Product::find() + ->defaultWidth(1) + ->all(); +``` +::: + + +

# expiryDate

+ +Narrows the query results based on the products’ expiry dates. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. +| `'< 2020-05-01'` | that will expire before 2020-05-01 +| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. + + + +::: code +```twig +{# Fetch products expiring this month #} +{% set nextMonth = date('first day of next month')|atom %} + +{% set products = craft.products() + .expiryDate("< #{nextMonth}") + .all() %} +``` + +```php +// Fetch products expiring this month +$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->expiryDate("< {$nextMonth}") + ->all(); +``` +::: + + +

# fixedOrder

+ +Causes the query results to be returned in the order specified by [id](#product-id). + + + +::: tip +If no IDs were passed to [id](#product-id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch products in a specific order #} +{% set products = craft.products() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch products in a specific order +$products = \craft\commerce\elements\Product::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +

# hasVariant

+ +Narrows the query results to only products that have certain variants. + +Possible values include: + +| Value | Fetches products… +| - | - +| a [VariantQuery](commerce4:craft\commerce\elements\db\VariantQuery) object | with variants that match the query. + + + + +

# id

+ +Narrows the query results based on the products’ IDs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the product by its ID #} +{% set product = craft.products() + .id(1) + .one() %} +``` + +```php +// Fetch the product by its ID +$product = \craft\commerce\elements\Product::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#product-fixedorder) if you want the results to be returned in a specific order. +::: + + +

# ignorePlaceholders

+ +Causes the query to return matching products as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +

# inReverse

+ +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch products in reverse #} +{% set products = craft.products() + .inReverse() + .all() %} +``` + +```php +// Fetch products in reverse +$products = \craft\commerce\elements\Product::find() + ->inReverse() + ->all(); +``` +::: + + +

# limit

+ +Determines the number of products that should be returned. + + + +::: code +```twig +{# Fetch up to 10 products #} +{% set products = craft.products() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 products +$products = \craft\commerce\elements\Product::find() + ->limit(10) + ->all(); +``` +::: + + +

# offset

+ +Determines how many products should be skipped in the results. + + + +::: code +```twig +{# Fetch all products except for the first 3 #} +{% set products = craft.products() + .offset(3) + .all() %} +``` + +```php +// Fetch all products except for the first 3 +$products = \craft\commerce\elements\Product::find() + ->offset(3) + ->all(); +``` +::: + + +

# orderBy

+ +Determines the order that the products should be returned in. (If empty, defaults to `postDate DESC`.) + + + +::: code +```twig +{# Fetch all products in order of date created #} +{% set products = craft.products() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all products in order of date created +$products = \craft\commerce\elements\Product::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +

# postDate

+ +Narrows the query results based on the products’ post dates. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. +| `'< 2018-05-01'` | that were posted before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch products posted last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set products = craft.products() + .postDate(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch products posted last month +$start = new \DateTime('first day of next month')->format(\DateTime::ATOM); +$end = new \DateTime('first day of this month')->format(\DateTime::ATOM); + +$products = \craft\commerce\elements\Product::find() + ->postDate(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +

# preferSites

+ +If [unique](#product-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique products from Site A, or Site B if they don’t exist in Site A #} +{% set products = craft.products() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique products from Site A, or Site B if they don’t exist in Site A +$products = \craft\commerce\elements\Product::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +

# prepareSubquery

+ +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +

# relatedTo

+ +Narrows the query results to only products that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all products that are related to myCategory #} +{% set products = craft.products() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all products that are related to $myCategory +$products = \craft\commerce\elements\Product::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + + + +Narrows the query results to only products that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all products that match the search query #} +{% set products = craft.products() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all products that match the search query +$products = \craft\commerce\elements\Product::find() + ->search($searchQuery) + ->all(); +``` +::: + + +

# shippingCategory

+ +Narrows the query results based on the products’ shipping category. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | of a shipping category with a handle of `foo`. +| `'not foo'` | not of a shipping category with a handle of `foo`. +| `['foo', 'bar']` | of a shipping category with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a shipping category with a handle of `foo` or `bar`. +| an [ShippingCategory](commerce4:craft\commerce\models\ShippingCategory) object | of a shipping category represented by the object. + + + +::: code +```twig +{# Fetch products with a Foo shipping category #} +{% set products = craft.products() + .shippingCategory('foo') + .all() %} +``` + +```php +// Fetch products with a Foo shipping category +$products = \craft\commerce\elements\Product::find() + ->shippingCategory('foo') + ->all(); +``` +::: + + +

# shippingCategoryId

+ +Narrows the query results based on the products’ shipping categories, per the shipping categories’ IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a shipping category with an ID of 1. +| `'not 1'` | not of a shipping category with an ID of 1. +| `[1, 2]` | of a shipping category with an ID of 1 or 2. +| `['not', 1, 2]` | not of a shipping category with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch products of the shipping category with an ID of 1 #} +{% set products = craft.products() + .shippingCategoryId(1) + .all() %} +``` + +```php +// Fetch products of the shipping category with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->shippingCategoryId(1) + ->all(); +``` +::: + + +

# site

+ +Determines which site(s) the products should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](https://docs.craftcms.com/api/v4/craft-models-site.html) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#product-unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch products from the Foo site #} +{% set products = craft.products() + .site('foo') + .all() %} +``` + +```php +// Fetch products from the Foo site +$products = \craft\commerce\elements\Product::find() + ->site('foo') + ->all(); +``` +::: + + +

# siteId

+ +Determines which site(s) the products should be queried in, per the site’s ID. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | from the site with an ID of `1`. +| `[1, 2]` | from a site with an ID of `1` or `2`. +| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. +| `'*'` | from any site. + + + +::: code +```twig +{# Fetch products from the site with an ID of 1 #} +{% set products = craft.products() + .siteId(1) + .all() %} +``` + +```php +// Fetch products from the site with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->siteId(1) + ->all(); +``` +::: + + +

# siteSettingsId

+ +Narrows the query results based on the products’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the product by its ID in the elements_sites table #} +{% set product = craft.products() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the product by its ID in the elements_sites table +$product = \craft\commerce\elements\Product::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +

# slug

+ +Narrows the query results based on the products’ slugs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | with a slug of `foo`. +| `'foo*'` | with a slug that begins with `foo`. +| `'*foo'` | with a slug that ends with `foo`. +| `'*foo*'` | with a slug that contains `foo`. +| `'not *foo*'` | with a slug that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested product slug from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the product with that slug #} +{% set product = craft.products() + .slug(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested product slug from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the product with that slug +$product = \craft\commerce\elements\Product::find() + ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +

# status

+ +Narrows the query results based on the products’ statuses. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'live'` _(default)_ | that are live. +| `'pending'` | that are pending (enabled with a Post Date in the future). +| `'expired'` | that are expired (enabled with an Expiry Date in the past). +| `'disabled'` | that are disabled. +| `['live', 'pending']` | that are live or pending. + + + +::: code +```twig +{# Fetch disabled products #} +{% set products = craft.products() + .status('disabled') + .all() %} +``` + +```php +// Fetch disabled products +$products = \craft\commerce\elements\Product::find() + ->status('disabled') + ->all(); +``` +::: + + +

# taxCategory

+ +Narrows the query results based on the products’ tax category. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | of a tax category with a handle of `foo`. +| `'not foo'` | not of a tax category with a handle of `foo`. +| `['foo', 'bar']` | of a tax category with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a tax category with a handle of `foo` or `bar`. +| an [ShippingCategory](commerce4:craft\commerce\models\ShippingCategory) object | of a tax category represented by the object. + + + +::: code +```twig +{# Fetch products with a Foo tax category #} +{% set products = craft.products() + .taxCategory('foo') + .all() %} +``` + +```php +// Fetch products with a Foo tax category +$products = \craft\commerce\elements\Product::find() + ->taxCategory('foo') + ->all(); +``` +::: + + +

# taxCategoryId

+ +Narrows the query results based on the products’ tax categories, per the tax categories’ IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a tax category with an ID of 1. +| `'not 1'` | not of a tax category with an ID of 1. +| `[1, 2]` | of a tax category with an ID of 1 or 2. +| `['not', 1, 2]` | not of a tax category with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch products of the tax category with an ID of 1 #} +{% set products = craft.products() + .taxCategoryId(1) + .all() %} +``` + +```php +// Fetch products of the tax category with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->taxCategoryId(1) + ->all(); +``` +::: + + +

# title

+ +Narrows the query results based on the products’ titles. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch products with a title that contains "Foo" #} +{% set products = craft.products() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch products with a title that contains "Foo" +$products = \craft\commerce\elements\Product::find() + ->title('*Foo*') + ->all(); +``` +::: + + +

# trashed

+ +Narrows the query results to only products that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed products #} +{% set products = craft.products() + .trashed() + .all() %} +``` + +```php +// Fetch trashed products +$products = \craft\commerce\elements\Product::find() + ->trashed() + ->all(); +``` +::: + + +

# type

+ +Narrows the query results based on the products’ types. + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | of a type with a handle of `foo`. +| `'not foo'` | not of a type with a handle of `foo`. +| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. +| an [ProductType](commerce4:craft\commerce\models\ProductType) object | of a type represented by the object. + + + +::: code +```twig +{# Fetch products with a Foo product type #} +{% set products = craft.products() + .type('foo') + .all() %} +``` + +```php +// Fetch products with a Foo product type +$products = \craft\commerce\elements\Product::find() + ->type('foo') + ->all(); +``` +::: + + +

# typeId

+ +Narrows the query results based on the products’ types, per the types’ IDs. + +Possible values include: + +| Value | Fetches products… +| - | - +| `1` | of a type with an ID of 1. +| `'not 1'` | not of a type with an ID of 1. +| `[1, 2]` | of a type with an ID of 1 or 2. +| `['not', 1, 2]` | not of a type with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch products of the product type with an ID of 1 #} +{% set products = craft.products() + .typeId(1) + .all() %} +``` + +```php +// Fetch products of the product type with an ID of 1 +$products = \craft\commerce\elements\Product::find() + ->typeId(1) + ->all(); +``` +::: + + +

# uid

+ +Narrows the query results based on the products’ UIDs. + + + + + +::: code +```twig +{# Fetch the product by its UID #} +{% set product = craft.products() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the product by its UID +$product = \craft\commerce\elements\Product::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +

# unique

+ +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique products across all sites #} +{% set products = craft.products() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique products across all sites +$products = \craft\commerce\elements\Product::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +

# uri

+ +Narrows the query results based on the products’ URIs. + + + +Possible values include: + +| Value | Fetches products… +| - | - +| `'foo'` | with a URI of `foo`. +| `'foo*'` | with a URI that begins with `foo`. +| `'*foo'` | with a URI that ends with `foo`. +| `'*foo*'` | with a URI that contains `foo`. +| `'not *foo*'` | with a URI that doesn’t contain `foo`. +| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested URI #} +{% set requestedUri = craft.app.request.getPathInfo() %} + +{# Fetch the product with that URI #} +{% set product = craft.products() + .uri(requestedUri|literal) + .one() %} +``` + +```php +// Get the requested URI +$requestedUri = \Craft::$app->request->getPathInfo(); + +// Fetch the product with that URI +$product = \craft\commerce\elements\Product::find() + ->uri(\craft\helpers\Db::escapeParam($requestedUri)) + ->one(); +``` +::: + + +

# with

+ +Causes the query to return matching products eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch products eager-loaded with the "Related" field’s relations #} +{% set products = craft.products() + .with(['related']) + .all() %} +``` + +```php +// Fetch products eager-loaded with the "Related" field’s relations +$products = \craft\commerce\elements\Product::find() + ->with(['related']) + ->all(); +``` +::: + + + + + +## Variants + +A variant describes the individual properties of a product as an item that may be purchased. + +Those properties inclue a SKU, price, and dimensions. Even if a product doesn’t appear to have any variants in the control panel, it still uses one *default variant* behind the scenes. + +Let’s compare examples of a single-variant an multi-variant product: a paperback book and a t-shirt. + +A book sold in only one format does not have meaningful variations for the customer to choose, but it would still have a specific SKU, price, weight, and dimensions. A single, implicit default variant needs to exist and that’s what would be added to the cart. + +A t-shirt, on the other hand, would have at least one variant for each available color and size combination. You wouldn’t sell the t-shirt without a specific color and size, so multiple variants would be necessary. If the shirt came in “small” and “large” sizes and “red” or “blue” colors, four unique variants could exist: + +- small, red +- small, blue +- large, red +- large, blue + +### Variant Properties + +Each variant includes the following unique properties: + +| Property | Type | Required? | +| ------------- | ------------------- | -------------- | +| SKU | string | | +| Price | number | | +| Stock | number or unlimited | | +| Allowed Qty | range | | +| Dimensions | number (l × w × h) | | +| Weight | number | | +| Related Sales | relationship (Sale) | | + +Each variant may also have any number of custom fields to allow other distinguishing traits. + +Commerce does not automatically create every possible unique variant for you—that’s up to the store manager. + +### Default Variant + +Every product has a default variant. Whenever a product is created, a default variant will be created as well. + +If a product type has multiple variants enabled, the author can choose which one should be used by default. Products that do not have multiple variants still have a default variant, but the author can’t add additional variants. + +For a single-variant product, variant details are shown in a unified view with custom product fields: + +![Stylized illustration of a single-variant product edit page, with custom product fields in a single content pane and fields like SKU in the sidebar details](./images/single-variant.png) + +When a product supports multiple variants, the default variant will be identified in a **Variants** field where more variants can be added: + +![Stylized illustration of a multi-variant product edit page, with an additional “Variants” tab that has a Matrix-like editor for multiple variants each having their own fields like SKU](./images/multi-variant.png) + +### Variant Stock + +Variants can have unlimited stock or a specific quantity. + +A finite stock amount will automatically be reduced whenever someone completes an order, until the stock amount reaches zero. At that point the variant’s “Available for purchase” setting won’t be changed, but zero-stock variants cannot be added to a cart. + +For returns or refunds that aren’t ultimately delivered to the customer, you’ll need to either manually update product stock or use [the `orderStatusChange` event](extend/events.md#orderstatuschange) to automate further stock adjustments. + +## Querying Variants + +You can fetch variants using **variant queries**. + +::: code +```twig +{# Create a new variant query #} +{% set myVariantQuery = craft.variants() %} +``` +```php +// Create a new variant query +$myVariantQuery = \craft\commerce\elements\Variant::find(); +``` +```graphql +# Create a new variant query +{ + variants { + # ... + } +} +``` +::: + +Once you’ve created a variant query, you can set [parameters](#variant-query-parameters) on it to narrow down the results, and then [execute it](https://craftcms.com/docs/4.x/element-queries.html#executing-element-queries) by calling `.all()`. An array of [Variant](commerce4:craft\commerce\elements\Variant) objects will be returned. + +You can also fetch only the number of items a query might return, which is better for performance when you don’t need the variant data. + +::: code +```twig +{# Count all enabled variants #} +{% set myVariantCount = craft.variants() + .status('enabled') + .count() %} +``` +```php +use craft\commerce\elements\Variant; + +// Count all enabled variants +$myVariantCount = Variant::find() + ->status(Variant::STATUS_ENABLED) + ->count(); +``` +```graphql +# Count all enabled variants +{ + variantCount(status: "enabled") +} +``` +::: + +::: tip +See [Element Queries](https://craftcms.com/docs/4.x/element-queries.html) in the Craft docs to learn about how element queries work. +::: + +### Example + +We can display a specific variant by its ID in Twig by doing the following: + +1. Create a variant query with `craft.variants()`. +2. Set the [`id`](#id) parameter on it. +3. Fetch the variant with `.one()`. +4. Output information about the variant as HTML. + +```twig +{# Get the requested variant ID from the query string #} +{% set variantId = craft.app.request.getQueryParam('id') %} + +{# Create a variant query with the 'id' parameter #} +{% set myVariantQuery = craft.variants() + .id(variantId) %} + +{# Fetch the variant #} +{% set variant = myVariantQuery.one() %} + +{# Make sure it exists #} +{% if not variant %} + {% exit 404 %} +{% endif %} + +{# Display the variant #} +

{{ variant.title }}

+ +``` + +Fetching the equivalent with GraphQL could look like this: + +```graphql +# Fetch variant having ID = 46 +{ + variants(id: 46) { + title + } +} +``` + +## Variant Query Parameters + +Variant queries support the following parameters: + + + + + + + +| Param | Description +| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#variant-afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#variant-andrelatedto) | Narrows the query results to only variants that are related to certain other elements. +| [asArray](#variant-asarray) | Causes the query to return matching variants as arrays of data, rather than [Variant](commerce4:craft\commerce\elements\Variant) objects. +| [cache](#variant-cache) | Enables query cache for this Query. +| [clearCachedResult](#variant-clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [dateCreated](#variant-datecreated) | Narrows the query results based on the variants’ creation dates. +| [dateUpdated](#variant-dateupdated) | Narrows the query results based on the variants’ last-updated dates. +| [fixedOrder](#variant-fixedorder) | Causes the query results to be returned in the order specified by [id](#variant-id). +| [hasProduct](#variant-hasproduct) | Narrows the query results to only variants for certain products. +| [hasSales](#variant-hassales) | Narrows the query results to only variants that are on sale. +| [hasStock](#variant-hasstock) | Narrows the query results to only variants that have stock. +| [hasUnlimitedStock](#variant-hasunlimitedstock) | Narrows the query results to only variants that have been set to unlimited stock. +| [height](#variant-height) | Narrows the query results based on the variants’ height dimension. +| [id](#variant-id) | Narrows the query results based on the variants’ IDs. +| [ignorePlaceholders](#variant-ignoreplaceholders) | Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#variant-inreverse) | Causes the query results to be returned in reverse order. +| [isDefault](#variant-isdefault) | Narrows the query results to only default variants. +| [length](#variant-length) | Narrows the query results based on the variants’ length dimension. +| [limit](#variant-limit) | Determines the number of variants that should be returned. +| [maxQty](#variant-maxqty) | Narrows the query results based on the variants’ max quantity. +| [minQty](#variant-minqty) | Narrows the query results based on the variants’ min quantity. +| [offset](#variant-offset) | Determines how many variants should be skipped in the results. +| [orderBy](#variant-orderby) | Determines the order that the variants should be returned in. (If empty, defaults to `sortOrder ASC`.) +| [preferSites](#variant-prefersites) | If [unique](#variant-unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#variant-preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [price](#variant-price) | Narrows the query results based on the variants’ price. +| [product](#variant-product) | Narrows the query results based on the variants’ product. +| [productId](#variant-productid) | Narrows the query results based on the variants’ products’ IDs. +| [relatedTo](#variant-relatedto) | Narrows the query results to only variants that are related to certain other elements. +| [search](#variant-search) | Narrows the query results to only variants that match a search query. +| [site](#variant-site) | Determines which site(s) the variants should be queried in. +| [siteId](#variant-siteid) | +| [siteSettingsId](#variant-sitesettingsid) | Narrows the query results based on the variants’ IDs in the `elements_sites` table. +| [sku](#variant-sku) | Narrows the query results based on the variants’ SKUs. +| [status](#variant-status) | +| [stock](#variant-stock) | Narrows the query results based on the variants’ stock. +| [title](#variant-title) | Narrows the query results based on the variants’ titles. +| [trashed](#variant-trashed) | Narrows the query results to only variants that have been soft-deleted. +| [typeId](#variant-typeid) | Narrows the query results based on the variants’ product types, per their IDs. +| [uid](#variant-uid) | Narrows the query results based on the variants’ UIDs. +| [unique](#variant-unique) | Determines whether only elements with unique IDs should be returned by the query. +| [weight](#variant-weight) | Narrows the query results based on the variants’ weight dimension. +| [width](#variant-width) | Narrows the query results based on the variants’ width dimension. +| [with](#variant-with) | Causes the query to return matching variants eager-loaded with related elements. + + + + + +

# afterPopulate

+ +Performs any post-population processing on elements. + + + + + + + + + + +

# andRelatedTo

+ +Narrows the query results to only variants that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all variants that are related to myCategoryA and myCategoryB #} +{% set variants = craft.variants() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all variants that are related to $myCategoryA and $myCategoryB +$variants = \craft\commerce\elements\Variant::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +

# asArray

+ +Causes the query to return matching variants as arrays of data, rather than [Variant](commerce4:craft\commerce\elements\Variant) objects. + + + + + +::: code +```twig +{# Fetch variants as arrays #} +{% set variants = craft.variants() + .asArray() + .all() %} +``` + +```php +// Fetch variants as arrays +$variants = \craft\commerce\elements\Variant::find() + ->asArray() + ->all(); +``` +::: + + +

# cache

+ +Enables query cache for this Query. + + + + + + + + + + +

# clearCachedResult

+ +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +

# dateCreated

+ +Narrows the query results based on the variants’ creation dates. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch variants created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set variants = craft.variants() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch variants created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$variants = \craft\commerce\elements\Variant::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +

# dateUpdated

+ +Narrows the query results based on the variants’ last-updated dates. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch variants updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set variants = craft.variants() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch variants updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$variants = \craft\commerce\elements\Variant::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +

# fixedOrder

+ +Causes the query results to be returned in the order specified by [id](#variant-id). + + + +::: tip +If no IDs were passed to [id](#variant-id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch variants in a specific order #} +{% set variants = craft.variants() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch variants in a specific order +$variants = \craft\commerce\elements\Variant::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +

# hasProduct

+ +Narrows the query results to only variants for certain products. + +Possible values include: + +| Value | Fetches variants… +| - | - +| a [ProductQuery](commerce4:craft\commerce\elements\db\ProductQuery) object | for products that match the query. + + + + +

# hasSales

+ +Narrows the query results to only variants that are on sale. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `true` | on sale +| `false` | not on sale + + + + +

# hasStock

+ +Narrows the query results to only variants that have stock. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `true` | with stock. +| `false` | with no stock. + + + + +

# hasUnlimitedStock

+ +Narrows the query results to only variants that have been set to unlimited stock. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `true` | with unlimited stock checked. +| `false` | with unlimited stock not checked. + + + + +

# height

+ +Narrows the query results based on the variants’ height dimension. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a height of 100. +| `'>= 100'` | with a height of at least 100. +| `'< 100'` | with a height of less than 100. + + + + +

# id

+ +Narrows the query results based on the variants’ IDs. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the variant by its ID #} +{% set variant = craft.variants() + .id(1) + .one() %} +``` + +```php +// Fetch the variant by its ID +$variant = \craft\commerce\elements\Variant::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#variant-fixedorder) if you want the results to be returned in a specific order. +::: + + +

# ignorePlaceholders

+ +Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +

# inReverse

+ +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch variants in reverse #} +{% set variants = craft.variants() + .inReverse() + .all() %} +``` + +```php +// Fetch variants in reverse +$variants = \craft\commerce\elements\Variant::find() + ->inReverse() + ->all(); +``` +::: + + +

# isDefault

+ +Narrows the query results to only default variants. + + + +::: code +```twig +{# Fetch default variants #} +{% set variants = craft.variants() + .isDefault() + .all() %} +``` + +```php +// Fetch default variants +$variants = \craft\commerce\elements\Variant::find() + ->isDefault() + ->all(); +``` +::: + + +

# length

+ +Narrows the query results based on the variants’ length dimension. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a length of 100. +| `'>= 100'` | with a length of at least 100. +| `'< 100'` | with a length of less than 100. + + + + +

# limit

+ +Determines the number of variants that should be returned. + + + +::: code +```twig +{# Fetch up to 10 variants #} +{% set variants = craft.variants() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 variants +$variants = \craft\commerce\elements\Variant::find() + ->limit(10) + ->all(); +``` +::: + + +

# maxQty

+ +Narrows the query results based on the variants’ max quantity. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a maxQty of 100. +| `'>= 100'` | with a maxQty of at least 100. +| `'< 100'` | with a maxQty of less than 100. + + + + +

# minQty

+ +Narrows the query results based on the variants’ min quantity. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a minQty of 100. +| `'>= 100'` | with a minQty of at least 100. +| `'< 100'` | with a minQty of less than 100. + + + + +

# offset

+ +Determines how many variants should be skipped in the results. + + + +::: code +```twig +{# Fetch all variants except for the first 3 #} +{% set variants = craft.variants() + .offset(3) + .all() %} +``` + +```php +// Fetch all variants except for the first 3 +$variants = \craft\commerce\elements\Variant::find() + ->offset(3) + ->all(); +``` +::: + + +

# orderBy

+ +Determines the order that the variants should be returned in. (If empty, defaults to `sortOrder ASC`.) + + + +::: code +```twig +{# Fetch all variants in order of date created #} +{% set variants = craft.variants() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all variants in order of date created +$variants = \craft\commerce\elements\Variant::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +

# preferSites

+ +If [unique](#variant-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique variants from Site A, or Site B if they don’t exist in Site A #} +{% set variants = craft.variants() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique variants from Site A, or Site B if they don’t exist in Site A +$variants = \craft\commerce\elements\Variant::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +

# prepareSubquery

+ +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +

# price

+ +Narrows the query results based on the variants’ price. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a price of 100. +| `'>= 100'` | with a price of at least 100. +| `'< 100'` | with a price of less than 100. + + + + +

# product

+ +Narrows the query results based on the variants’ product. + +Possible values include: + +| Value | Fetches variants… +| - | - +| a [Product](commerce4:craft\commerce\elements\Product) object | for a product represented by the object. + + + + +

# productId

+ +Narrows the query results based on the variants’ products’ IDs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | for a product with an ID of 1. +| `[1, 2]` | for product with an ID of 1 or 2. +| `['not', 1, 2]` | for product not with an ID of 1 or 2. + + + + +

# relatedTo

+ +Narrows the query results to only variants that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all variants that are related to myCategory #} +{% set variants = craft.variants() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all variants that are related to $myCategory +$variants = \craft\commerce\elements\Variant::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + + + +Narrows the query results to only variants that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all variants that match the search query #} +{% set variants = craft.variants() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all variants that match the search query +$variants = \craft\commerce\elements\Variant::find() + ->search($searchQuery) + ->all(); +``` +::: + + +

# site

+ +Determines which site(s) the variants should be queried in. + + + +The current site will be used by default. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'foo'` | from the site with a handle of `foo`. +| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. +| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. +| a [craft\models\Site](https://docs.craftcms.com/api/v4/craft-models-site.html) object | from the site represented by the object. +| `'*'` | from any site. + +::: tip +If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you +only want unique elements to be returned, use [unique](#variant-unique) in conjunction with this. +::: + + + +::: code +```twig +{# Fetch variants from the Foo site #} +{% set variants = craft.variants() + .site('foo') + .all() %} +``` + +```php +// Fetch variants from the Foo site +$variants = \craft\commerce\elements\Variant::find() + ->site('foo') + ->all(); +``` +::: + + +

# siteId

+ + + + + + + + +

# siteSettingsId

+ +Narrows the query results based on the variants’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the variant by its ID in the elements_sites table #} +{% set variant = craft.variants() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the variant by its ID in the elements_sites table +$variant = \craft\commerce\elements\Variant::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +

# sku

+ +Narrows the query results based on the variants’ SKUs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'foo'` | with a SKU of `foo`. +| `'foo*'` | with a SKU that begins with `foo`. +| `'*foo'` | with a SKU that ends with `foo`. +| `'*foo*'` | with a SKU that contains `foo`. +| `'not *foo*'` | with a SKU that doesn’t contain `foo`. +| `['*foo*', '*bar*'` | with a SKU that contains `foo` or `bar`. +| `['not', '*foo*', '*bar*']` | with a SKU that doesn’t contain `foo` or `bar`. + + + +::: code +```twig +{# Get the requested variant SKU from the URL #} +{% set requestedSlug = craft.app.request.getSegment(3) %} + +{# Fetch the variant with that slug #} +{% set variant = craft.variants() + .sku(requestedSlug|literal) + .one() %} +``` + +```php +// Get the requested variant SKU from the URL +$requestedSlug = \Craft::$app->request->getSegment(3); + +// Fetch the variant with that slug +$variant = \craft\commerce\elements\Variant::find() + ->sku(\craft\helpers\Db::escapeParam($requestedSlug)) + ->one(); +``` +::: + + +

# status

+ + + + + + + + +

# stock

+ +Narrows the query results based on the variants’ stock. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `0` | with no stock. +| `'>= 5'` | with a stock of at least 5. +| `'< 10'` | with a stock of less than 10. + + + + +

# title

+ +Narrows the query results based on the variants’ titles. + + + +Possible values include: + +| Value | Fetches variants… +| - | - +| `'Foo'` | with a title of `Foo`. +| `'Foo*'` | with a title that begins with `Foo`. +| `'*Foo'` | with a title that ends with `Foo`. +| `'*Foo*'` | with a title that contains `Foo`. +| `'not *Foo*'` | with a title that doesn’t contain `Foo`. +| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. +| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. + + + +::: code +```twig +{# Fetch variants with a title that contains "Foo" #} +{% set variants = craft.variants() + .title('*Foo*') + .all() %} +``` + +```php +// Fetch variants with a title that contains "Foo" +$variants = \craft\commerce\elements\Variant::find() + ->title('*Foo*') + ->all(); +``` +::: + + +

# trashed

+ +Narrows the query results to only variants that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed variants #} +{% set variants = craft.variants() + .trashed() + .all() %} +``` + +```php +// Fetch trashed variants +$variants = \craft\commerce\elements\Variant::find() + ->trashed() + ->all(); +``` +::: + + +

# typeId

+ +Narrows the query results based on the variants’ product types, per their IDs. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `1` | for a product of a type with an ID of 1. +| `[1, 2]` | for product of a type with an ID of 1 or 2. +| `['not', 1, 2]` | for product of a type not with an ID of 1 or 2. + + + + +

# uid

+ +Narrows the query results based on the variants’ UIDs. + + + + + +::: code +```twig +{# Fetch the variant by its UID #} +{% set variant = craft.variants() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the variant by its UID +$variant = \craft\commerce\elements\Variant::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +

# unique

+ +Determines whether only elements with unique IDs should be returned by the query. + + + +This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not +desired. + + + +::: code +```twig +{# Fetch unique variants across all sites #} +{% set variants = craft.variants() + .site('*') + .unique() + .all() %} +``` + +```php +// Fetch unique variants across all sites +$variants = \craft\commerce\elements\Variant::find() + ->site('*') + ->unique() + ->all(); +``` +::: + + +

# weight

+ +Narrows the query results based on the variants’ weight dimension. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a weight of 100. +| `'>= 100'` | with a weight of at least 100. +| `'< 100'` | with a weight of less than 100. + + + + +

# width

+ +Narrows the query results based on the variants’ width dimension. + +Possible values include: + +| Value | Fetches variants… +| - | - +| `100` | with a width of 100. +| `'>= 100'` | with a width of at least 100. +| `'< 100'` | with a width of less than 100. + + + + +

# with

+ +Causes the query to return matching variants eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch variants eager-loaded with the "Related" field’s relations #} +{% set variants = craft.variants() + .with(['related']) + .all() %} +``` + +```php +// Fetch variants eager-loaded with the "Related" field’s relations +$variants = \craft\commerce\elements\Variant::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/commerce/4.x/subscriptions.md b/docs/.artifacts/commerce/4.x/subscriptions.md new file mode 100644 index 000000000..a3c9d3430 --- /dev/null +++ b/docs/.artifacts/commerce/4.x/subscriptions.md @@ -0,0 +1,1062 @@ + + + + + + + + +| Param | Description +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. +| [andRelatedTo](#andrelatedto) | Narrows the query results to only subscriptions that are related to certain other elements. +| [asArray](#asarray) | Causes the query to return matching subscriptions as arrays of data, rather than [Subscription](commerce4:craft\commerce\elements\Subscription) objects. +| [cache](#cache) | Enables query cache for this Query. +| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). +| [dateCanceled](#datecanceled) | Narrows the query results based on the subscriptions’ cancellation date. +| [dateCreated](#datecreated) | Narrows the query results based on the subscriptions’ creation dates. +| [dateExpired](#dateexpired) | Narrows the query results based on the subscriptions’ expiration date. +| [dateSuspended](#datesuspended) | Narrows the query results based on the subscriptions’ suspension date. +| [dateUpdated](#dateupdated) | Narrows the query results based on the subscriptions’ last-updated dates. +| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). +| [gatewayId](#gatewayid) | Narrows the query results based on the gateway, per its ID. +| [hasStarted](#hasstarted) | Narrows the query results to only subscriptions that have started. +| [id](#id) | Narrows the query results based on the subscriptions’ IDs. +| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). +| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. +| [isCanceled](#iscanceled) | Narrows the query results to only subscriptions that are canceled. +| [isExpired](#isexpired) | Narrows the query results to only subscriptions that have expired. +| [isSuspended](#issuspended) | Narrows the query results to only subscriptions that are suspended. +| [limit](#limit) | Determines the number of subscriptions that should be returned. +| [nextPaymentDate](#nextpaymentdate) | Narrows the query results based on the subscriptions’ next payment dates. +| [offset](#offset) | Determines how many subscriptions should be skipped in the results. +| [onTrial](#ontrial) | Narrows the query results to only subscriptions that are on trial. +| [orderBy](#orderby) | Determines the order that the subscriptions should be returned in. (If empty, defaults to `dateCreated DESC`.) +| [orderId](#orderid) | Narrows the query results based on the order, per its ID. +| [plan](#plan) | Narrows the query results based on the subscription plan. +| [planId](#planid) | Narrows the query results based on the subscription plans’ IDs. +| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v4/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. +| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). +| [reference](#reference) | Narrows the query results based on the reference. +| [relatedTo](#relatedto) | Narrows the query results to only subscriptions that are related to certain other elements. +| [search](#search) | Narrows the query results to only subscriptions that match a search query. +| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the subscriptions’ IDs in the `elements_sites` table. +| [status](#status) | Narrows the query results based on the subscriptions’ statuses. +| [trashed](#trashed) | Narrows the query results to only subscriptions that have been soft-deleted. +| [trialDays](#trialdays) | Narrows the query results based on the number of trial days. +| [uid](#uid) | Narrows the query results based on the subscriptions’ UIDs. +| [user](#user) | Narrows the query results based on the subscriptions’ user accounts. +| [userId](#userid) | Narrows the query results based on the subscriptions’ user accounts’ IDs. +| [with](#with) | Causes the query to return matching subscriptions eager-loaded with related elements. + + + + + +#### `afterPopulate` + +Performs any post-population processing on elements. + + + + + + + + + + +#### `andRelatedTo` + +Narrows the query results to only subscriptions that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all subscriptions that are related to myCategoryA and myCategoryB #} +{% set subscriptions = craft.subscriptions() + .relatedTo(myCategoryA) + .andRelatedTo(myCategoryB) + .all() %} +``` + +```php +// Fetch all subscriptions that are related to $myCategoryA and $myCategoryB +$subscriptions = \craft\commerce\elements\Subscription::find() + ->relatedTo($myCategoryA) + ->andRelatedTo($myCategoryB) + ->all(); +``` +::: + + +#### `asArray` + +Causes the query to return matching subscriptions as arrays of data, rather than [Subscription](commerce4:craft\commerce\elements\Subscription) objects. + + + + + +::: code +```twig +{# Fetch subscriptions as arrays #} +{% set subscriptions = craft.subscriptions() + .asArray() + .all() %} +``` + +```php +// Fetch subscriptions as arrays +$subscriptions = \craft\commerce\elements\Subscription::find() + ->asArray() + ->all(); +``` +::: + + +#### `cache` + +Enables query cache for this Query. + + + + + + + + + + +#### `clearCachedResult` + +Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). + + + + + + +#### `dateCanceled` + +Narrows the query results based on the subscriptions’ cancellation date. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that were canceled on or after 2018-04-01. +| `'< 2018-05-01'` | that were canceled before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were canceled between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch subscriptions that were canceled recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateCanceled(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch subscriptions that were canceled recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateCanceled(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `dateCreated` + +Narrows the query results based on the subscriptions’ creation dates. + + + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that were created on or after 2018-04-01. +| `'< 2018-05-01'` | that were created before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch subscriptions created last month #} +{% set start = date('first day of last month')|atom %} +{% set end = date('first day of this month')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateCreated(['and', ">= #{start}", "< #{end}"]) + .all() %} +``` + +```php +// Fetch subscriptions created last month +$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); +$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateCreated(['and', ">= {$start}", "< {$end}"]) + ->all(); +``` +::: + + +#### `dateExpired` + +Narrows the query results based on the subscriptions’ expiration date. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that expired on or after 2018-04-01. +| `'< 2018-05-01'` | that expired before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that expired between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch subscriptions that expired recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateExpired(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch subscriptions that expired recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateExpired(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `dateSuspended` + +Narrows the query results based on the subscriptions’ suspension date. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that were suspended on or after 2018-04-01. +| `'< 2018-05-01'` | that were suspended before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were suspended between 2018-04-01 and 2018-05-01. + + +::: code +```twig +{# Fetch subscriptions that were suspended recently #} +{% set aWeekAgo = date('7 days ago')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateSuspended(">= #{aWeekAgo}") + .all() %} +``` + +```php +// Fetch subscriptions that were suspended recently +$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateSuspended(">= {$aWeekAgo}") + ->all(); +``` +::: + + +#### `dateUpdated` + +Narrows the query results based on the subscriptions’ last-updated dates. + + + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. +| `'< 2018-05-01'` | that were updated before 2018-05-01. +| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. +| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. + + + +::: code +```twig +{# Fetch subscriptions updated in the last week #} +{% set lastWeek = date('1 week ago')|atom %} + +{% set subscriptions = craft.subscriptions() + .dateUpdated(">= #{lastWeek}") + .all() %} +``` + +```php +// Fetch subscriptions updated in the last week +$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->dateUpdated(">= {$lastWeek}") + ->all(); +``` +::: + + +#### `fixedOrder` + +Causes the query results to be returned in the order specified by [id](#id). + + + +::: tip +If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. +::: + + + +::: code +```twig +{# Fetch subscriptions in a specific order #} +{% set subscriptions = craft.subscriptions() + .id([1, 2, 3, 4, 5]) + .fixedOrder() + .all() %} +``` + +```php +// Fetch subscriptions in a specific order +$subscriptions = \craft\commerce\elements\Subscription::find() + ->id([1, 2, 3, 4, 5]) + ->fixedOrder() + ->all(); +``` +::: + + +#### `gatewayId` + +Narrows the query results based on the gateway, per its ID. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | with a gateway with an ID of 1. +| `'not 1'` | not with a gateway with an ID of 1. +| `[1, 2]` | with a gateway with an ID of 1 or 2. +| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. + + + + +#### `hasStarted` + +Narrows the query results to only subscriptions that have started. + + + +::: code +```twig +{# Fetch started subscriptions #} +{% set subscriptions = craft.subscriptions() + .hasStarted() + .all() %} +``` + +```php +// Fetch started subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->hasStarted() + ->all(); +``` +::: + + +#### `id` + +Narrows the query results based on the subscriptions’ IDs. + + + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | with an ID of 1. +| `'not 1'` | not with an ID of 1. +| `[1, 2]` | with an ID of 1 or 2. +| `['not', 1, 2]` | not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the subscription by its ID #} +{% set subscription = craft.subscriptions() + .id(1) + .one() %} +``` + +```php +// Fetch the subscription by its ID +$subscription = \craft\commerce\elements\Subscription::find() + ->id(1) + ->one(); +``` +::: + + + +::: tip +This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. +::: + + +#### `ignorePlaceholders` + +Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder +elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). + + + + + + + + + + +#### `inReverse` + +Causes the query results to be returned in reverse order. + + + + + +::: code +```twig +{# Fetch subscriptions in reverse #} +{% set subscriptions = craft.subscriptions() + .inReverse() + .all() %} +``` + +```php +// Fetch subscriptions in reverse +$subscriptions = \craft\commerce\elements\Subscription::find() + ->inReverse() + ->all(); +``` +::: + + +#### `isCanceled` + +Narrows the query results to only subscriptions that are canceled. + + + +::: code +```twig +{# Fetch canceled subscriptions #} +{% set subscriptions = craft.subscriptions() + .isCanceled() + .all() %} +``` + +```php +// Fetch canceled subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->isCanceled() + ->all(); +``` +::: + + +#### `isExpired` + +Narrows the query results to only subscriptions that have expired. + + + +::: code +```twig +{# Fetch expired subscriptions #} +{% set subscriptions = craft.subscriptions() + .isExpired() + .all() %} +``` + +```php +// Fetch expired subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->isExpired() + ->all(); +``` +::: + + +#### `isSuspended` + +Narrows the query results to only subscriptions that are suspended. + + + +::: code +```twig +{# Fetch suspended subscriptions #} +{% set subscriptions = craft.subscriptions() + .isSuspended() + .all() %} +``` + +```php +// Fetch suspended subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->isSuspended() + ->all(); +``` +::: + + +#### `limit` + +Determines the number of subscriptions that should be returned. + + + +::: code +```twig +{# Fetch up to 10 subscriptions #} +{% set subscriptions = craft.subscriptions() + .limit(10) + .all() %} +``` + +```php +// Fetch up to 10 subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->limit(10) + ->all(); +``` +::: + + +#### `nextPaymentDate` + +Narrows the query results based on the subscriptions’ next payment dates. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'>= 2018-04-01'` | with a next payment on or after 2018-04-01. +| `'< 2018-05-01'` | with a next payment before 2018-05-01 +| `['and', '>= 2018-04-04', '< 2018-05-01']` | with a next payment between 2018-04-01 and 2018-05-01. + + + +::: code +```twig +{# Fetch subscriptions with a payment due soon #} +{% set aWeekFromNow = date('+7 days')|atom %} + +{% set subscriptions = craft.subscriptions() + .nextPaymentDate("< #{aWeekFromNow}") + .all() %} +``` + +```php +// Fetch subscriptions with a payment due soon +$aWeekFromNow = new \DateTime('+7 days')->format(\DateTime::ATOM); + +$subscriptions = \craft\commerce\elements\Subscription::find() + ->nextPaymentDate("< {$aWeekFromNow}") + ->all(); +``` +::: + + +#### `offset` + +Determines how many subscriptions should be skipped in the results. + + + +::: code +```twig +{# Fetch all subscriptions except for the first 3 #} +{% set subscriptions = craft.subscriptions() + .offset(3) + .all() %} +``` + +```php +// Fetch all subscriptions except for the first 3 +$subscriptions = \craft\commerce\elements\Subscription::find() + ->offset(3) + ->all(); +``` +::: + + +#### `onTrial` + +Narrows the query results to only subscriptions that are on trial. + + + +::: code +```twig +{# Fetch trialed subscriptions #} +{% set subscriptions = craft.subscriptions() + .onTrial() + .all() %} +``` + +```php +// Fetch trialed subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->isPaid() + ->all(); +``` +::: + + +#### `orderBy` + +Determines the order that the subscriptions should be returned in. (If empty, defaults to `dateCreated DESC`.) + + + +::: code +```twig +{# Fetch all subscriptions in order of date created #} +{% set subscriptions = craft.subscriptions() + .orderBy('dateCreated ASC') + .all() %} +``` + +```php +// Fetch all subscriptions in order of date created +$subscriptions = \craft\commerce\elements\Subscription::find() + ->orderBy('dateCreated ASC') + ->all(); +``` +::: + + +#### `orderId` + +Narrows the query results based on the order, per its ID. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | with an order with an ID of 1. +| `'not 1'` | not with an order with an ID of 1. +| `[1, 2]` | with an order with an ID of 1 or 2. +| `['not', 1, 2]` | not with an order with an ID of 1 or 2. + + + + +#### `plan` + +Narrows the query results based on the subscription plan. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'foo'` | for a plan with a handle of `foo`. +| `['foo', 'bar']` | for plans with a handle of `foo` or `bar`. +| a [Plan](commerce4:craft\commerce\base\Plan) object | for a plan represented by the object. + + + +::: code +```twig +{# Fetch Supporter plan subscriptions #} +{% set subscriptions = craft.subscriptions() + .plan('supporter') + .all() %} +``` + +```php +// Fetch Supporter plan subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->plan('supporter') + ->all(); +``` +::: + + +#### `planId` + +Narrows the query results based on the subscription plans’ IDs. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | for a plan with an ID of 1. +| `[1, 2]` | for plans with an ID of 1 or 2. +| `['not', 1, 2]` | for plans not with an ID of 1 or 2. + + + + +#### `preferSites` + +If [unique()](https://docs.craftcms.com/api/v4/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. + + + +For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, +and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned +for Site C. + +If this isn’t set, then preference goes to the current site. + + + +::: code +```twig +{# Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A #} +{% set subscriptions = craft.subscriptions() + .site('*') + .unique() + .preferSites(['a', 'b']) + .all() %} +``` + +```php +// Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A +$subscriptions = \craft\commerce\elements\Subscription::find() + ->site('*') + ->unique() + ->preferSites(['a', 'b']) + ->all(); +``` +::: + + +#### `prepareSubquery` + +Prepares the element query and returns its subquery (which determines what elements will be returned). + + + + + + +#### `reference` + +Narrows the query results based on the reference. + + + + + + +#### `relatedTo` + +Narrows the query results to only subscriptions that are related to certain other elements. + + + +See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch all subscriptions that are related to myCategory #} +{% set subscriptions = craft.subscriptions() + .relatedTo(myCategory) + .all() %} +``` + +```php +// Fetch all subscriptions that are related to $myCategory +$subscriptions = \craft\commerce\elements\Subscription::find() + ->relatedTo($myCategory) + ->all(); +``` +::: + + +#### `search` + +Narrows the query results to only subscriptions that match a search query. + + + +See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Get the search query from the 'q' query string param #} +{% set searchQuery = craft.app.request.getQueryParam('q') %} + +{# Fetch all subscriptions that match the search query #} +{% set subscriptions = craft.subscriptions() + .search(searchQuery) + .all() %} +``` + +```php +// Get the search query from the 'q' query string param +$searchQuery = \Craft::$app->request->getQueryParam('q'); + +// Fetch all subscriptions that match the search query +$subscriptions = \craft\commerce\elements\Subscription::find() + ->search($searchQuery) + ->all(); +``` +::: + + +#### `siteSettingsId` + +Narrows the query results based on the subscriptions’ IDs in the `elements_sites` table. + + + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | with an `elements_sites` ID of 1. +| `'not 1'` | not with an `elements_sites` ID of 1. +| `[1, 2]` | with an `elements_sites` ID of 1 or 2. +| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. + + + +::: code +```twig +{# Fetch the subscription by its ID in the elements_sites table #} +{% set subscription = craft.subscriptions() + .siteSettingsId(1) + .one() %} +``` + +```php +// Fetch the subscription by its ID in the elements_sites table +$subscription = \craft\commerce\elements\Subscription::find() + ->siteSettingsId(1) + ->one(); +``` +::: + + +#### `status` + +Narrows the query results based on the subscriptions’ statuses. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'active'` _(default)_ | that are active. +| `'expired'` | that have expired. + + + +::: code +```twig +{# Fetch expired subscriptions #} +{% set subscriptions = craft.subscriptions() + .status('expired') + .all() %} +``` + +```php +// Fetch expired subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->status('expired') + ->all(); +``` +::: + + +#### `trashed` + +Narrows the query results to only subscriptions that have been soft-deleted. + + + + + +::: code +```twig +{# Fetch trashed subscriptions #} +{% set subscriptions = craft.subscriptions() + .trashed() + .all() %} +``` + +```php +// Fetch trashed subscriptions +$subscriptions = \craft\commerce\elements\Subscription::find() + ->trashed() + ->all(); +``` +::: + + +#### `trialDays` + +Narrows the query results based on the number of trial days. + + + + + + +#### `uid` + +Narrows the query results based on the subscriptions’ UIDs. + + + + + +::: code +```twig +{# Fetch the subscription by its UID #} +{% set subscription = craft.subscriptions() + .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + .one() %} +``` + +```php +// Fetch the subscription by its UID +$subscription = \craft\commerce\elements\Subscription::find() + ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + ->one(); +``` +::: + + +#### `user` + +Narrows the query results based on the subscriptions’ user accounts. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `'foo'` | for a user account with a username of `foo` +| `['foo', 'bar']` | for user accounts with a username of `foo` or `bar`. +| a [User](https://docs.craftcms.com/api/v4/craft-elements-user.html) object | for a user account represented by the object. + + + +::: code +```twig +{# Fetch the current user's subscriptions #} +{% set subscriptions = craft.subscriptions() + .user(currentUser) + .all() %} +``` + +```php +// Fetch the current user's subscriptions +$user = Craft::$app->user->getIdentity(); +$subscriptions = \craft\commerce\elements\Subscription::find() + ->user($user) + ->all(); +``` +::: + + +#### `userId` + +Narrows the query results based on the subscriptions’ user accounts’ IDs. + +Possible values include: + +| Value | Fetches subscriptions… +| - | - +| `1` | for a user account with an ID of 1. +| `[1, 2]` | for user accounts with an ID of 1 or 2. +| `['not', 1, 2]` | for user accounts not with an ID of 1 or 2. + + + +::: code +```twig +{# Fetch the current user's subscriptions #} +{% set subscriptions = craft.subscriptions() + .userId(currentUser.id) + .all() %} +``` + +```php +// Fetch the current user's subscriptions +$user = Craft::$app->user->getIdentity(); +$subscriptions = \craft\commerce\elements\Subscription::find() + ->userId($user->id) + ->all(); +``` +::: + + +#### `with` + +Causes the query to return matching subscriptions eager-loaded with related elements. + + + +See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. + + + +::: code +```twig +{# Fetch subscriptions eager-loaded with the "Related" field’s relations #} +{% set subscriptions = craft.subscriptions() + .with(['related']) + .all() %} +``` + +```php +// Fetch subscriptions eager-loaded with the "Related" field’s relations +$subscriptions = \craft\commerce\elements\Subscription::find() + ->with(['related']) + ->all(); +``` +::: + + + + diff --git a/docs/.artifacts/include-template.md b/docs/.artifacts/include-template.md new file mode 100644 index 000000000..2c39bc685 --- /dev/null +++ b/docs/.artifacts/include-template.md @@ -0,0 +1 @@ + diff --git a/docs/.vuepress/components/Since.vue b/docs/.vuepress/components/Since.vue index f8d527b79..4fbaa0fea 100644 --- a/docs/.vuepress/components/Since.vue +++ b/docs/.vuepress/components/Since.vue @@ -2,7 +2,7 @@ {{ ver }}+ @@ -16,6 +16,10 @@ export default { components: {}, props: { ver: String, + product: { + type: String, + default: 'Craft', + }, useChangelog: { type: Boolean, default: true, @@ -28,6 +32,10 @@ export default { type: String, default: 'This feature', }, + description: { + type: String, + default: '{feature} was first available in version {ver} of {product}.', + } }, computed: { releaseUrl() { @@ -38,6 +46,12 @@ export default { return `${GITHUB_URL}/${this.repo}/releases/tag/${this.ver}`; }, + parsedDescription() { + return this.description + .replace('{feature}', this.feature) + .replace('{ver}', this.ver) + .replace('{product}', this.product); + } }, }; diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 7b3e00160..596a4be31 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -65,8 +65,8 @@ module.exports = { }, feedback: { helpful: "Was this page helpful?", - thanks: "Thanks for your feedback.", - more: "Give More Feedback →" + thanks: "Thanks for your feedback!", + more: "Report an Issue →" } }, markdown: { @@ -86,7 +86,8 @@ module.exports = { md.use(require("./theme/util/replace-anchor-prefixes").replacePrefixes) .use(require("./theme/markup")) .use(require("markdown-it-deflist")) - .use(require("markdown-it-imsize")); + .use(require("markdown-it-imsize")) + .use(require("markdown-it-include")); } }, postcss: { diff --git a/docs/.vuepress/sets/craft-cms.js b/docs/.vuepress/sets/craft-cms.js index ade8b2900..5797f1901 100644 --- a/docs/.vuepress/sets/craft-cms.js +++ b/docs/.vuepress/sets/craft-cms.js @@ -176,6 +176,7 @@ module.exports = { "categories-fields", "checkboxes-fields", "color-fields", + "country-fields", "date-time-fields", "dropdown-fields", "email-fields", diff --git a/docs/.vuepress/theme/components/EventBrowser.vue b/docs/.vuepress/theme/components/EventBrowser.vue index c9951c0bb..73a1812da 100644 --- a/docs/.vuepress/theme/components/EventBrowser.vue +++ b/docs/.vuepress/theme/components/EventBrowser.vue @@ -342,10 +342,10 @@ - - diff --git a/docs/.vuepress/theme/components/PageFooter.vue b/docs/.vuepress/theme/components/PageFooter.vue index 0bd078c8c..caf4492d3 100644 --- a/docs/.vuepress/theme/components/PageFooter.vue +++ b/docs/.vuepress/theme/components/PageFooter.vue @@ -1,165 +1,105 @@ @@ -267,9 +193,7 @@ export default { this.hasVoted = this.vote !== null; }, getIssueUrl() { - return encodeURI( - `https://github.com/${this.$themeConfig.docsRepo}/issues/new?title=Improve “${this.$page.title}”&body=I have a suggestion for https://craftcms.com/docs${this.$route.fullPath}:\n` - ); + return 'https://github.com/craftcms/docs/issues/new/choose'; }, }, watch: { diff --git a/docs/.vuepress/theme/components/SidebarLink.vue b/docs/.vuepress/theme/components/SidebarLink.vue index ce4bb8b06..9b8e197c7 100644 --- a/docs/.vuepress/theme/components/SidebarLink.vue +++ b/docs/.vuepress/theme/components/SidebarLink.vue @@ -60,6 +60,12 @@ export default { }; function renderLink(h, to, text, active, level) { + const hashPosition = to.indexOf('#'); + const path = to.substring(0, hashPosition > 0 ? hashPosition : to.length); + const segments = path.split('/'); + const lastSegment = segments[segments.length - 1]; + const handle = lastSegment.replace('.html', ''); + const component = { props: { to, @@ -69,6 +75,8 @@ function renderLink(h, to, text, active, level) { class: { active, "sidebar-link": true, + // Include a “slug” identifier when this isn't a jump link: + [`slug-${handle || 'root'}`]: hashPosition < 0, }, }; diff --git a/docs/3.x/assets.md b/docs/3.x/assets.md index b64dbda58..03a085c46 100644 --- a/docs/3.x/assets.md +++ b/docs/3.x/assets.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Assets You can manage your project’s media and document files (“assets”) in Craft just like entries and other content types. @@ -156,1238 +160,5 @@ You can cache-bust asset URLs automatically by enabling the [revAssetUrls](confi Asset queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only assets that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching assets as arrays of data, rather than [Asset](craft3:craft\elements\Asset) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#datecreated) | Narrows the query results based on the assets’ creation dates. -| [dateModified](#datemodified) | Narrows the query results based on the assets’ files’ last-modified dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the assets’ last-updated dates. -| [filename](#filename) | Narrows the query results based on the assets’ filenames. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [folderId](#folderid) | Narrows the query results based on the folders the assets belong to, per the folders’ IDs. -| [folderPath](#folderpath) | Narrows the query results based on the folders the assets belong to, per the folders’ paths. -| [height](#height) | Narrows the query results based on the assets’ image heights. -| [id](#id) | Narrows the query results based on the assets’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [includeSubfolders](#includesubfolders) | Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). -| [kind](#kind) | Narrows the query results based on the assets’ file kinds. -| [limit](#limit) | Determines the number of assets that should be returned. -| [offset](#offset) | Determines how many assets should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [relatedTo](#relatedto) | Narrows the query results to only assets that are related to certain other elements. -| [search](#search) | Narrows the query results to only assets that match a search query. -| [site](#site) | Determines which site(s) the assets should be queried in. -| [siteId](#siteid) | Determines which site(s) the assets should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the assets’ IDs in the `elements_sites` table. -| [size](#size) | Narrows the query results based on the assets’ file sizes (in bytes). -| [title](#title) | Narrows the query results based on the assets’ titles. -| [trashed](#trashed) | Narrows the query results to only assets that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the assets’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uploader](#uploader) | Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. -| [volume](#volume) | Narrows the query results based on the volume the assets belong to. -| [volumeId](#volumeid) | Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. -| [width](#width) | Narrows the query results based on the assets’ image widths. -| [with](#with) | Causes the query to return matching assets eager-loaded with related elements. -| [withTransforms](#withtransforms) | Causes the query to return matching assets eager-loaded with image transform indexes. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only assets that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all assets that are related to myCategoryA and myCategoryB #} -{% set assets = craft.assets() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all assets that are related to $myCategoryA and $myCategoryB -$assets = \craft\elements\Asset::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all assets, regardless of status #} -{% set assets = craft.assets() - .anyStatus() - .all() %} -``` - -```php -// Fetch all assets, regardless of status -$assets = \craft\elements\Asset::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching assets as arrays of data, rather than [Asset](craft3:craft\elements\Asset) objects. - - - - - -::: code -```twig -{# Fetch assets as arrays #} -{% set assets = craft.assets() - .asArray() - .all() %} -``` - -```php -// Fetch assets as arrays -$assets = \craft\elements\Asset::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `dateCreated` - -Narrows the query results based on the assets’ creation dates. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch assets created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set assets = craft.assets() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch assets created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$assets = \craft\elements\Asset::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateModified` - -Narrows the query results based on the assets’ files’ last-modified dates. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'>= 2018-04-01'` | that were modified on or after 2018-04-01. -| `'< 2018-05-01'` | that were modified before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were modified between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch assets modified in the last month #} -{% set start = date('30 days ago')|atom %} - -{% set assets = craft.assets() - .dateModified(">= #{start}") - .all() %} -``` - -```php -// Fetch assets modified in the last month -$start = (new \DateTime('30 days ago'))->format(\DateTime::ATOM); - -$assets = \craft\elements\Asset::find() - ->dateModified(">= {$start}") - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the assets’ last-updated dates. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch assets updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set assets = craft.assets() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch assets updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$assets = \craft\elements\Asset::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `filename` - -Narrows the query results based on the assets’ filenames. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'foo.jpg'` | with a filename of `foo.jpg`. -| `'foo*'` | with a filename that begins with `foo`. -| `'*.jpg'` | with a filename that ends with `.jpg`. -| `'*foo*'` | with a filename that contains `foo`. -| `'not *foo*'` | with a filename that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a filename that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a filename that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Fetch all the hi-res images #} -{% set assets = craft.assets() - .filename('*@2x*') - .all() %} -``` - -```php -// Fetch all the hi-res images -$assets = \craft\elements\Asset::find() - ->filename('*@2x*') - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch assets in a specific order #} -{% set assets = craft.assets() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch assets in a specific order -$assets = \craft\elements\Asset::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `folderId` - -Narrows the query results based on the folders the assets belong to, per the folders’ IDs. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | in a folder with an ID of 1. -| `'not 1'` | not in a folder with an ID of 1. -| `[1, 2]` | in a folder with an ID of 1 or 2. -| `['not', 1, 2]` | not in a folder with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch assets in the folder with an ID of 1 #} -{% set assets = craft.assets() - .folderId(1) - .all() %} -``` - -```php -// Fetch assets in the folder with an ID of 1 -$assets = \craft\elements\Asset::find() - ->folderId(1) - ->all(); -``` -::: - - - -::: tip -This can be combined with [includeSubfolders](#includesubfolders) if you want to include assets in all the subfolders of a certain folder. -::: -#### `folderPath` - -Narrows the query results based on the folders the assets belong to, per the folders’ paths. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `foo/` | in a `foo/` folder (excluding nested folders). -| `foo/*` | in a `foo/` folder (including nested folders). -| `'not foo/*'` | not in a `foo/` folder (including nested folders). -| `['foo/*', 'bar/*']` | in a `foo/` or `bar/` folder (including nested folders). -| `['not', 'foo/*', 'bar/*']` | not in a `foo/` or `bar/` folder (including nested folders). - - - -::: code -```twig -{# Fetch assets in the foo/ folder or its nested folders #} -{% set assets = craft.assets() - .folderPath('foo/*') - .all() %} -``` - -```php -// Fetch assets in the foo/ folder or its nested folders -$assets = \craft\elements\Asset::find() - ->folderPath('foo/*') - ->all(); -``` -::: - - -#### `height` - -Narrows the query results based on the assets’ image heights. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `100` | with a height of 100. -| `'>= 100'` | with a height of at least 100. -| `['>= 100', '<= 1000']` | with a height between 100 and 1,000. - - - -::: code -```twig -{# Fetch XL images #} -{% set assets = craft.assets() - .kind('image') - .height('>= 1000') - .all() %} -``` - -```php -// Fetch XL images -$assets = \craft\elements\Asset::find() - ->kind('image') - ->height('>= 1000') - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the assets’ IDs. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the asset by its ID #} -{% set asset = craft.assets() - .id(1) - .one() %} -``` - -```php -// Fetch the asset by its ID -$asset = \craft\elements\Asset::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch assets in reverse #} -{% set assets = craft.assets() - .inReverse() - .all() %} -``` - -```php -// Fetch assets in reverse -$assets = \craft\elements\Asset::find() - ->inReverse() - ->all(); -``` -::: - - -#### `includeSubfolders` - -Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). - - - -::: code -```twig -{# Fetch assets in the folder with an ID of 1 (including its subfolders) #} -{% set assets = craft.assets() - .folderId(1) - .includeSubfolders() - .all() %} -``` - -```php -// Fetch assets in the folder with an ID of 1 (including its subfolders) -$assets = \craft\elements\Asset::find() - ->folderId(1) - ->includeSubfolders() - ->all(); -``` -::: - - - -::: warning -This will only work if [folderId](#folderid) was set to a single folder ID. -::: -#### `kind` - -Narrows the query results based on the assets’ file kinds. - -Supported file kinds: -- `access` -- `audio` -- `compressed` -- `excel` -- `flash` -- `html` -- `illustrator` -- `image` -- `javascript` -- `json` -- `pdf` -- `photoshop` -- `php` -- `powerpoint` -- `text` -- `video` -- `word` -- `xml` -- `unknown` - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'image'` | with a file kind of `image`. -| `'not image'` | not with a file kind of `image`.. -| `['image', 'pdf']` | with a file kind of `image` or `pdf`. -| `['not', 'image', 'pdf']` | not with a file kind of `image` or `pdf`. - - - -::: code -```twig -{# Fetch all the images #} -{% set assets = craft.assets() - .kind('image') - .all() %} -``` - -```php -// Fetch all the images -$assets = \craft\elements\Asset::find() - ->kind('image') - ->all(); -``` -::: - - -#### `limit` - -Determines the number of assets that should be returned. - - - -::: code -```twig -{# Fetch up to 10 assets #} -{% set assets = craft.assets() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 assets -$assets = \craft\elements\Asset::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many assets should be skipped in the results. - - - -::: code -```twig -{# Fetch all assets except for the first 3 #} -{% set assets = craft.assets() - .offset(3) - .all() %} -``` - -```php -// Fetch all assets except for the first 3 -$assets = \craft\elements\Asset::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) - - - -::: code -```twig -{# Fetch all assets in order of date created #} -{% set assets = craft.assets() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all assets in order of date created -$assets = \craft\elements\Asset::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique assets from Site A, or Site B if they don’t exist in Site A #} -{% set assets = craft.assets() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique assets from Site A, or Site B if they don’t exist in Site A -$assets = \craft\elements\Asset::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only assets that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all assets that are related to myCategory #} -{% set assets = craft.assets() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all assets that are related to $myCategory -$assets = \craft\elements\Asset::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only assets that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all assets that match the search query #} -{% set assets = craft.assets() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all assets that match the search query -$assets = \craft\elements\Asset::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the assets should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch assets from the Foo site #} -{% set assets = craft.assets() - .site('foo') - .all() %} -``` - -```php -// Fetch assets from the Foo site -$assets = \craft\elements\Asset::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the assets should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch assets from the site with an ID of 1 #} -{% set assets = craft.assets() - .siteId(1) - .all() %} -``` - -```php -// Fetch assets from the site with an ID of 1 -$assets = \craft\elements\Asset::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the assets’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the asset by its ID in the elements_sites table #} -{% set asset = craft.assets() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the asset by its ID in the elements_sites table -$asset = \craft\elements\Asset::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `size` - -Narrows the query results based on the assets’ file sizes (in bytes). - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1000` | with a size of 1,000 bytes (1KB). -| `'< 1000000'` | with a size of less than 1,000,000 bytes (1MB). -| `['>= 1000', '< 1000000']` | with a size between 1KB and 1MB. - - - -::: code -```twig -{# Fetch assets that are smaller than 1KB #} -{% set assets = craft.assets() - .size('< 1000') - .all() %} -``` - -```php -// Fetch assets that are smaller than 1KB -$assets = \craft\elements\Asset::find() - ->size('< 1000') - ->all(); -``` -::: - - -#### `title` - -Narrows the query results based on the assets’ titles. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch assets with a title that contains "Foo" #} -{% set assets = craft.assets() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch assets with a title that contains "Foo" -$assets = \craft\elements\Asset::find() - ->title('*Foo*') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only assets that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed assets #} -{% set assets = craft.assets() - .trashed() - .all() %} -``` - -```php -// Fetch trashed assets -$assets = \craft\elements\Asset::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the assets’ UIDs. - - - - - -::: code -```twig -{# Fetch the asset by its UID #} -{% set asset = craft.assets() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the asset by its UID -$asset = \craft\elements\Asset::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique assets across all sites #} -{% set assets = craft.assets() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique assets across all sites -$assets = \craft\elements\Asset::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `uploader` - -Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | uploaded by the user with an ID of 1. -| a [craft\elements\User](craft3:craft\elements\User) object | uploaded by the user represented by the object. - - - -::: code -```twig -{# Fetch assets uploaded by the user with an ID of 1 #} -{% set assets = craft.assets() - .uploader(1) - .all() %} -``` - -```php -// Fetch assets uploaded by the user with an ID of 1 -$assets = \craft\elements\Asset::find() - ->uploader(1) - ->all(); -``` -::: - - -#### `volume` - -Narrows the query results based on the volume the assets belong to. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'foo'` | in a volume with a handle of `foo`. -| `'not foo'` | not in a volume with a handle of `foo`. -| `['foo', 'bar']` | in a volume with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a volume with a handle of `foo` or `bar`. -| a [volume](craft3:craft\base\VolumeInterface) object | in a volume represented by the object. - - - -::: code -```twig -{# Fetch assets in the Foo volume #} -{% set assets = craft.assets() - .volume('foo') - .all() %} -``` - -```php -// Fetch assets in the Foo group -$assets = \craft\elements\Asset::find() - ->volume('foo') - ->all(); -``` -::: - - -#### `volumeId` - -Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | in a volume with an ID of 1. -| `'not 1'` | not in a volume with an ID of 1. -| `[1, 2]` | in a volume with an ID of 1 or 2. -| `['not', 1, 2]` | not in a volume with an ID of 1 or 2. -| `':empty:'` | that haven’t been stored in a volume yet - - - -::: code -```twig -{# Fetch assets in the volume with an ID of 1 #} -{% set assets = craft.assets() - .volumeId(1) - .all() %} -``` - -```php -// Fetch assets in the volume with an ID of 1 -$assets = \craft\elements\Asset::find() - ->volumeId(1) - ->all(); -``` -::: - - -#### `width` - -Narrows the query results based on the assets’ image widths. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `100` | with a width of 100. -| `'>= 100'` | with a width of at least 100. -| `['>= 100', '<= 1000']` | with a width between 100 and 1,000. - - - -::: code -```twig -{# Fetch XL images #} -{% set assets = craft.assets() - .kind('image') - .width('>= 1000') - .all() %} -``` - -```php -// Fetch XL images -$assets = \craft\elements\Asset::find() - ->kind('image') - ->width('>= 1000') - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching assets eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch assets eager-loaded with the "Related" field’s relations #} -{% set assets = craft.assets() - .with(['related']) - .all() %} -``` - -```php -// Fetch assets eager-loaded with the "Related" field’s relations -$assets = \craft\elements\Asset::find() - ->with(['related']) - ->all(); -``` -::: - - -#### `withTransforms` - -Causes the query to return matching assets eager-loaded with image transform indexes. - -This can improve performance when displaying several image transforms at once, if the transforms -have already been generated. - -Transforms can be specified as their handle or an object that contains `width` and/or `height` properties. - -You can include `srcset`-style sizes (e.g. `100w` or `2x`) following a normal transform definition, for example: - -::: code - -```twig -[{width: 1000, height: 600}, '1.5x', '2x', '3x'] -``` - -```php -[['width' => 1000, 'height' => 600], '1.5x', '2x', '3x'] -``` - -::: - -When a `srcset`-style size is encountered, the preceding normal transform definition will be used as a -reference when determining the resulting transform dimensions. - - - -::: code -```twig -{# Fetch assets with the 'thumbnail' and 'hiResThumbnail' transform data preloaded #} -{% set assets = craft.assets() - .kind('image') - .withTransforms(['thumbnail', 'hiResThumbnail']) - .all() %} -``` - -```php -// Fetch assets with the 'thumbnail' and 'hiResThumbnail' transform data preloaded -$assets = \craft\elements\Asset::find() - ->kind('image') - ->withTransforms(['thumbnail', 'hiResThumbnail']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/3.x/assets.md)!!! diff --git a/docs/3.x/categories.md b/docs/3.x/categories.md index 7379150fb..787a094d7 100644 --- a/docs/3.x/categories.md +++ b/docs/3.x/categories.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Categories You can create taxonomies for your [entries](entries.md), [users](users.md), and [assets](assets.md) using Categories. @@ -121,1345 +125,3 @@ To maintain the exact order you see in the control panel, add `orderBy('lft ASC' ### Parameters Category queries support the following parameters: - - - - - - - -| Param | Description -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [ancestorDist](#ancestordist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). -| [ancestorOf](#ancestorof) | Narrows the query results to only categories that are ancestors of another category in its structure. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only categories that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching categories as arrays of data, rather than [Category](craft3:craft\elements\Category) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#datecreated) | Narrows the query results based on the categories’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the categories’ last-updated dates. -| [descendantDist](#descendantdist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). -| [descendantOf](#descendantof) | Narrows the query results to only categories that are descendants of another category in its structure. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [group](#group) | Narrows the query results based on the category groups the categories belong to. -| [groupId](#groupid) | Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. -| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the categories have any descendants in their structure. -| [id](#id) | Narrows the query results based on the categories’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [leaves](#leaves) | Narrows the query results based on whether the categories are “leaves” (categories with no descendants). -| [level](#level) | Narrows the query results based on the categories’ level within the structure. -| [limit](#limit) | Determines the number of categories that should be returned. -| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the category that comes immediately after another category in its structure. -| [offset](#offset) | Determines how many categories should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`, or the order defined by the category group if the [group](#group) or [groupId](#groupid) params are set to a single group.) -| [positionedAfter](#positionedafter) | Narrows the query results to only categories that are positioned after another category in its structure. -| [positionedBefore](#positionedbefore) | Narrows the query results to only categories that are positioned before another category in its structure. -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the category that comes immediately before another category in its structure. -| [relatedTo](#relatedto) | Narrows the query results to only categories that are related to certain other elements. -| [search](#search) | Narrows the query results to only categories that match a search query. -| [siblingOf](#siblingof) | Narrows the query results to only categories that are siblings of another category in its structure. -| [site](#site) | Determines which site(s) the categories should be queried in. -| [siteId](#siteid) | Determines which site(s) the categories should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the categories’ IDs in the `elements_sites` table. -| [slug](#slug) | Narrows the query results based on the categories’ slugs. -| [status](#status) | Narrows the query results based on the categories’ statuses. -| [title](#title) | Narrows the query results based on the categories’ titles. -| [trashed](#trashed) | Narrows the query results to only categories that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the categories’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uri](#uri) | Narrows the query results based on the categories’ URIs. -| [with](#with) | Causes the query to return matching categories eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `ancestorDist` - -Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). - - - - - -::: code -```twig -{# Fetch categories above this one #} -{% set categories = craft.categories() - .ancestorOf(myCategory) - .ancestorDist(3) - .all() %} -``` - -```php -// Fetch categories above this one -$categories = \craft\elements\Category::find() - ->ancestorOf($myCategory) - ->ancestorDist(3) - ->all(); -``` -::: - - -#### `ancestorOf` - -Narrows the query results to only categories that are ancestors of another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | above the category with an ID of 1. -| a [Category](craft3:craft\elements\Category) object | above the category represented by the object. - - - -::: code -```twig -{# Fetch categories above this one #} -{% set categories = craft.categories() - .ancestorOf(myCategory) - .all() %} -``` - -```php -// Fetch categories above this one -$categories = \craft\elements\Category::find() - ->ancestorOf($myCategory) - ->all(); -``` -::: - - - -::: tip -This can be combined with [ancestorDist](#ancestordist) if you want to limit how far away the ancestor categories can be. -::: - - -#### `andRelatedTo` - -Narrows the query results to only categories that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all categories that are related to myCategoryA and myCategoryB #} -{% set categories = craft.categories() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all categories that are related to $myCategoryA and $myCategoryB -$categories = \craft\elements\Category::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all categories, regardless of status #} -{% set categories = craft.categories() - .anyStatus() - .all() %} -``` - -```php -// Fetch all categories, regardless of status -$categories = \craft\elements\Category::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching categories as arrays of data, rather than [Category](craft3:craft\elements\Category) objects. - - - - - -::: code -```twig -{# Fetch categories as arrays #} -{% set categories = craft.categories() - .asArray() - .all() %} -``` - -```php -// Fetch categories as arrays -$categories = \craft\elements\Category::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `dateCreated` - -Narrows the query results based on the categories’ creation dates. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch categories created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set categories = craft.categories() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch categories created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$categories = \craft\elements\Category::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the categories’ last-updated dates. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch categories updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set categories = craft.categories() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch categories updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$categories = \craft\elements\Category::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `descendantDist` - -Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). - - - - - -::: code -```twig -{# Fetch categories below this one #} -{% set categories = craft.categories() - .descendantOf(myCategory) - .descendantDist(3) - .all() %} -``` - -```php -// Fetch categories below this one -$categories = \craft\elements\Category::find() - ->descendantOf($myCategory) - ->descendantDist(3) - ->all(); -``` -::: - - -#### `descendantOf` - -Narrows the query results to only categories that are descendants of another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | below the category with an ID of 1. -| a [Category](craft3:craft\elements\Category) object | below the category represented by the object. - - - -::: code -```twig -{# Fetch categories below this one #} -{% set categories = craft.categories() - .descendantOf(myCategory) - .all() %} -``` - -```php -// Fetch categories below this one -$categories = \craft\elements\Category::find() - ->descendantOf($myCategory) - ->all(); -``` -::: - - - -::: tip -This can be combined with [descendantDist](#descendantdist) if you want to limit how far away the descendant categories can be. -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch categories in a specific order #} -{% set categories = craft.categories() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch categories in a specific order -$categories = \craft\elements\Category::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `group` - -Narrows the query results based on the category groups the categories belong to. - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'foo'` | in a group with a handle of `foo`. -| `'not foo'` | not in a group with a handle of `foo`. -| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. -| a [CategoryGroup](craft3:craft\models\CategoryGroup) object | in a group represented by the object. - - - -::: code -```twig -{# Fetch categories in the Foo group #} -{% set categories = craft.categories() - .group('foo') - .all() %} -``` - -```php -// Fetch categories in the Foo group -$categories = \craft\elements\Category::find() - ->group('foo') - ->all(); -``` -::: - - -#### `groupId` - -Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | in a group with an ID of 1. -| `'not 1'` | not in a group with an ID of 1. -| `[1, 2]` | in a group with an ID of 1 or 2. -| `['not', 1, 2]` | not in a group with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch categories in the group with an ID of 1 #} -{% set categories = craft.categories() - .groupId(1) - .all() %} -``` - -```php -// Fetch categories in the group with an ID of 1 -$categories = \craft\elements\Category::find() - ->groupId(1) - ->all(); -``` -::: - - -#### `hasDescendants` - -Narrows the query results based on whether the categories have any descendants in their structure. - - - -(This has the opposite effect of calling [leaves](#leaves).) - - - -::: code -```twig -{# Fetch categories that have descendants #} -{% set categories = craft.categories() - .hasDescendants() - .all() %} -``` - -```php -// Fetch categories that have descendants -$categories = \craft\elements\Category::find() - ->hasDescendants() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the categories’ IDs. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the category by its ID #} -{% set category = craft.categories() - .id(1) - .one() %} -``` - -```php -// Fetch the category by its ID -$category = \craft\elements\Category::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch categories in reverse #} -{% set categories = craft.categories() - .inReverse() - .all() %} -``` - -```php -// Fetch categories in reverse -$categories = \craft\elements\Category::find() - ->inReverse() - ->all(); -``` -::: - - -#### `leaves` - -Narrows the query results based on whether the categories are “leaves” (categories with no descendants). - - - -(This has the opposite effect of calling [hasDescendants](#hasdescendants).) - - - -::: code -```twig -{# Fetch categories that have no descendants #} -{% set categories = craft.categories() - .leaves() - .all() %} -``` - -```php -// Fetch categories that have no descendants -$categories = \craft\elements\Category::find() - ->leaves() - ->all(); -``` -::: - - -#### `level` - -Narrows the query results based on the categories’ level within the structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | with a level of 1. -| `'not 1'` | not with a level of 1. -| `'>= 3'` | with a level greater than or equal to 3. -| `[1, 2]` | with a level of 1 or 2 -| `['not', 1, 2]` | not with level of 1 or 2. - - - -::: code -```twig -{# Fetch categories positioned at level 3 or above #} -{% set categories = craft.categories() - .level('>= 3') - .all() %} -``` - -```php -// Fetch categories positioned at level 3 or above -$categories = \craft\elements\Category::find() - ->level('>= 3') - ->all(); -``` -::: - - -#### `limit` - -Determines the number of categories that should be returned. - - - -::: code -```twig -{# Fetch up to 10 categories #} -{% set categories = craft.categories() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 categories -$categories = \craft\elements\Category::find() - ->limit(10) - ->all(); -``` -::: - - -#### `nextSiblingOf` - -Narrows the query results to only the category that comes immediately after another category in its structure. - - - -Possible values include: - -| Value | Fetches the category… -| - | - -| `1` | after the category with an ID of 1. -| a [Category](craft3:craft\elements\Category) object | after the category represented by the object. - - - -::: code -```twig -{# Fetch the next category #} -{% set category = craft.categories() - .nextSiblingOf(myCategory) - .one() %} -``` - -```php -// Fetch the next category -$category = \craft\elements\Category::find() - ->nextSiblingOf($myCategory) - ->one(); -``` -::: - - -#### `offset` - -Determines how many categories should be skipped in the results. - - - -::: code -```twig -{# Fetch all categories except for the first 3 #} -{% set categories = craft.categories() - .offset(3) - .all() %} -``` - -```php -// Fetch all categories except for the first 3 -$categories = \craft\elements\Category::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`, or the order defined by the category group if the [group](#group) or [groupId](#groupid) params are set to a single group.) - - - -::: code -```twig -{# Fetch all categories in order of date created #} -{% set categories = craft.categories() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all categories in order of date created -$categories = \craft\elements\Category::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `positionedAfter` - -Narrows the query results to only categories that are positioned after another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | after the category with an ID of 1. -| a [Category](craft3:craft\elements\Category) object | after the category represented by the object. - - - -::: code -```twig -{# Fetch categories after this one #} -{% set categories = craft.categories() - .positionedAfter(myCategory) - .all() %} -``` - -```php -// Fetch categories after this one -$categories = \craft\elements\Category::find() - ->positionedAfter($myCategory) - ->all(); -``` -::: - - -#### `positionedBefore` - -Narrows the query results to only categories that are positioned before another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | before the category with an ID of 1. -| a [Category](craft3:craft\elements\Category) object | before the category represented by the object. - - - -::: code -```twig -{# Fetch categories before this one #} -{% set categories = craft.categories() - .positionedBefore(myCategory) - .all() %} -``` - -```php -// Fetch categories before this one -$categories = \craft\elements\Category::find() - ->positionedBefore($myCategory) - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique categories from Site A, or Site B if they don’t exist in Site A #} -{% set categories = craft.categories() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique categories from Site A, or Site B if they don’t exist in Site A -$categories = \craft\elements\Category::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prevSiblingOf` - -Narrows the query results to only the category that comes immediately before another category in its structure. - - - -Possible values include: - -| Value | Fetches the category… -| - | - -| `1` | before the category with an ID of 1. -| a [Category](craft3:craft\elements\Category) object | before the category represented by the object. - - - -::: code -```twig -{# Fetch the previous category #} -{% set category = craft.categories() - .prevSiblingOf(myCategory) - .one() %} -``` - -```php -// Fetch the previous category -$category = \craft\elements\Category::find() - ->prevSiblingOf($myCategory) - ->one(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only categories that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all categories that are related to myCategory #} -{% set categories = craft.categories() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all categories that are related to $myCategory -$categories = \craft\elements\Category::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only categories that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all categories that match the search query #} -{% set categories = craft.categories() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all categories that match the search query -$categories = \craft\elements\Category::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `siblingOf` - -Narrows the query results to only categories that are siblings of another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | beside the category with an ID of 1. -| a [Category](craft3:craft\elements\Category) object | beside the category represented by the object. - - - -::: code -```twig -{# Fetch categories beside this one #} -{% set categories = craft.categories() - .siblingOf(myCategory) - .all() %} -``` - -```php -// Fetch categories beside this one -$categories = \craft\elements\Category::find() - ->siblingOf($myCategory) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the categories should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch categories from the Foo site #} -{% set categories = craft.categories() - .site('foo') - .all() %} -``` - -```php -// Fetch categories from the Foo site -$categories = \craft\elements\Category::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the categories should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch categories from the site with an ID of 1 #} -{% set categories = craft.categories() - .siteId(1) - .all() %} -``` - -```php -// Fetch categories from the site with an ID of 1 -$categories = \craft\elements\Category::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the categories’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the category by its ID in the elements_sites table #} -{% set category = craft.categories() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the category by its ID in the elements_sites table -$category = \craft\elements\Category::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `slug` - -Narrows the query results based on the categories’ slugs. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'foo'` | with a slug of `foo`. -| `'foo*'` | with a slug that begins with `foo`. -| `'*foo'` | with a slug that ends with `foo`. -| `'*foo*'` | with a slug that contains `foo`. -| `'not *foo*'` | with a slug that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested category slug from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the category with that slug #} -{% set category = craft.categories() - .slug(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested category slug from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the category with that slug -$category = \craft\elements\Category::find() - ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the categories’ statuses. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'enabled'` _(default)_ | that are enabled. -| `'disabled'` | that are disabled. -| `['not', 'disabled']` | that are not disabled. - - - -::: code -```twig -{# Fetch disabled categories #} -{% set categories = craft.categories() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled categories -$categories = \craft\elements\Category::find() - ->status('disabled') - ->all(); -``` -::: - - -#### `title` - -Narrows the query results based on the categories’ titles. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch categories with a title that contains "Foo" #} -{% set categories = craft.categories() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch categories with a title that contains "Foo" -$categories = \craft\elements\Category::find() - ->title('*Foo*') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only categories that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed categories #} -{% set categories = craft.categories() - .trashed() - .all() %} -``` - -```php -// Fetch trashed categories -$categories = \craft\elements\Category::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the categories’ UIDs. - - - - - -::: code -```twig -{# Fetch the category by its UID #} -{% set category = craft.categories() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the category by its UID -$category = \craft\elements\Category::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique categories across all sites #} -{% set categories = craft.categories() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique categories across all sites -$categories = \craft\elements\Category::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `uri` - -Narrows the query results based on the categories’ URIs. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the category with that URI #} -{% set category = craft.categories() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the category with that URI -$category = \craft\elements\Category::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching categories eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch categories eager-loaded with the "Related" field’s relations #} -{% set categories = craft.categories() - .with(['related']) - .all() %} -``` - -```php -// Fetch categories eager-loaded with the "Related" field’s relations -$categories = \craft\elements\Category::find() - ->with(['related']) - ->all(); -``` -::: - - - - diff --git a/docs/3.x/config/config-settings.md b/docs/3.x/config/config-settings.md index 3676fe51b..d26135608 100644 --- a/docs/3.x/config/config-settings.md +++ b/docs/3.x/config/config-settings.md @@ -37,3468 +37,5 @@ return [ Here’s the full list of config settings that Craft supports: - - -## System - -### `accessibilityDefaults` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[ - 'alwaysShowFocusRings' => false, - 'useShapes' => false, - 'underlineLinks' => false, -]` - -Defined by -: [GeneralConfig::$accessibilityDefaults](craft3:craft\config\GeneralConfig::$accessibilityDefaults) - -Since -: 3.6.4 - -
- -The default user accessibility preferences that should be applied to users that haven’t saved their preferences yet. - -The array can contain the following keys: - -- `alwaysShowFocusRings` - Whether focus rings should always be shown when an element has focus -- `useShapes` – Whether shapes should be used to represent statuses -- `underlineLinks` – Whether links should be underlined - - - -### `allowAdminChanges` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$allowAdminChanges](craft3:craft\config\GeneralConfig::$allowAdminChanges) - -Since -: 3.1.0 - -
- -Whether admins should be allowed to make administrative changes to the system. - -When this is disabled, the Settings section will be hidden, the Craft edition and Craft/plugin versions will be locked, -and the project config and Plugin Store will become read-only—though Craft and plugin licenses may still be purchased. - -It’s best to disable this in production environments with a deployment workflow that runs `composer install` and -[propagates project config updates](../project-config.md#propagating-changes) on deploy. - -::: warning -Don’t disable this setting until **all** environments have been updated to Craft 3.1.0 or later. -::: - - - -### `allowSimilarTags` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$allowSimilarTags](craft3:craft\config\GeneralConfig::$allowSimilarTags) - -
- -Whether users should be allowed to create similarly-named tags. - - - -### `allowUpdates` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$allowUpdates](craft3:craft\config\GeneralConfig::$allowUpdates) - -
- -Whether Craft should allow system and plugin updates in the control panel, and plugin installation from the Plugin Store. - -This setting will automatically be disabled if is disabled. - - - -### `autoLoginAfterAccountActivation` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$autoLoginAfterAccountActivation](craft3:craft\config\GeneralConfig::$autoLoginAfterAccountActivation) - -
- -Whether users should automatically be logged in after activating their account or resetting their password. - - - -### `autosaveDrafts` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$autosaveDrafts](craft3:craft\config\GeneralConfig::$autosaveDrafts) - -Since -: 3.5.6 - -
- -Whether drafts should be saved automatically as they are edited. - -Note that drafts *will* be autosaved while Live Preview is open, regardless of this setting. - - - -### `backupOnUpdate` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$backupOnUpdate](craft3:craft\config\GeneralConfig::$backupOnUpdate) - -
- -Whether Craft should create a database backup before applying a new system update. - - - -### `cacheDuration` - -
- -Allowed types -: `mixed` - -Default value -: `86400` (1 day) - -Defined by -: [GeneralConfig::$cacheDuration](craft3:craft\config\GeneralConfig::$cacheDuration) - -
- -The default length of time Craft will store data, RSS feed, and template caches. - -If set to `0`, data and RSS feed caches will be stored indefinitely; template caches will be stored for one year. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `cpHeadTags` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$cpHeadTags](craft3:craft\config\GeneralConfig::$cpHeadTags) - -Since -: 3.5.0 - -
- -List of additional HTML tags that should be included in the `` of control panel pages. - -Each tag can be specified as an array of the tag name and its attributes. - -For example, you can give the control panel a custom favicon (etc.) like this: - -```php -'cpHeadTags' => [ - // Traditional favicon - ['link', ['rel' => 'icon', 'href' => '/icons/favicon.ico']], - // Scalable favicon for browsers that support them - ['link', ['rel' => 'icon', 'type' => 'image/svg+xml', 'sizes' => 'any', 'href' => '/icons/favicon.svg']], - // Touch icon for mobile devices - ['link', ['rel' => 'apple-touch-icon', 'sizes' => '180x180', 'href' => '/icons/touch-icon.svg']], - // Pinned tab icon for Safari - ['link', ['rel' => 'mask-icon', 'href' => '/icons/mask-icon.svg', 'color' => '#663399']], -], -``` - - - -### `defaultCpLanguage` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$defaultCpLanguage](craft3:craft\config\GeneralConfig::$defaultCpLanguage) - -
- -The default language the control panel should use for users who haven’t set a preferred language yet. - - - -### `defaultCpLocale` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$defaultCpLocale](craft3:craft\config\GeneralConfig::$defaultCpLocale) - -Since -: 3.5.0 - -
- -The default locale the control panel should use for date/number formatting, for users who haven’t set -a preferred language or formatting locale. - -If this is `null`, the config setting will determine which locale is used for date/number formatting by default. - - - -### `defaultDirMode` - -
- -Allowed types -: `mixed` - -Default value -: `0775` - -Defined by -: [GeneralConfig::$defaultDirMode](craft3:craft\config\GeneralConfig::$defaultDirMode) - -
- -The default permission to be set for newly-generated directories. - -If set to `null`, the permission will be determined by the current environment. - - - -### `defaultFileMode` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$defaultFileMode](craft3:craft\config\GeneralConfig::$defaultFileMode) - -
- -The default permission to be set for newly-generated files. - -If set to `null`, the permission will be determined by the current environment. - - - -### `defaultSearchTermOptions` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$defaultSearchTermOptions](craft3:craft\config\GeneralConfig::$defaultSearchTermOptions) - -
- -The default options that should be applied to each search term. - -Options include: - -- `attribute` – The attribute that the term should apply to (e.g. `'title'`), if any. (`null` by default) -- `exact` – Whether the term must be an exact match (only applies if `attribute` is set). (`false` by default) -- `exclude` – Whether search results should *exclude* records with this term. (`false` by default) -- `subLeft` – Whether to include keywords that contain the term, with additional characters before it. (`false` by default) -- `subRight` – Whether to include keywords that contain the term, with additional characters after it. (`true` by default) - - - -### `defaultTemplateExtensions` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[ - 'html', - 'twig', -]` - -Defined by -: [GeneralConfig::$defaultTemplateExtensions](craft3:craft\config\GeneralConfig::$defaultTemplateExtensions) - -
- -The template file extensions Craft will look for when matching a template path to a file on the front end. - - - -### `defaultWeekStartDay` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `1` (Monday) - -Defined by -: [GeneralConfig::$defaultWeekStartDay](craft3:craft\config\GeneralConfig::$defaultWeekStartDay) - -
- -The default day new users should have set as their Week Start Day. - -This should be set to one of the following integers: - -- `0` – Sunday -- `1` – Monday -- `2` – Tuesday -- `3` – Wednesday -- `4` – Thursday -- `5` – Friday -- `6` – Saturday - - - -### `devMode` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$devMode](craft3:craft\config\GeneralConfig::$devMode) - -
- -Whether the system should run in [Dev Mode](https://craftcms.com/support/dev-mode). - - - -### `disabledPlugins` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$disabledPlugins](craft3:craft\config\GeneralConfig::$disabledPlugins) - -Since -: 3.1.9 - -
- -Array of plugin handles that should be disabled, regardless of what the project config says. - -```php -'dev' => [ - 'disabledPlugins' => ['webhooks'], -], -``` - -This can also be set to `'*'` to disable **all** plugins. - -```php -'dev' => [ - 'disabledPlugins' => '*', -], -``` - -::: warning -This should not be set on a per-environment basis, as it could result in plugin schema version mismatches -between environments, which will prevent project config changes from getting applied. -::: - - - -### `disallowRobots` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$disallowRobots](craft3:craft\config\GeneralConfig::$disallowRobots) - -Since -: 3.5.10 - -
- -Whether front end requests should respond with `X-Robots-Tag: none` HTTP headers, indicating that pages should not be indexed, -and links on the page should not be followed, by web crawlers. - -::: tip -This should be set to `true` for development and staging environments. -::: - - - -### `enableTemplateCaching` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableTemplateCaching](craft3:craft\config\GeneralConfig::$enableTemplateCaching) - -
- -Whether to enable Craft’s template `{% cache %}` tag on a global basis. - - - -### `errorTemplatePrefix` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [GeneralConfig::$errorTemplatePrefix](craft3:craft\config\GeneralConfig::$errorTemplatePrefix) - -
- -The prefix that should be prepended to HTTP error status codes when determining the path to look for an error’s template. - -If set to `'_'` your site’s 404 template would live at `templates/_404.html`, for example. - - - -### `extraAllowedFileExtensions` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$extraAllowedFileExtensions](craft3:craft\config\GeneralConfig::$extraAllowedFileExtensions) - -
- -List of file extensions that will be merged into the config setting. - - - -### `extraAppLocales` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$extraAppLocales](craft3:craft\config\GeneralConfig::$extraAppLocales) - -Since -: 3.0.24 - -
- -List of extra locale IDs that the application should support, and users should be able to select as their Preferred Language. - -Only use this setting if your server has the Intl PHP extension, or if you’ve saved the corresponding -[locale data](https://github.com/craftcms/locales) into your `config/locales/` folder. - - - -### `handleCasing` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `GeneralConfig::CAMEL_CASE` - -Defined by -: [GeneralConfig::$handleCasing](craft3:craft\config\GeneralConfig::$handleCasing) - -Since -: 3.6.0 - -
- -The casing to use for autogenerated component handles. - -This can be set to one of the following: - -- `camel` – for camelCase -- `pascal` – for PascalCase (aka UpperCamelCase) -- `snake` – for snake_case - - - -### `headlessMode` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$headlessMode](craft3:craft\config\GeneralConfig::$headlessMode) - -Since -: 3.3.0 - -
- -Whether the system should run in Headless Mode, which optimizes the system and control panel for headless CMS implementations. - -When this is enabled, the following changes will take place: - -- Template settings for sections and category groups will be hidden. -- Template route management will be hidden. -- Front-end routing will skip checks for element and template requests. -- Front-end responses will be JSON-formatted rather than HTML by default. -- Twig will be configured to escape unsafe strings for JavaScript/JSON rather than HTML by default for front-end requests. -- The , , , and settings will be ignored. - -::: tip -With Headless Mode enabled, users may only set passwords and verify email addresses via the control panel. Be sure to grant “Access the control -panel” permission to all content editors and administrators. You’ll also need to set the config setting if the control -panel is located on a different domain than your front end. -::: - - - -### `httpProxy` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$httpProxy](craft3:craft\config\GeneralConfig::$httpProxy) - -Since -: 3.7.0 - -
- -The proxy server that should be used for outgoing HTTP requests. - -This can be set to a URL (`http://localhost`) or a URL plus a port (`http://localhost:8125`). - - - -### `indexTemplateFilenames` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[ - 'index', -]` - -Defined by -: [GeneralConfig::$indexTemplateFilenames](craft3:craft\config\GeneralConfig::$indexTemplateFilenames) - -
- -The template filenames Craft will look for within a directory to represent the directory’s “index” template when -matching a template path to a file on the front end. - - - -### `ipHeaders` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$ipHeaders](craft3:craft\config\GeneralConfig::$ipHeaders) - -
- -List of headers where proxies store the real client IP. - -See [yii\web\Request::$ipHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$ipHeaders-detail) for more details. - -If not set, the default [craft\web\Request::$ipHeaders](https://docs.craftcms.com/api/v3/craft-web-request.html#ipheaders) value will be used. - - - -### `isSystemLive` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$isSystemLive](craft3:craft\config\GeneralConfig::$isSystemLive) - -
- -Whether the site is currently live. If set to `true` or `false`, it will take precedence over the System Status setting -in Settings → General. - - - -### `limitAutoSlugsToAscii` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$limitAutoSlugsToAscii](craft3:craft\config\GeneralConfig::$limitAutoSlugsToAscii) - -
- -Whether non-ASCII characters in auto-generated slugs should be converted to ASCII (i.e. ñ → n). - -::: tip -This only affects the JavaScript auto-generated slugs. Non-ASCII characters can still be used in slugs if entered manually. -::: - - - -### `maxBackups` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [false](https://php.net/language.types.boolean) - -Default value -: `20` - -Defined by -: [GeneralConfig::$maxBackups](craft3:craft\config\GeneralConfig::$maxBackups) - -
- -The number of backups Craft should make before it starts deleting the oldest backups. If set to `false`, Craft will -not delete any backups. - - - -### `maxRevisions` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) - -Default value -: `50` - -Defined by -: [GeneralConfig::$maxRevisions](craft3:craft\config\GeneralConfig::$maxRevisions) - -Since -: 3.2.0 - -
- -The maximum number of revisions that should be stored for each element. - -Set to `0` if you want to store an unlimited number of revisions. - - - -### `maxSlugIncrement` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `100` - -Defined by -: [GeneralConfig::$maxSlugIncrement](craft3:craft\config\GeneralConfig::$maxSlugIncrement) - -
- -The highest number Craft will tack onto a slug in order to make it unique before giving up and throwing an error. - - - -### `permissionsPolicyHeader` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$permissionsPolicyHeader](craft3:craft\config\GeneralConfig::$permissionsPolicyHeader) - -Since -: 3.6.14 - -
- -The `Permissions-Policy` header that should be sent for web responses. - - - -### `phpMaxMemoryLimit` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$phpMaxMemoryLimit](craft3:craft\config\GeneralConfig::$phpMaxMemoryLimit) - -
- -The maximum amount of memory Craft will try to reserve during memory-intensive operations such as zipping, -unzipping and updating. Defaults to an empty string, which means it will use as much memory as it can. - -See for a list of acceptable values. - - - -### `previewIframeResizerOptions` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$previewIframeResizerOptions](craft3:craft\config\GeneralConfig::$previewIframeResizerOptions) - -Since -: 3.5.0 - -
- -Custom [iFrame Resizer options](http://davidjbradshaw.github.io/iframe-resizer/#options) that should be used for preview iframes. - -```php -'previewIframeResizerOptions' => [ - 'autoResize' => false, -], -``` - - - -### `privateTemplateTrigger` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'_'` - -Defined by -: [GeneralConfig::$privateTemplateTrigger](craft3:craft\config\GeneralConfig::$privateTemplateTrigger) - -
- -The template path segment prefix that should be used to identify “private” templates, which are templates that are not -directly accessible via a matching URL. - -Set to an empty value to disable public template routing. - - - -### `runQueueAutomatically` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$runQueueAutomatically](craft3:craft\config\GeneralConfig::$runQueueAutomatically) - -
- -Whether Craft should run pending queue jobs automatically when someone visits the control panel. - -If disabled, an alternate queue worker *must* be set up separately, either as an -[always-running daemon](https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/worker.md), or a cron job that runs the -`queue/run` command every minute: - -```cron -* * * * * /path/to/project/craft queue/run -``` - -::: tip -This setting should be disabled for servers running Win32, or with Apache’s mod_deflate/mod_gzip installed, -where PHP’s [flush()](https://php.net/manual/en/function.flush.php) method won’t work. -::: - - - -### `sameSiteCookieValue` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `null` - -Defined by -: [GeneralConfig::$sameSiteCookieValue](craft3:craft\config\GeneralConfig::$sameSiteCookieValue) - -Since -: 3.1.33 - -
- -The [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) value that should be set on Craft cookies, if any. - -This can be set to `'None'`, `'Lax'`, `'Strict'`, or `null`. - -::: tip -This setting requires PHP 7.3 or later. -::: - - - -### `sendContentLengthHeader` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$sendContentLengthHeader](craft3:craft\config\GeneralConfig::$sendContentLengthHeader) - -Since -: 3.7.3 - -
- -Whether a `Content-Length` header should be sent with responses. - - - -### `sendPoweredByHeader` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$sendPoweredByHeader](craft3:craft\config\GeneralConfig::$sendPoweredByHeader) - -
- -Whether an `X-Powered-By: Craft CMS` header should be sent, helping services like [BuiltWith](https://builtwith.com/) and -[Wappalyzer](https://www.wappalyzer.com/) identify that the site is running on Craft. - - - -### `slugWordSeparator` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'-'` - -Defined by -: [GeneralConfig::$slugWordSeparator](craft3:craft\config\GeneralConfig::$slugWordSeparator) - -
- -The character(s) that should be used to separate words in slugs. - - - -### `testToEmailAddress` - -
- -Allowed types -: [string](https://php.net/language.types.string), [array](https://php.net/language.types.array), [false](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$testToEmailAddress](craft3:craft\config\GeneralConfig::$testToEmailAddress) - -
- -Configures Craft to send all system emails to either a single email address or an array of email addresses -for testing purposes. - -By default, the recipient name(s) will be “Test Recipient”, but you can customize that by setting the value with the format -`['me@domain.tld' => 'Name']`. - - - -### `timezone` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$timezone](craft3:craft\config\GeneralConfig::$timezone) - -
- -The timezone of the site. If set, it will take precedence over the Timezone setting in Settings → General. - -This can be set to one of PHP’s [supported timezones](https://php.net/manual/en/timezones.php). - - - -### `translationDebugOutput` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$translationDebugOutput](craft3:craft\config\GeneralConfig::$translationDebugOutput) - -
- -Whether translated messages should be wrapped in special characters to help find any strings that are not being run through -`Craft::t()` or the `|translate` filter. - - - -### `useEmailAsUsername` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$useEmailAsUsername](craft3:craft\config\GeneralConfig::$useEmailAsUsername) - -
- -Whether Craft should set users’ usernames to their email addresses, rather than let them set their username separately. - -If you enable this setting after user accounts already exist, run this terminal command to update existing usernames: - -```bash -php craft utils/update-usernames -``` - - - -### `useFileLocks` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$useFileLocks](craft3:craft\config\GeneralConfig::$useFileLocks) - -
- -Whether to grab an exclusive lock on a file when writing to it by using the `LOCK_EX` flag. - -Some file systems, such as NFS, do not support exclusive file locking. - -If not set to `true` or `false`, Craft will try to detect if the underlying file system supports exclusive file locking and cache the results. - - - -### `useIframeResizer` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$useIframeResizer](craft3:craft\config\GeneralConfig::$useIframeResizer) - -Since -: 3.5.5 - -
- -Whether [iFrame Resizer options](http://davidjbradshaw.github.io/iframe-resizer/#options) should be used for Live Preview. - -Using iFrame Resizer makes it possible for Craft to retain the preview’s scroll position between page loads, for cross-origin web pages. - -It works by setting the height of the iframe to match the height of the inner web page, and the iframe’s container will be scrolled rather -than the iframe document itself. This can lead to some unexpected CSS issues, however, because the previewed viewport height will be taller -than the visible portion of the iframe. - -If you have a [decoupled front end](https://craftcms.com/docs/3.x/entries.html#previewing-decoupled-front-ends), you will need to include -[iframeResizer.contentWindow.min.js](https://raw.github.com/davidjbradshaw/iframe-resizer/master/js/iframeResizer.contentWindow.min.js) on your -page as well for this to work. You can conditionally include it for only Live Preview requests by checking if the requested URL contains a -`x-craft-live-preview` query string parameter. - -::: tip -You can customize the behavior of iFrame Resizer via the config setting. -::: - - - -## Environment - -### `aliases` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$aliases](craft3:craft\config\GeneralConfig::$aliases) - -
- -Any custom Yii [aliases](https://www.yiiframework.com/doc/guide/2.0/en/concept-aliases) that should be defined for every request. - - - -### `backupCommand` - -
- -Allowed types -: [string](https://php.net/language.types.string), [false](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$backupCommand](craft3:craft\config\GeneralConfig::$backupCommand) - -
- -The shell command that Craft should execute to create a database backup. - -When set to `null` (default), Craft will run `mysqldump` or `pg_dump`, provided that those libraries are in the `$PATH` variable -for the system user running the web server. - -You may provide your own command, which can include several tokens Craft will substitute at runtime: - -- `{file}` - the target backup file path -- `{port}` - the current database port -- `{server}` - the current database hostname -- `{user}` - user that was used to connect to the database -- `{password}` - password for the specified `{user}` -- `{database}` - the current database name -- `{schema}` - the current database schema (if any) - -This can also be set to `false` to disable database backups completely. - - - -### `defaultCookieDomain` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [GeneralConfig::$defaultCookieDomain](craft3:craft\config\GeneralConfig::$defaultCookieDomain) - -
- -The domain that cookies generated by Craft should be created for. If blank, it will be left up to the browser to determine -which domain to use (almost always the current). If you want the cookies to work for all subdomains, for example, you could -set this to `'.my-project.tld'`. - - - -### `resourceBasePath` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'@webroot/cpresources'` - -Defined by -: [GeneralConfig::$resourceBasePath](craft3:craft\config\GeneralConfig::$resourceBasePath) - -
- -The path to the root directory that should store published control panel resources. - - - -### `resourceBaseUrl` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'@web/cpresources'` - -Defined by -: [GeneralConfig::$resourceBaseUrl](craft3:craft\config\GeneralConfig::$resourceBaseUrl) - -
- -The URL to the root directory that should store published control panel resources. - - - -### `restoreCommand` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$restoreCommand](craft3:craft\config\GeneralConfig::$restoreCommand) - -
- -The shell command Craft should execute to restore a database backup. - -By default Craft will run `mysql` or `psql`, provided those libraries are in the `$PATH` variable for the user the web server is running as. - -There are several tokens you can use that Craft will swap out at runtime: - -- `{path}` - the backup file path -- `{port}` - the current database port -- `{server}` - the current database hostname -- `{user}` - the user to connect to the database -- `{database}` - the current database name -- `{schema}` - the current database schema (if any) - -This can also be set to `false` to disable database restores completely. - - - -## Routing - -### `actionTrigger` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'actions'` - -Defined by -: [GeneralConfig::$actionTrigger](craft3:craft\config\GeneralConfig::$actionTrigger) - -
- -The URI segment Craft should look for when determining if the current request should be routed to a controller action. - - - -### `activateAccountSuccessPath` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$activateAccountSuccessPath](craft3:craft\config\GeneralConfig::$activateAccountSuccessPath) - -
- -The URI that users without access to the control panel should be redirected to after activating their account. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `addTrailingSlashesToUrls` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$addTrailingSlashesToUrls](craft3:craft\config\GeneralConfig::$addTrailingSlashesToUrls) - -
- -Whether auto-generated URLs should have trailing slashes. - - - -### `allowUppercaseInSlug` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$allowUppercaseInSlug](craft3:craft\config\GeneralConfig::$allowUppercaseInSlug) - -
- -Whether uppercase letters should be allowed in slugs. - - - -### `baseCpUrl` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$baseCpUrl](craft3:craft\config\GeneralConfig::$baseCpUrl) - -
- -The base URL Craft should use when generating control panel URLs. - -It will be determined automatically if left blank. - -::: tip -The base control panel URL should **not** include the [control panel trigger word](config3:cpTrigger) (e.g. `/admin`). -::: - - - -### `cpTrigger` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `'admin'` - -Defined by -: [GeneralConfig::$cpTrigger](craft3:craft\config\GeneralConfig::$cpTrigger) - -
- -The URI segment Craft should look for when determining if the current request should route to the control panel rather than -the front-end website. - -This can be set to `null` if you have a dedicated hostname for the control panel (e.g. `cms.my-project.tld`), or you are running Craft in -[Headless Mode](config3:headlessMode). If you do that, you will need to ensure that the control panel is being served from its own web root -directory on your server, with an `index.php` file that defines the `CRAFT_CP` PHP constant. - -```php -define('CRAFT_CP', true); -``` - -Alternatively, you can set the config setting, but then you will run the risk of losing access to portions of your -control panel due to URI conflicts with actual folders/files in your main web root. - -(For example, if you have an `assets/` folder, that would conflict with the `/assets` page in the control panel.) - - - -### `invalidUserTokenPath` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$invalidUserTokenPath](craft3:craft\config\GeneralConfig::$invalidUserTokenPath) - -
- -The URI Craft should redirect to when user token validation fails. A token is used on things like setting and resetting user account -passwords. Note that this only affects front-end site requests. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `loginPath` - -
- -Allowed types -: `mixed` - -Default value -: `'login'` - -Defined by -: [GeneralConfig::$loginPath](craft3:craft\config\GeneralConfig::$loginPath) - -
- -The URI Craft should use for user login on the front end. - -This can be set to `false` to disable front-end login. - -Note that this config setting is ignored when is enabled. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `logoutPath` - -
- -Allowed types -: `mixed` - -Default value -: `'logout'` - -Defined by -: [GeneralConfig::$logoutPath](craft3:craft\config\GeneralConfig::$logoutPath) - -
- -The URI Craft should use for user logout on the front end. - -This can be set to `false` to disable front-end logout. - -Note that this config setting is ignored when is enabled. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `omitScriptNameInUrls` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$omitScriptNameInUrls](craft3:craft\config\GeneralConfig::$omitScriptNameInUrls) - -
- -Whether generated URLs should omit `index.php` (e.g. `http://my-project.tld/path` instead of `http://my-project.tld/index.php/path`) - -This can only be possible if your server is configured to redirect would-be 404s to `index.php`, for example, with the redirect found -in the `.htaccess` file that came with Craft: - -``` -RewriteEngine On -RewriteCond %{REQUEST_FILENAME} !-f -RewriteCond %{REQUEST_FILENAME} !-d -RewriteRule (.+) /index.php?p= [QSA,L] -``` - -::: tip -Even when this is set to `true`, the script name could still be included in some action URLs. -If you want to ensure that `index.php` is fully omitted from **all** generated URLs, set the -config setting to `null`. -::: - - - -### `pageTrigger` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'p'` - -Defined by -: [GeneralConfig::$pageTrigger](craft3:craft\config\GeneralConfig::$pageTrigger) - -
- -The string preceding a number which Craft will look for when determining if the current request is for a particular page in -a paginated list of pages. - -Example Value | Example URI -------------- | ----------- -`p` | `/news/p5` -`page` | `/news/page5` -`page/` | `/news/page/5` -`?page` | `/news?page=5` - -::: tip -If you want to set this to `?p` (e.g. `/news?p=5`), you’ll also need to change your setting which defaults to `p`. -If your server is running Apache, you’ll need to update the redirect code in your `.htaccess` file to match your new `pathParam` value. -::: - - - -### `pathParam` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `'p'` - -Defined by -: [GeneralConfig::$pathParam](craft3:craft\config\GeneralConfig::$pathParam) - -
- -The query string param that Craft will check when determining the request’s path. - -This can be set to `null` if your web server is capable of directing traffic to `index.php` without a query string param. -If you’re using Apache, that means you’ll need to change the `RewriteRule` line in your `.htaccess` file to: - -``` -RewriteRule (.+) index.php [QSA,L] -``` - - - -### `postCpLoginRedirect` - -
- -Allowed types -: `mixed` - -Default value -: `'dashboard'` - -Defined by -: [GeneralConfig::$postCpLoginRedirect](craft3:craft\config\GeneralConfig::$postCpLoginRedirect) - -
- -The path users should be redirected to after logging into the control panel. - -This setting will also come into effect if a user visits the control panel’s login page (`/admin/login`) or the control panel’s -root URL (`/admin`) when they are already logged in. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `postLoginRedirect` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$postLoginRedirect](craft3:craft\config\GeneralConfig::$postLoginRedirect) - -
- -The path users should be redirected to after logging in from the front-end site. - -This setting will also come into effect if the user visits the login page (as specified by the config setting) when -they are already logged in. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `postLogoutRedirect` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$postLogoutRedirect](craft3:craft\config\GeneralConfig::$postLogoutRedirect) - -
- -The path that users should be redirected to after logging out from the front-end site. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `setPasswordPath` - -
- -Allowed types -: `mixed` - -Default value -: `'setpassword'` - -Defined by -: [GeneralConfig::$setPasswordPath](craft3:craft\config\GeneralConfig::$setPasswordPath) - -
- -The URI or URL that Craft should use for Set Password forms on the front end. - -Note that this config setting is ignored when is enabled, unless it’s set to an absolute URL. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: tip -You might also want to set in case a user clicks on an expired password reset link. -::: - - - -### `setPasswordRequestPath` - -
- -Allowed types -: `mixed` - -Default value -: `null` - -Defined by -: [GeneralConfig::$setPasswordRequestPath](craft3:craft\config\GeneralConfig::$setPasswordRequestPath) - -Since -: 3.5.14 - -
- -The URI to the page where users can request to change their password. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -If this is set, Craft will redirect [.well-known/change-password requests](https://w3c.github.io/webappsec-change-password-url/) to this URI. - -::: tip -You’ll also need to set [setPasswordPath](config3:setPasswordPath), which determines the URI and template path for the Set Password form -where the user resets their password after following the link in the Password Reset email. -::: - - - -### `setPasswordSuccessPath` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$setPasswordSuccessPath](craft3:craft\config\GeneralConfig::$setPasswordSuccessPath) - -
- -The URI Craft should redirect users to after setting their password from the front end. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `siteToken` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'siteToken'` - -Defined by -: [GeneralConfig::$siteToken](craft3:craft\config\GeneralConfig::$siteToken) - -Since -: 3.5.0 - -
- -The query string parameter name that site tokens should be set to. - - - -### `tokenParam` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'token'` - -Defined by -: [GeneralConfig::$tokenParam](craft3:craft\config\GeneralConfig::$tokenParam) - -
- -The query string parameter name that Craft tokens should be set to. - - - -### `usePathInfo` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$usePathInfo](craft3:craft\config\GeneralConfig::$usePathInfo) - -
- -Whether Craft should specify the path using `PATH_INFO` or as a query string parameter when generating URLs. - -Note that this setting only takes effect if is set to `false`. - - - -### `useSslOnTokenizedUrls` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean), [string](https://php.net/language.types.string) - -Default value -: `'auto'` - -Defined by -: [GeneralConfig::$useSslOnTokenizedUrls](craft3:craft\config\GeneralConfig::$useSslOnTokenizedUrls) - -
- -Determines what protocol/schema Craft will use when generating tokenized URLs. If set to `'auto'`, Craft will check the -current site’s base URL and the protocol of the current request and if either of them are HTTPS will use `https` in the tokenized URL. If not, -will use `http`. - -If set to `false`, Craft will always use `http`. If set to `true`, then, Craft will always use `https`. - - - -### `verifyEmailPath` - -
- -Allowed types -: `mixed` - -Default value -: `'verifyemail'` - -Defined by -: [GeneralConfig::$verifyEmailPath](craft3:craft\config\GeneralConfig::$verifyEmailPath) - -Since -: 3.4.0 - -
- -The URI or URL that Craft should use for email verification links on the front end. - -Note that this config setting is ignored when is enabled, unless it’s set to an absolute URL. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -### `verifyEmailSuccessPath` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$verifyEmailSuccessPath](craft3:craft\config\GeneralConfig::$verifyEmailSuccessPath) - -Since -: 3.1.20 - -
- -The URI that users without access to the control panel should be redirected to after verifying a new email address. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - - - -## Session - -### `phpSessionName` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'CraftSessionId'` - -Defined by -: [GeneralConfig::$phpSessionName](craft3:craft\config\GeneralConfig::$phpSessionName) - -
- -The name of the PHP session cookie. - - - -### `rememberUsernameDuration` - -
- -Allowed types -: `mixed` - -Default value -: `31536000` (1 year) - -Defined by -: [GeneralConfig::$rememberUsernameDuration](craft3:craft\config\GeneralConfig::$rememberUsernameDuration) - -
- -The amount of time Craft will remember a username and pre-populate it on the control panel’s Login page. - -Set to `0` to disable this feature altogether. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `rememberedUserSessionDuration` - -
- -Allowed types -: `mixed` - -Default value -: `1209600` (14 days) - -Defined by -: [GeneralConfig::$rememberedUserSessionDuration](craft3:craft\config\GeneralConfig::$rememberedUserSessionDuration) - -
- -The amount of time a user stays logged if “Remember Me” is checked on the login page. - -Set to `0` to disable the “Remember Me” feature altogether. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `requireMatchingUserAgentForSession` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$requireMatchingUserAgentForSession](craft3:craft\config\GeneralConfig::$requireMatchingUserAgentForSession) - -
- -Whether Craft should require a matching user agent string when restoring a user session from a cookie. - - - -### `requireUserAgentAndIpForSession` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$requireUserAgentAndIpForSession](craft3:craft\config\GeneralConfig::$requireUserAgentAndIpForSession) - -
- -Whether Craft should require the existence of a user agent string and IP address when creating a new user session. - - - -### `userSessionDuration` - -
- -Allowed types -: `mixed` - -Default value -: `3600` (1 hour) - -Defined by -: [GeneralConfig::$userSessionDuration](craft3:craft\config\GeneralConfig::$userSessionDuration) - -
- -The amount of time before a user will get logged out due to inactivity. - -Set to `0` if you want users to stay logged in as long as their browser is open rather than a predetermined amount of time. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -## Security - -### `blowfishHashCost` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `13` - -Defined by -: [GeneralConfig::$blowfishHashCost](craft3:craft\config\GeneralConfig::$blowfishHashCost) - -
- -The higher the cost value, the longer it takes to generate a password hash and to verify against it. - -Therefore, higher cost slows down a brute-force attack. - -For best protection against brute force attacks, set it to the highest value that is tolerable on production servers. - -The time taken to compute the hash doubles for every increment by one for this value. - -For example, if the hash takes 1 second to compute when the value is 14 then the compute time varies as -2^(value - 14) seconds. - - - -### `cooldownDuration` - -
- -Allowed types -: `mixed` - -Default value -: `300` (5 minutes) - -Defined by -: [GeneralConfig::$cooldownDuration](craft3:craft\config\GeneralConfig::$cooldownDuration) - -
- -The amount of time a user must wait before re-attempting to log in after their account is locked due to too many -failed login attempts. - -Set to `0` to keep the account locked indefinitely, requiring an admin to manually unlock the account. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `csrfTokenName` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'CRAFT_CSRF_TOKEN'` - -Defined by -: [GeneralConfig::$csrfTokenName](craft3:craft\config\GeneralConfig::$csrfTokenName) - -
- -The name of CSRF token used for CSRF validation if is set to `true`. - - - -### `defaultTokenDuration` - -
- -Allowed types -: `mixed` - -Default value -: `86400` (1 day) - -Defined by -: [GeneralConfig::$defaultTokenDuration](craft3:craft\config\GeneralConfig::$defaultTokenDuration) - -
- -The default amount of time tokens can be used before expiring. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `deferPublicRegistrationPassword` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$deferPublicRegistrationPassword](craft3:craft\config\GeneralConfig::$deferPublicRegistrationPassword) - -
- -By default, Craft requires a front-end “password” field for public user registrations. Setting this to `true` -removes that requirement for the initial registration form. - -If you have email verification enabled, new users will set their password once they’ve followed the verification link in the email. -If you don’t, the only way they can set their password is to go through your “forgot password” workflow. - - - -### `elevatedSessionDuration` - -
- -Allowed types -: `mixed` - -Default value -: `300` (5 minutes) - -Defined by -: [GeneralConfig::$elevatedSessionDuration](craft3:craft\config\GeneralConfig::$elevatedSessionDuration) - -
- -The amount of time a user’s elevated session will last, which is required for some sensitive actions (e.g. user group/permission assignment). - -Set to `0` to disable elevated session support. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `enableBasicHttpAuth` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$enableBasicHttpAuth](craft3:craft\config\GeneralConfig::$enableBasicHttpAuth) - -Since -: 3.5.0 - -
- -Whether front-end web requests should support basic HTTP authentication. - - - -### `enableCsrfCookie` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableCsrfCookie](craft3:craft\config\GeneralConfig::$enableCsrfCookie) - -
- -Whether to use a cookie to persist the CSRF token if is enabled. If false, the CSRF token will be -stored in session under the `csrfTokenName` config setting name. Note that while storing CSRF tokens in session increases security, -it requires starting a session for every page that a CSRF token is needed, which may degrade site performance. - - - -### `enableCsrfProtection` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableCsrfProtection](craft3:craft\config\GeneralConfig::$enableCsrfProtection) - -
- -Whether to enable CSRF protection via hidden form inputs for all forms submitted via Craft. - - - -### `invalidLoginWindowDuration` - -
- -Allowed types -: `mixed` - -Default value -: `3600` (1 hour) - -Defined by -: [GeneralConfig::$invalidLoginWindowDuration](craft3:craft\config\GeneralConfig::$invalidLoginWindowDuration) - -
- -The amount of time to track invalid login attempts for a user, for determining if Craft should lock an account. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `maxInvalidLogins` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `5` - -Defined by -: [GeneralConfig::$maxInvalidLogins](craft3:craft\config\GeneralConfig::$maxInvalidLogins) - -
- -The number of invalid login attempts Craft will allow within the specified duration before the account gets locked. - - - -### `preventUserEnumeration` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$preventUserEnumeration](craft3:craft\config\GeneralConfig::$preventUserEnumeration) - -
- -When `true`, Craft will always return a successful response in the “forgot password” flow, making it difficult to enumerate users. - -When set to `false` and you go through the “forgot password” flow from the control panel login page, you’ll get distinct messages indicating -whether the username/email exists and whether an email was sent with further instructions. This can be helpful for the user attempting to -log in but allow for username/email enumeration based on the response. - - - -### `previewTokenDuration` - -
- -Allowed types -: `mixed` - -Default value -: `null` (1 day) - -Defined by -: [GeneralConfig::$previewTokenDuration](craft3:craft\config\GeneralConfig::$previewTokenDuration) - -Since -: 3.7.0 - -
- -The amount of time content preview tokens can be used before expiring. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `sanitizeCpImageUploads` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$sanitizeCpImageUploads](craft3:craft\config\GeneralConfig::$sanitizeCpImageUploads) - -Since -: 3.6.0 - -
- -Whether images uploaded via the control panel should be sanitized. - - - -### `sanitizeSvgUploads` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$sanitizeSvgUploads](craft3:craft\config\GeneralConfig::$sanitizeSvgUploads) - -
- -Whether Craft should sanitize uploaded SVG files and strip out potential malicious-looking content. - -This should definitely be enabled if you are accepting SVG uploads from untrusted sources. - - - -### `secureHeaders` - -
- -Allowed types -: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$secureHeaders](craft3:craft\config\GeneralConfig::$secureHeaders) - -
- -Lists of headers that are, by default, subject to the trusted host configuration. - -See [yii\web\Request::$secureHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureHeaders-detail) for more details. - -If not set, the default [yii\web\Request::$secureHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureHeaders-detail) value will be used. - - - -### `secureProtocolHeaders` - -
- -Allowed types -: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$secureProtocolHeaders](craft3:craft\config\GeneralConfig::$secureProtocolHeaders) - -
- -List of headers to check for determining whether the connection is made via HTTPS. - -See [yii\web\Request::$secureProtocolHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureProtocolHeaders-detail) for more details. - -If not set, the default [yii\web\Request::$secureProtocolHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureProtocolHeaders-detail) value will be used. - - - -### `securityKey` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `null` - -Defined by -: [GeneralConfig::$securityKey](craft3:craft\config\GeneralConfig::$securityKey) - -
- -A private, random, cryptographically-secure key that is used for hashing and encrypting data in [craft\services\Security](craft3:craft\services\Security). - -This value should be the same across all environments. If this key ever changes, any data that was encrypted with it will be inaccessible. - - - -### `storeUserIps` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$storeUserIps](craft3:craft\config\GeneralConfig::$storeUserIps) - -Since -: 3.1.0 - -
- -Whether user IP addresses should be stored/logged by the system. - - - -### `trustedHosts` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[ - 'any', -]` - -Defined by -: [GeneralConfig::$trustedHosts](craft3:craft\config\GeneralConfig::$trustedHosts) - -
- -The configuration for trusted security-related headers. - -See [yii\web\Request::$trustedHosts](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$trustedHosts-detail) for more details. - -By default, all hosts are trusted. - - - -### `useSecureCookies` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean), [string](https://php.net/language.types.string) - -Default value -: `'auto'` - -Defined by -: [GeneralConfig::$useSecureCookies](craft3:craft\config\GeneralConfig::$useSecureCookies) - -
- -Whether Craft will set the “secure” flag when saving cookies when using `Craft::cookieConfig()` to create a cookie. - -Valid values are `true`, `false`, and `'auto'`. Defaults to `'auto'`, which will set the secure flag if the page you’re currently accessing -is over `https://`. `true` will always set the flag, regardless of protocol and `false` will never automatically set the flag. - - - -### `verificationCodeDuration` - -
- -Allowed types -: `mixed` - -Default value -: `86400` (1 day) - -Defined by -: [GeneralConfig::$verificationCodeDuration](craft3:craft\config\GeneralConfig::$verificationCodeDuration) - -
- -The amount of time a user verification code can be used before expiring. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -## Assets - -### `allowedFileExtensions` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[ - '7z', - 'aiff', - 'asc', - 'asf', - 'avi', - 'avif', - 'bmp', - 'cap', - 'cin', - 'csv', - 'dfxp', - 'doc', - 'docx', - 'dotm', - 'dotx', - 'fla', - 'flv', - 'gif', - 'gz', - 'gzip', - 'heic', - 'heif', - 'hevc', - 'itt', - 'jp2', - 'jpeg', - 'jpg', - 'jpx', - 'js', - 'json', - 'lrc', - 'm2t', - 'm4a', - 'm4v', - 'mcc', - 'mid', - 'mov', - 'mp3', - 'mp4', - 'mpc', - 'mpeg', - 'mpg', - 'mpsub', - 'ods', - 'odt', - 'ogg', - 'ogv', - 'pdf', - 'png', - 'potx', - 'pps', - 'ppsm', - 'ppsx', - 'ppt', - 'pptm', - 'pptx', - 'ppz', - 'pxd', - 'qt', - 'ram', - 'rar', - 'rm', - 'rmi', - 'rmvb', - 'rt', - 'rtf', - 'sami', - 'sbv', - 'scc', - 'sdc', - 'sitd', - 'smi', - 'srt', - 'stl', - 'sub', - 'svg', - 'swf', - 'sxc', - 'sxw', - 'tar', - 'tds', - 'tgz', - 'tif', - 'tiff', - 'ttml', - 'txt', - 'vob', - 'vsd', - 'vtt', - 'wav', - 'webm', - 'webp', - 'wma', - 'wmv', - 'xls', - 'xlsx', - 'zip', -]` - -Defined by -: [GeneralConfig::$allowedFileExtensions](craft3:craft\config\GeneralConfig::$allowedFileExtensions) - -
- -The file extensions Craft should allow when a user is uploading files. - - - -### `convertFilenamesToAscii` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$convertFilenamesToAscii](craft3:craft\config\GeneralConfig::$convertFilenamesToAscii) - -
- -Whether uploaded filenames with non-ASCII characters should be converted to ASCII (i.e. `ñ` → `n`). - -::: tip -You can run `php craft utils/ascii-filenames` in your terminal to apply ASCII filenames to all existing assets. -::: - - - -### `extraFileKinds` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$extraFileKinds](craft3:craft\config\GeneralConfig::$extraFileKinds) - -Since -: 3.0.37 - -
- -List of additional file kinds Craft should support. This array will get merged with the one defined in -`\craft\helpers\Assets::_buildFileKinds()`. - -```php -'extraFileKinds' => [ - // merge .psb into list of Photoshop file kinds - 'photoshop' => [ - 'extensions' => ['psb'], - ], - // register new "Stylesheet" file kind - 'stylesheet' => [ - 'label' => 'Stylesheet', - 'extensions' => ['css', 'less', 'pcss', 'sass', 'scss', 'styl'], - ], -], -``` - -::: tip -File extensions listed here won’t immediately be allowed to be uploaded. You will also need to list them with -the config setting. -::: - - - -### `filenameWordSeparator` - -
- -Allowed types -: [string](https://php.net/language.types.string), [boolean](https://php.net/language.types.boolean) - -Default value -: `'-'` - -Defined by -: [GeneralConfig::$filenameWordSeparator](craft3:craft\config\GeneralConfig::$filenameWordSeparator) - -
- -The string to use to separate words when uploading assets. If set to `false`, spaces will be left alone. - - - -### `maxUploadFileSize` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [string](https://php.net/language.types.string) - -Default value -: `16777216` (16MB) - -Defined by -: [GeneralConfig::$maxUploadFileSize](craft3:craft\config\GeneralConfig::$maxUploadFileSize) - -
- -The maximum upload file size allowed. - -See [craft\helpers\ConfigHelper::sizeInBytes()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-sizeinbytes) for a list of supported value types. - - - -### `revAssetUrls` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$revAssetUrls](craft3:craft\config\GeneralConfig::$revAssetUrls) - -Since -: 3.7.0 - -
- -Whether asset URLs should be revved so browsers don’t load cached versions when they’re modified. - - - -## Image Handling - -### `brokenImagePath` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$brokenImagePath](craft3:craft\config\GeneralConfig::$brokenImagePath) - -Since -: 3.5.0 - -
- -The server path to an image file that should be sent when responding to an image request with a -404 status code. - -This can be set to an aliased path such as `@webroot/assets/404.svg`. - - - -### `defaultImageQuality` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `82` - -Defined by -: [GeneralConfig::$defaultImageQuality](craft3:craft\config\GeneralConfig::$defaultImageQuality) - -
- -The quality level Craft will use when saving JPG and PNG files. Ranges from 1 (worst quality, smallest file) to -100 (best quality, biggest file). - - - -### `generateTransformsBeforePageLoad` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$generateTransformsBeforePageLoad](craft3:craft\config\GeneralConfig::$generateTransformsBeforePageLoad) - -
- -Whether image transforms should be generated before page load. - - - -### `imageDriver` - -
- -Allowed types -: `mixed` - -Default value -: `GeneralConfig::IMAGE_DRIVER_AUTO` - -Defined by -: [GeneralConfig::$imageDriver](craft3:craft\config\GeneralConfig::$imageDriver) - -
- -The image driver Craft should use to cleanse and transform images. By default Craft will use ImageMagick if it’s installed -and otherwise fall back to GD. You can explicitly set either `'imagick'` or `'gd'` here to override that behavior. - - - -### `imageEditorRatios` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[ - 'Unconstrained' => 'none', - 'Original' => 'original', - 'Square' => 1, - '16:9' => 1.78, - '10:8' => 1.25, - '7:5' => 1.4, - '4:3' => 1.33, - '5:3' => 1.67, - '3:2' => 1.5, -]` - -Defined by -: [GeneralConfig::$imageEditorRatios](craft3:craft\config\GeneralConfig::$imageEditorRatios) - -
- -An array containing the selectable image aspect ratios for the image editor. The array must be in the format -of `label` => `ratio`, where ratio must be a float or a string. For string values, only values of “none” and “original” are allowed. - - - -### `maxCachedCloudImageSize` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `2000` - -Defined by -: [GeneralConfig::$maxCachedCloudImageSize](craft3:craft\config\GeneralConfig::$maxCachedCloudImageSize) - -
- -The maximum dimension size to use when caching images from external sources to use in transforms. Set to `0` to never cache them. - - - -### `optimizeImageFilesize` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$optimizeImageFilesize](craft3:craft\config\GeneralConfig::$optimizeImageFilesize) - -
- -Whether Craft should optimize images for reduced file sizes without noticeably reducing image quality. (Only supported when -ImageMagick is used.) - - - -### `preserveCmykColorspace` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$preserveCmykColorspace](craft3:craft\config\GeneralConfig::$preserveCmykColorspace) - -Since -: 3.0.8 - -
- -Whether CMYK should be preserved as the colorspace when manipulating images. - -Setting this to `true` will prevent Craft from transforming CMYK images to sRGB, but on some ImageMagick versions it can cause -image color distortion. This will only have an effect if ImageMagick is in use. - - - -### `preserveExifData` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$preserveExifData](craft3:craft\config\GeneralConfig::$preserveExifData) - -
- -Whether the EXIF data should be preserved when manipulating and uploading images. - -Setting this to `true` will result in larger image file sizes. - -This will only have effect if ImageMagick is in use. - - - -### `preserveImageColorProfiles` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$preserveImageColorProfiles](craft3:craft\config\GeneralConfig::$preserveImageColorProfiles) - -
- -Whether the embedded Image Color Profile (ICC) should be preserved when manipulating images. - -Setting this to `false` will reduce the image size a little bit, but on some ImageMagick versions can cause images to be saved with -an incorrect gamma value, which causes the images to become very dark. This will only have effect if ImageMagick is in use. - - - -### `rasterizeSvgThumbs` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$rasterizeSvgThumbs](craft3:craft\config\GeneralConfig::$rasterizeSvgThumbs) - -Since -: 3.6.0 - -
- -Whether SVG thumbnails should be rasterized. - -Note this will only work if ImageMagick is installed, and is set to either `auto` or `imagick`. - - - -### `rotateImagesOnUploadByExifData` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$rotateImagesOnUploadByExifData](craft3:craft\config\GeneralConfig::$rotateImagesOnUploadByExifData) - -
- -Whether Craft should rotate images according to their EXIF data on upload. - - - -### `transformGifs` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$transformGifs](craft3:craft\config\GeneralConfig::$transformGifs) - -Since -: 3.0.7 - -
- -Whether GIF files should be cleansed/transformed. - - - -### `transformSvgs` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$transformSvgs](craft3:craft\config\GeneralConfig::$transformSvgs) - -Since -: 3.7.1 - -
- -Whether SVG files should be transformed. - - - -### `upscaleImages` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$upscaleImages](craft3:craft\config\GeneralConfig::$upscaleImages) - -Since -: 3.4.0 - -
- -Whether images should be upscaled if the provided transform size is larger than the image. - - - -## GraphQL - -### `allowedGraphqlOrigins` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [false](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$allowedGraphqlOrigins](craft3:craft\config\GeneralConfig::$allowedGraphqlOrigins) - -Since -: 3.5.0 - -
- -The Ajax origins that should be allowed to access the GraphQL API, if enabled. - -If this is set to an array, then `graphql/api` requests will only include the current request’s [origin](https://www.yiiframework.com/doc/api/2.0/yii-web-request#getOrigin()-detail) -in the `Access-Control-Allow-Origin` response header if it’s listed here. - -If this is set to `false`, then the `Access-Control-Allow-Origin` response header will never be sent. - - - -### `disableGraphqlTransformDirective` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$disableGraphqlTransformDirective](craft3:craft\config\GeneralConfig::$disableGraphqlTransformDirective) - -Since -: 3.6.0 - -
- -Whether the `transform` directive should be disabled for the GraphQL API. - - - -### `enableGql` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableGql](craft3:craft\config\GeneralConfig::$enableGql) - -Since -: 3.3.1 - -
- -Whether the GraphQL API should be enabled. - -Note that the GraphQL API is only available for Craft Pro. - - - -### `enableGraphqlCaching` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableGraphqlCaching](craft3:craft\config\GeneralConfig::$enableGraphqlCaching) - -Since -: 3.3.12 - -
- -Whether Craft should cache GraphQL queries. - -If set to `true`, Craft will cache the results for unique GraphQL queries per access token. The cache is automatically invalidated any time -an element is saved, the site structure is updated, or a GraphQL schema is saved. - -This setting will have no effect if a plugin is using the [craft\services\Gql::EVENT_BEFORE_EXECUTE_GQL_QUERY](https://docs.craftcms.com/api/v3/craft-services-gql.html#event-before-execute-gql-query) event to provide its own -caching logic and setting the `result` property. - - - -### `enableGraphqlIntrospection` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableGraphqlIntrospection](craft3:craft\config\GeneralConfig::$enableGraphqlIntrospection) - -Since -: 3.6.0 - -
- -Whether GraphQL introspection queries are allowed. Defaults to `true` and is always allowed in the control panel. - - - -### `gqlTypePrefix` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [GeneralConfig::$gqlTypePrefix](craft3:craft\config\GeneralConfig::$gqlTypePrefix) - -
- -Prefix to use for all type names returned by GraphQL. - - - -### `maxGraphqlComplexity` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `0` - -Defined by -: [GeneralConfig::$maxGraphqlComplexity](craft3:craft\config\GeneralConfig::$maxGraphqlComplexity) - -Since -: 3.6.0 - -
- -The maximum allowed complexity a GraphQL query is allowed to have. Set to `0` to allow any complexity. - - - -### `maxGraphqlDepth` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `0` - -Defined by -: [GeneralConfig::$maxGraphqlDepth](craft3:craft\config\GeneralConfig::$maxGraphqlDepth) - -Since -: 3.6.0 - -
- -The maximum allowed depth a GraphQL query is allowed to reach. Set to `0` to allow any depth. - - - -### `maxGraphqlResults` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `0` - -Defined by -: [GeneralConfig::$maxGraphqlResults](craft3:craft\config\GeneralConfig::$maxGraphqlResults) - -Since -: 3.6.0 - -
- -The maximum allowed results for a single GraphQL query. Set to `0` to disable any limits. - - - -### `prefixGqlRootTypes` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$prefixGqlRootTypes](craft3:craft\config\GeneralConfig::$prefixGqlRootTypes) - -Since -: 3.6.6 - -
- -Whether the config setting should have an impact on `query`, `mutation`, and `subscription` types. - - - -### `setGraphqlDatesToSystemTimeZone` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$setGraphqlDatesToSystemTimeZone](craft3:craft\config\GeneralConfig::$setGraphqlDatesToSystemTimeZone) - -Since -: 3.7.0 - -
- -Whether dates returned by the GraphQL API should be set to the system time zone by default, rather than UTC. - - - -## Garbage Collection - -### `purgePendingUsersDuration` - -
- -Allowed types -: `mixed` - -Default value -: `0` - -Defined by -: [GeneralConfig::$purgePendingUsersDuration](craft3:craft\config\GeneralConfig::$purgePendingUsersDuration) - -
- -The amount of time to wait before Craft purges pending users from the system that have not activated. - -Any content assigned to a pending user will be deleted as well when the given time interval passes. - -Set to `0` to disable this feature. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: tip -Users will only be purged when [garbage collection](https://craftcms.com/docs/3.x/gc.html) is run. -::: - - - -### `purgeStaleUserSessionDuration` - -
- -Allowed types -: `mixed` - -Default value -: `7776000` (90 days) - -Defined by -: [GeneralConfig::$purgeStaleUserSessionDuration](craft3:craft\config\GeneralConfig::$purgeStaleUserSessionDuration) - -Since -: 3.3.0 - -
- -The amount of time to wait before Craft purges stale user sessions from the sessions table in the database. - -Set to `0` to disable this feature. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `purgeUnsavedDraftsDuration` - -
- -Allowed types -: `mixed` - -Default value -: `2592000` (30 days) - -Defined by -: [GeneralConfig::$purgeUnsavedDraftsDuration](craft3:craft\config\GeneralConfig::$purgeUnsavedDraftsDuration) - -Since -: 3.2.0 - -
- -The amount of time to wait before Craft purges unpublished drafts that were never updated with content. - -Set to `0` to disable this feature. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - -### `softDeleteDuration` - -
- -Allowed types -: `mixed` - -Default value -: `2592000` (30 days) - -Defined by -: [GeneralConfig::$softDeleteDuration](craft3:craft\config\GeneralConfig::$softDeleteDuration) - -Since -: 3.1.0 - -
- -The amount of time before a soft-deleted item will be up for hard-deletion by garbage collection. - -Set to `0` if you don’t ever want to delete soft-deleted items. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - - - - - + +!!!include(docs/.artifacts/cms/3.x/config-general.md)!!! diff --git a/docs/3.x/config/db-settings.md b/docs/3.x/config/db-settings.md index 552892106..c6fd5ca09 100644 --- a/docs/3.x/config/db-settings.md +++ b/docs/3.x/config/db-settings.md @@ -49,380 +49,5 @@ We recommend this environment variable approach for two reasons: Here’s the full list of database connection settings that Craft supports: - - -### `attributes` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [DbConfig::$attributes](craft3:craft\config\DbConfig::$attributes) - -
- -An array of key => value pairs of PDO attributes to pass into the PDO constructor. - -For example, when using the [MySQL PDO driver](https://php.net/manual/en/ref.pdo-mysql.php), if you wanted to enable a SSL database connection -(assuming [SSL is enabled in MySQL](https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-secure-connections.html) and `'user'` can connect via SSL, -you’d set these: - -```php -[ - PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem', - PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem', - PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem', -], -``` - - - -### `charset` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'utf8'` - -Defined by -: [DbConfig::$charset](craft3:craft\config\DbConfig::$charset) - -
- -The charset to use when creating tables. - -::: tip -You can change the character set and collation across all existing database tables using this terminal command: - -```bash -> php craft db/convert-charset -``` -::: - - - -### `collation` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$collation](craft3:craft\config\DbConfig::$collation) - -Since -: 3.6.4 - -
- -The collation to use when creating tables. - -This is only used by MySQL. If null, the [charset’s](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#charset) default collation will be used. - -| Charset | Default collation | -| --------- | -------------------- | -| `utf8` | `utf8_general_ci` | -| `utf8mb4` | `utf8mb4_0900_ai_ci` | - -::: tip -You can change the character set and collation across all existing database tables using this terminal command: - -```bash -> php craft db/convert-charset -``` -::: - - - -### `database` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$database](craft3:craft\config\DbConfig::$database) - -
- -The name of the database to select. - - - -### `driver` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$driver](craft3:craft\config\DbConfig::$driver) - -
- -The database driver to use. Either `mysql` for MySQL or `pgsql` for PostgreSQL. - - - -### `dsn` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$dsn](craft3:craft\config\DbConfig::$dsn) - -
- -The Data Source Name (“DSN”) that tells Craft how to connect to the database. - -DSNs should begin with a driver prefix (`mysql:` or `pgsql:`), followed by driver-specific parameters. -For example, `mysql:host=127.0.0.1;port=3306;dbname=acme_corp`. - -- MySQL parameters: -- PostgreSQL parameters: - - - -### `password` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [DbConfig::$password](craft3:craft\config\DbConfig::$password) - -
- -The database password to connect with. - - - -### `port` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$port](craft3:craft\config\DbConfig::$port) - -
- -The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. - - - -### `schema` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'public'` - -Defined by -: [DbConfig::$schema](craft3:craft\config\DbConfig::$schema) - -
- -The schema that Postgres is configured to use by default (PostgreSQL only). - -::: tip -To force Craft to use the specified schema regardless of PostgreSQL’s `search_path` setting, you must enable -the [setSchemaOnConnect](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#setschemaonconnect) setting. -::: - - - -### `server` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$server](craft3:craft\config\DbConfig::$server) - -
- -The database server name or IP address. Usually `localhost` or `127.0.0.1`. - - - -### `setSchemaOnConnect` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [DbConfig::$setSchemaOnConnect](craft3:craft\config\DbConfig::$setSchemaOnConnect) - -Since -: 3.7.27 - -
- -Whether the [schema](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#schema) should be explicitly used for database queries (PostgreSQL only). - -::: warning -This will cause an extra `SET search_path` SQL query to be executed per database connection. Ideally, -PostgreSQL’s `search_path` setting should be configured to prioritize the desired schema. -::: - - - -### `tablePrefix` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [DbConfig::$tablePrefix](craft3:craft\config\DbConfig::$tablePrefix) - -
- -If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), -you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase. - - - -### `unixSocket` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$unixSocket](craft3:craft\config\DbConfig::$unixSocket) - -
- -MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of -the server and port. If this is specified, then `server` and `port` settings are ignored. - - - -### `url` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$url](craft3:craft\config\DbConfig::$url) - -
- -The database connection URL, if one was provided by your hosting environment. - -If this is set, the values for [driver](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#driver), [user](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#user), [database](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#database), [server](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#server), [port](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#port), and [database](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#database) will be extracted from it. - - - -### `useUnbufferedConnections` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [DbConfig::$useUnbufferedConnections](craft3:craft\config\DbConfig::$useUnbufferedConnections) - -Since -: 3.7.0 - -
- -Whether batched queries should be executed on a separate, unbuffered database connection. - -This setting only applies to MySQL. It can be enabled when working with high volume content, to prevent -PHP from running out of memory when querying too much data at once. (See - for an explanation -of MySQL’s batch query limitations.) - - - -### `user` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'root'` - -Defined by -: [DbConfig::$user](craft3:craft\config\DbConfig::$user) - -
- -The database username to connect with. - - - - - + +!!!include(docs/.artifacts/cms/3.x/config-db.md)!!! diff --git a/docs/3.x/console-commands.md b/docs/3.x/console-commands.md index 82011ba8f..a5d6a42e1 100644 --- a/docs/3.x/console-commands.md +++ b/docs/3.x/console-commands.md @@ -49,2587 +49,5 @@ See the [Console Commands](extend/commands.md) page in the _Extending Craft_ sec While the complete list of available commands will include those from any plugins or custom modules you’ve added to your project, the following are Craft’s default console commands: - - -## `cache` - -Allows you to flush caches. - -

- # - cache/flush -

- - -Flushes given cache components. - -Example: - -```sh -# flushes caches by ID: “first”, “second”, “third” -php craft cache/flush first second third -``` - -

- # - cache/flush-all -

- - -Flushes all caches registered in the system. - -

- # - cache/flush-schema -

- - -Clears DB schema cache for a given connection component. - -```sh -php craft cache/flush-schema -# identical to `php craft cache/flush-schema db` -``` - -

Parameters

- -componentId -: ID of the connection component. (Defaults to `db`.) - - - -

- # - cache -

- - -Lists the caches that can be flushed. - -## `clear-caches` - -Allows you to clear various Craft caches. - -

- # - clear-caches/all -

- - -Clear all caches. - -

- # - clear-caches/asset -

- - -Clears Asset caches. - -

- # - clear-caches/asset-indexing-data -

- - -Clears Asset indexing data. - -

- # - clear-caches/compiled-classes -

- - -Clears compiled classes. - -

- # - clear-caches/compiled-templates -

- - -Clears compiled templates. - -

- # - clear-caches/cp-resources -

- - -Clears control panel resources. - -

- # - clear-caches/data -

- - -Clears data caches. - -

- # - clear-caches -

- - -Lists the caches that can be cleared. - -

- # - clear-caches/temp-files -

- - -Clears temporary files. - -

- # - clear-caches/transform-indexes -

- - -Clears the Asset transform index. - -## `clear-deprecations` - - -

- # - clear-deprecations -

- - -Clears all deprecation warnings. - -## `db` - -Performs database operations. - -

- # - db/backup -

- - -Creates a new database backup. - -Example: -``` -php craft db/backup ./my-backups/ -``` - -

Parameters

- -path -: The path the database backup should be created at. -Can be any of the following: - - - A full file path - - A folder path (backup will be saved in there with a dynamically-generated name) - - A filename (backup will be saved in the working directory with the given name) - - Blank (backup will be saved to the `storage/backups/` folder with a dynamically-generated name) - - - -

Options

- - ---zip -: Whether the backup should be saved as a zip file. - - ---overwrite -: Whether to overwrite an existing backup file, if a specific file path is given. - - - -

- # - db/convert-charset -

- - -Converts tables’ character sets and collations. (MySQL only) - -Example: -``` -php craft db/convert-charset utf8 utf8_unicode_ci -``` - -

Parameters

- -charset -: The target character set, which honors `DbConfig::$charset` - or defaults to `utf8`. - -collation -: The target collation, which honors `DbConfig::$collation` - or defaults to `utf8_unicode_ci`. - - - -

- # - db/restore -

- - -Restores a database backup. - -Example: -``` -php craft db/restore ./my-backup.sql -``` - -

Parameters

- -path -: The path to the database backup file. - - - -## `fixture` - -Allows you to manage test fixtures. - -

- # - fixture/load -

- - -Loads the specified fixture data. - -Example: - -```sh -# load User fixture data (any existing fixture data will be removed first) -php craft fixture/load "User" - -# load all available fixtures found under 'tests\unit\fixtures' -php craft fixture/load "*" - -# load all fixtures except User -php craft fixture/load "*, -User" -``` - -

Parameters

- -fixturesInput -: Array of fixtures to load. - - - -

Options

- - ---global-fixtures, -g -: Array of global fixtures that should be applied when loading and unloading. Set to `InitDbFixture` by default, which disables and enables integrity check so your data can be safely loaded. - - ---namespace, -n -: Namespace to search for fixtures. Defaults to `tests\unit\fixtures`. - - - -

- # - fixture/unload -

- - -Unloads the specified fixtures. - -Example: - -```sh -# unload User fixture data -php craft fixture/load "User" - -# unload all fixtures found under 'tests\unit\fixtures' -php craft fixture/load "*" - -# unload all fixtures except User -php craft fixture/load "*, -User" -``` - -

Parameters

- -fixturesInput -: Array of fixtures to unload. - - - -

Options

- - ---global-fixtures, -g -: Array of global fixtures that should be applied when loading and unloading. Set to `InitDbFixture` by default, which disables and enables integrity check so your data can be safely loaded. - - ---namespace, -n -: Namespace to search for fixtures. Defaults to `tests\unit\fixtures`. - - - -## `gc` - - -

- # - gc/run -

- - -Runs garbage collection. - -

Options

- - ---delete-all-trashed -: Whether all soft-deleted items should be deleted, rather than just -the ones that were deleted long enough ago to be ready for hard-deletion -per the `softDeleteDuration` config setting. - - ---empty-deprecated-tables -: Whether old database tables should be emptied out. - - - -## `graphql` - -Allows you to manage GraphQL schemas. - -

- # - graphql/create-token -

- - -Creates a new authorization token for a schema. - -

Parameters

- -schemaUid -: The schema UUID - - - -

Options

- - ---name -: The schema name - - ---expiry -: Expiry date - - - -

- # - graphql/dump-schema -

- - -Dumps a given GraphQL schema to a file. - -

Options

- - ---schema -: The GraphQL schema UUID. - - ---token -: The token to look up to determine the appropriate GraphQL schema. - - ---full-schema -: Whether full schema should be printed or dumped. - - - -

- # - graphql/list-schemas -

- - -Lists all GraphQL schemas. - -

- # - graphql/print-schema -

- - -Prints a given GraphQL schema. - -

Options

- - ---schema -: The GraphQL schema UUID. - - ---token -: The token to look up to determine the appropriate GraphQL schema. - - ---full-schema -: Whether full schema should be printed or dumped. - - - -## `help` - -Provides help information about console commands. - -

- # - help -

- - -Displays available commands or the detailed information -about a particular command. - -Example: - -``` -$ php craft help db/backup - -DESCRIPTION - -Creates a new database backup. - -Example: -php craft db/backup ./my-backups/ - - -USAGE - -craft db/backup [path] [...options...] - -- path: string - The path the database backup should be created at. - Can be any of the following: - - - A full file path - - A folder path (backup will be saved in there with a dynamically-generated name) - - A filename (backup will be saved in the working directory with the given name) - - Blank (backup will be saved to the `storage/backups/` folder with a dynamically-generated name) - - -OPTIONS - ---appconfig: string - custom application configuration file path. - If not set, default application configuration is used. - ---color: boolean, 0 or 1 - whether to enable ANSI color in the output. - If not set, ANSI color will only be enabled for terminals that support it. - ---help, -h: boolean, 0 or 1 (defaults to 0) - whether to display help information about current command. - ---interactive: boolean, 0 or 1 (defaults to 1) - whether to run the command interactively. - ---overwrite: boolean, 0 or 1 (defaults to 0) - Whether to overwrite an existing backup file, if a specific file path is given. - ---silent-exit-on-exception: boolean, 0 or 1 - if true - script finish with `ExitCode::OK` in case of exception. - false - `ExitCode::UNSPECIFIED_ERROR`. - Default: `YII_ENV_TEST` - ---zip: boolean, 0 or 1 (defaults to 0) - Whether the backup should be saved as a zip file. - -$ -``` - - -

Parameters

- -command -: The name of the command to show help about. -If not provided, all available commands will be displayed. - - - -

Options

- - ---as-json, -j -: Should the commands help be returned in JSON format? - - - -

- # - help/list -

- - -Lists all available controllers and actions in machine-readable format. - -

- # - help/list-action-options -

- - -List all available options for `action` in machine-readable format. - -

Parameters

- -action -: Route to action. - - - -

- # - help/usage -

- - -Displays usage information for `action`. - -

Parameters

- -action -: Route to action. - - - -## `index-assets` - -Allows you to re-index assets in volumes. - -

- # - index-assets/all -

- - -Re-indexes assets across all volumes. - -

Options

- - ---cache-remote-images -: Whether remote-stored images should be locally cached in the process. - - ---create-missing-assets -: Whether to auto-create new asset records when missing. - - ---delete-missing-assets -: Whether to delete all the asset records that have their files missing. - - - -

- # - index-assets/one -

- - -Re-indexes assets from the given volume handle. - -

Parameters

- -handle -: The handle of the volume to index. -You can optionally provide a volume sub-path, e.g. `php craft index-assets/one volume-handle/path/to/folder`. - -startAt -: Index of the asset to start with, which defaults to `0`. - - - -

Options

- - ---cache-remote-images -: Whether remote-stored images should be locally cached in the process. - - ---create-missing-assets -: Whether to auto-create new asset records when missing. - - ---delete-missing-assets -: Whether to delete all the asset records that have their files missing. - - - -## `install` - -Craft CMS CLI installer. - -

- # - install/check -

- - -Checks whether Craft is already installed. - -

- # - install/craft -

- - -Runs the install migration. - -

Options

- - ---email -: The default email address for the first user to create during install. - - ---username -: The default username for the first user to create during install. - - ---password -: The default password for the first user to create during install. - - ---site-name -: The default site name for the first site to create during install. - - ---site-url -: The default site URL for the first site to create during install. - - ---language -: The default langcode for the first site to create during install. - - - -## `invalidate-tags` - -Allows you to invalidate cache tags. - -

- # - invalidate-tags/all -

- - -Invalidates all cache tags. - -

- # - invalidate-tags/graphql -

- - -Invalidates all GraphQL query cache tags. - -

- # - invalidate-tags -

- - -Lists the cache tags that can be invalidated. - -

- # - invalidate-tags/template -

- - -Invalidates all template cache tags. - -## `mailer` - - -

- # - mailer/test -

- - -Tests sending an email with the current mailer settings. - -

Options

- - ---to -: Email address that should receive the test message. - - - -## `migrate` - -Manages Craft and plugin migrations. - -

- # - migrate/all -

- - -Runs all pending Craft, plugin, and content migrations. - -

Options

- - ---no-content -: Exclude pending content migrations. - - ---no-backup -: Skip backing up the database. - - - -

- # - migrate/create -

- - -Creates a new migration. - -This command creates a new migration using the available migration template. -After using this command, developers should modify the created migration -skeleton by filling up the actual migration logic. - -``` -craft migrate/create create_news_section -``` - -By default, the migration is created in the project’s `migrations/` -folder (as a “content migration”).\ -Use `--plugin=` to create a new plugin migration.\ -Use `--type=app` to create a new Craft CMS app migration. - -

Parameters

- -name -: the name of the new migration. This should only contain -letters, digits, and underscores. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - ---template-file -: The template file for generating new migrations. This can be either a path alias (e.g. `@app/migrations/template.php`) or a file path. Defaults to `vendor/craftcms/cms/src/updates/migration.php.template`. - - - -

- # - migrate/down -

- - -Downgrades Craft by reverting old migrations. - -Example: - -```sh -php craft migrate/down # revert last migration -php craft migrate/down 3 # revert last three migrations -php craft migrate/down all # revert all migrations -``` - -

Parameters

- -limit -: The number of migrations to be reverted. Defaults to `1`, meaning the last applied migration will be reverted. When value is `all`, all migrations will be reverted. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/history -

- - -Shows the list of migrations that have been applied so far. - -Example: - -```sh -php craft migrate/history # displays the last ten migrations -php craft migrate/history 5 # displays the last five migrations -php craft migrate/history all # displays the entire migration history -``` - -

Parameters

- -limit -: The maximum number of migrations to be displayed. (Defaults to `10`.) -If `all`, the whole migration history will be displayed. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/mark -

- - -Modifies the migration history to the specified version. - -No actual migration will be performed. - -```sh -php craft migrate/mark 101129_185401 # using timestamp -php craft migrate/mark m101129_185401_create_user_table # using name -php craft migrate/mark app\migrations\M101129185401CreateUser # using namespace name -php craft migrate/mark m000000_000000_base # reset entire history -``` - -

Parameters

- -version -: The version at which the migration history should be marked, which can be either the timestamp or the full name of the migration. - - Specify `m000000_000000_base` to set the migration history to a state where no migration has been applied. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/new -

- - -Shows any new migrations that have not been applied. - -Example: - -```sh -php craft migrate/new # displays the first 10 new migrations -php craft migrate/new 5 # displays the first 5 new migrations -php craft migrate/new all # displays all new migrations -``` - -

Parameters

- -limit -: The maximum number of new migrations to be displayed. (Defaults to `10`.) -If `all`, then every available new migration will be displayed. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/redo -

- - -Reapplies previous migrations by first reverting them and then applying them again. - -Example: - -```sh -php craft migrate/redo # redo the last applied migration -php craft migrate/redo 3 # redo the last three applied migrations -php craft migrate/redo all # redo all migrations -``` - -

Parameters

- -limit -: The number of migrations to be redone. Defaults to `1`, meaning the last applied migration will be redone. When `all`, every migration will be redone. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/to -

- - -Upgrades or downgrades until the specified version. - -You can downgrade versions to a past apply time by providing a UNIX timestamp or a [strtotime()](https://www.php.net/manual/en/function.strtotime.php)-parseable value. All versions applied after that specified time will then be reverted. - -Example: - -```sh -php craft migrate/to 101129_185401 # migration timestamp -php craft migrate/to m101129_185401_create_user_table # full name -php craft migrate/to 1392853618 # UNIX timestamp -php craft migrate/to "2022-02-02 02:02:02" # strtotime()-parseable -php craft migrate/to app\migrations\M101129185401CreateUser # full namespace name -``` - -

Parameters

- -version -: Either the version name or a past time value to be migrated to. This can be a timestamp, the full name of the migration, a UNIX timestamp, or a string value that can be parsed by [strotime()](https://www.php.net/manual/en/function.strtotime.php). - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/up -

- - -Upgrades Craft by applying new migrations. - -Example: -``` -php craft migrate # apply all new migrations -php craft migrate 3 # apply the first 3 new migrations -``` - -

Parameters

- -limit -: The number of new migrations to be applied. If `0`, every new migration -will be applied. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -## `off` - - -

- # - off -

- - -Disables `system.live` project config value—bypassing any `allowAdminChanges` config setting -restrictions—meant for temporary use during the deployment process. - -

Options

- - ---retry -: Number of seconds the `Retry-After` HTTP header should be set to for 503 responses. - - The `retryDuration` config setting can be used to configure a *system-wide* `Retry-After` header. - - ::: warning - The `isSystemLive` config setting takes precedence over the `system.live` project config value, - so if `config/general.php` sets `isSystemLive` to `true` or `false` these `on`/`off` commands error out. - ::: - - **Example** - - Running the following takes the system offline and returns 503 responses until it’s switched on again: - - ``` - $ php craft off --retry=60 - The system is now offline. - The retry duration is now set to 60. - ``` - - - -## `on` - - -

- # - on -

- - -Turns the system on. - -Example: -``` -$ php craft on -The system is now online. -``` - -## `plugin` - -Manages plugins. - -

- # - plugin/disable -

- - -Disables a plugin. - -``` -$ php craft plugin/disable - -The following plugins are enabled: - - Handle Name Version - ------------- -------------- ------- - apple-news Apple News 2.0.1 - ckeditor CKEditor 1.3.0 - commerce Craft Commerce 3.4.11 - gatsby-helper Gatsby Helper 1.1.2 - -Choose a plugin handle to disable: ckeditor -*** disabling ckeditor -*** disabled ckeditor successfully (time: 0.003s) -``` - - -

Parameters

- -handle -: The plugin handle. - - - -

- # - plugin/enable -

- - -Enables a plugin. - -``` -$ php craft plugin/enable - -The following plugins are disabled: - - Handle Name Version - ---------- ---------- ------- - apple-news Apple News 2.0.1 - ckeditor CKEditor 1.3.0 - -Choose a plugin handle to enable: ckeditor -*** enabling ckeditor -*** enabled ckeditor successfully (time: 0.004s) -``` - - -

Parameters

- -handle -: The plugin handle. - - - -

- # - plugin/install -

- - -Installs a plugin. - -``` -$ php craft plugin/install - -The following uninstalled plugins are present: - - Handle Name Version - ------------- -------------- ------- - anchors Anchors 2.3.1 - apple-news Apple News 2.0.1 - ckeditor CKEditor 1.3.0 - commerce Craft Commerce 3.4.11 - gatsby-helper Gatsby Helper 1.1.2 - -Choose a plugin handle to install: ckeditor -*** installing ckeditor -*** installed ckeditor successfully (time: 0.496s) -``` - - -

Parameters

- -handle -: The plugin handle. - - - -

- # - plugin/list -

- - -Lists all plugins. - -``` -$ php craft plugin/list - - Name Handle Package Name Version Installed Enabled - -------------- ------------- ---------------------- ------- --------- ------- - Anchors anchors craftcms/anchors 2.3.1 Yes Yes - Apple News apple-news craftcms/apple-news 2.0.1 Yes Yes - CKEditor ckeditor craftcms/ckeditor 1.3.0 Yes Yes - Craft Commerce commerce craftcms/commerce 3.4.11 Yes Yes - Gatsby Helper gatsby-helper craftcms/gatsby-helper 1.1.2 Yes Yes -``` - - -

- # - plugin/uninstall -

- - -Uninstalls a plugin. - -``` -$ php craft plugin/uninstall - -The following plugins plugins are installed and enabled: - - Handle Name Version - ------------- -------------- ------- - anchors Anchors 2.3.1 - apple-news Apple News 2.0.1 - ckeditor CKEditor 1.3.0 - commerce Craft Commerce 3.4.11 - gatsby-helper Gatsby Helper 1.1.2 - -Choose a plugin handle to uninstall: ckeditor -*** uninstalling ckeditor -*** uninstalled ckeditor successfully (time: 0.496s) -``` - - -

Parameters

- -handle -: The plugin handle. - - - -

Options

- - ---force -: Whether the plugin uninstallation should be forced. - - - -## `project-config` - -Manages the Project Config. - -

- # - project-config/apply -

- - -Applies project config file changes. - -

Options

- - ---force -: Whether every entry change should be force-applied. - - - -

- # - project-config/diff -

- - -Prints a diff of the pending project config YAML changes. - -

Options

- - ---invert -: Whether to treat the loaded project config as the source of truth, instead of the YAML files. - - - -

- # - project-config/export -

- - -Exports the entire project config to a single file. - -

Parameters

- -path -: The path the project config should be exported to. -Can be any of the following: - - - A full file path - - A folder path (export will be saved in there with a dynamically-generated name) - - A filename (export will be saved in the working directory with the given name) - - Blank (export will be saved in the working directly with a dynamically-generated name) - - - -

Options

- - ---external -: Whether to export the external project config data, from the `config/project/` folder - - ---overwrite -: Whether to overwrite an existing export file, if a specific file path is given. - - - -

- # - project-config/rebuild -

- - -Rebuilds the project config. - -

- # - project-config/touch -

- - -Updates the `dateModified` value in `config/project/project.yaml`, attempting to resolve a Git conflict for it. - -

- # - project-config/write -

- - -Writes out the currently-loaded project config as YAML files to the `config/project/` folder, discarding any pending YAML changes. - -## `queue` - -Manages the queue. - -

- # - queue/exec -

- - -Executes a job. -The command is internal, and used to isolate a job execution. Manual usage is not provided. - -

Parameters

- -id -: of a message - -ttr -: time to reserve - -attempt -: number - -pid -: of a worker - - - -

Options

- - ---verbose, -v -: verbose mode of a job execute. If enabled, execute result of each job -will be printed. - - - -

- # - queue/info -

- - -Info about queue status. - -

- # - queue/listen -

- - -Listens for new jobs added to the queue and runs them. - -

Parameters

- -timeout -: The number of seconds to wait between cycles. - - - -

Options

- - ---verbose, -v -: verbose mode of a job execute. If enabled, execute result of each job -will be printed. - - ---isolate -: isolate mode. It executes a job in a child process. - - ---php-binary -: path to php interpreter that uses to run child processes. -If it is undefined, PHP_BINARY will be used. - - - -

- # - queue/release -

- - -Releases job(s) from the queue. - -Example: - -``` -php craft queue/release all -``` - -

Parameters

- -job -: The job ID to release. Pass `all` to release all jobs. - - - -

- # - queue/retry -

- - -Re-adds failed job(s) to the queue. - -

Parameters

- -job -: The job ID that should be retried, or `all` to retry all failed jobs. - - - -

- # - queue/run -

- - -Runs all jobs in the queue. - -

Options

- - ---verbose, -v -: verbose mode of a job execute. If enabled, execute result of each job -will be printed. - - ---isolate -: isolate mode. It executes a job in a child process. - - ---php-binary -: path to php interpreter that uses to run child processes. -If it is undefined, PHP_BINARY will be used. - - - -## `resave` - -Allows you to bulk-save elements. - -

- # - resave/assets -

- - -Re-saves assets. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to save elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---volume -: The volume handle(s) to save assets from. Can be set to multiple comma-separated volumes. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/categories -

- - -Re-saves categories. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to save elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---group -: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/entries -

- - -Re-saves entries. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---drafts -: Whether to resave element drafts. - - ---provisional-drafts -: Whether to resave provisional element drafts. - - ---revisions -: Whether to resave element revisions. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to save elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---section -: The section handle(s) to save entries from. Can be set to multiple comma-separated sections. - - ---type -: The type handle(s) of the elements to resave. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/matrix-blocks -

- - -Re-saves Matrix blocks. - -You must supply the `--field` or `--element-id` argument for this to work properly. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to save elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---type -: The type handle(s) of the elements to resave. - - ---field -: The field handle to save Matrix blocks for. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/tags -

- - -Re-saves tags. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to save elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---group -: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/users -

- - -Re-saves users. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to save elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---group -: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn($element) => $element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -## `serve` - - -

- # - serve -

- - -Runs PHP built-in web server. - -

Parameters

- -address -: address to serve on. Either "host" or "host:port". - - - -

Options

- - ---docroot, -t -: path or [path alias](https://craftcms.com/docs/3.x/config/#aliases) of the directory to serve. - - ---port, -p -: port to serve on. - - ---router, -r -: path or [path alias](guide:concept-aliases) to router script. -See https://www.php.net/manual/en/features.commandline.webserver.php - - - -## `setup` - -Craft CMS setup installer. - -

- # - setup/app-id -

- - -Generates a new application ID and saves it in the `.env` file. - -

- # - setup/db -

- - -Alias for [setup/db-creds](#setup-db-creds). - -

Options

- - ---driver -: The database driver to use. Either `'mysql'` for MySQL or `'pgsql'` for PostgreSQL. - - ---server -: The database server name or IP address. Usually `'localhost'` or `'127.0.0.1'`. - - ---port -: The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. - - ---user -: The database username to connect with. - - ---password -: The database password to connect with. - - ---database -: The name of the database to select. - - ---schema -: The schema that Postgres is configured to use by default (PostgreSQL only). - - ---table-prefix -: The table prefix to add to all database tables. This can -be no more than 5 characters, and must be all lowercase. - - - -

- # - setup/db-cache-table -

- - -Creates a database table for storing DB caches. - -

- # - setup/db-creds -

- - -Stores new DB connection settings to the `.env` file. - -

Options

- - ---driver -: The database driver to use. Either `'mysql'` for MySQL or `'pgsql'` for PostgreSQL. - - ---server -: The database server name or IP address. Usually `'localhost'` or `'127.0.0.1'`. - - ---port -: The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. - - ---user -: The database username to connect with. - - ---password -: The database password to connect with. - - ---database -: The name of the database to select. - - ---schema -: The schema that Postgres is configured to use by default (PostgreSQL only). - - ---table-prefix -: The table prefix to add to all database tables. This can -be no more than 5 characters, and must be all lowercase. - - - -

- # - setup -

- - -Sets up all the things. - -

- # - setup/php-session-table -

- - -Creates a database table for storing PHP session information. - -

- # - setup/security-key -

- - -Generates a new security key and saves it in the `.env` file. - -

- # - setup/welcome -

- - -Called from the `post-create-project-cmd` Composer hook. - -## `shell` - - -

- # - shell -

- - -Runs an interactive shell. - -::: tip -This command requires the [`yiisoft/yii2-shell`](https://github.com/yiisoft/yii2-shell) package, which you may need to add to your project: - -``` -composer require --dev yiisoft/yii2-shell -``` -::: - -``` -$ php craft shell -Psy Shell v0.10.4 (PHP 7.4.3 — cli) by Justin Hileman ->>> help - help Show a list of commands. Type `help [foo]` for information about [foo]. Alias - ls List local, instance or class variables, methods and constants. Alias - dump Dump an object or primitive. - doc Read the documentation for an object, class, constant, method or property. Alias - show Show the code for an object, class, constant, method or property. - wtf Show the backtrace of the most recent exception. Alias - whereami Show where you are in the code. - throw-up Throw an exception or error out of the Psy Shell. - timeit Profiles with a timer. - trace Show the current call stack. - buffer Show (or clear) the contents of the code input buffer. Alias - clear Clear the Psy Shell screen. - edit Open an external editor. Afterwards, get produced code in input buffer. - sudo Evaluate PHP code, bypassing visibility restrictions. - history Show the Psy Shell history. Alias - exit End the current session and return to caller. Alias -``` - - -

Options

- - ---include -: Include file(s) before starting tinker shell. - - - -## `tests` - - -

- # - tests/setup -

- - -Sets up a test suite for the current project. - -

Parameters

- -dst -: The folder that the test suite should be generated in. - Defaults to the current working directory. - - - -## `up` - - -

- # - up -

- - -Runs pending migrations and applies pending project config changes. - -

Options

- - ---force -: Whether to perform the action even if a mutex lock could not be acquired. - - - -## `update` - -Updates Craft and plugins. - -

- # - update/composer-install -

- - -Installs dependencies based on the current `composer.json` & `composer.lock`. - -

- # - update/info -

- - -Displays info about available updates. - -

- # - update/update -

- - -Updates Craft and/or plugins. - -

Parameters

- -handle -: The update handle (`all`, `craft`, or a plugin handle). -You can pass multiple handles separated by spaces, and you can update to a specific -version using the syntax `:`. - - - -

Options

- - ---force, -f -: Force the update if allowUpdates is disabled - - ---backup -: Backup the database before updating - - ---migrate -: Run new database migrations after completing the update - - - -## `users` - -Manages user accounts. - -

- # - users/activation-url -

- - -Generates an activation URL for a pending user. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

- # - users/create -

- - -Creates a user. - -

Options

- - ---email -: The user’s email address. - - ---username -: The user’s username. - - ---password -: The user’s new password. - - ---admin -: Whether the user should be an admin. - - ---groups -: The group handles to assign the created user to. - - ---group-ids -: The group IDs to assign the user to the created user to. - - - -

- # - users/delete -

- - -Deletes a user. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

Options

- - ---inheritor -: The email or username of the user to inherit content when deleting a user. - - ---delete-content -: Whether to delete the user’s content if no inheritor is specified. - - ---hard -: Whether the user should be hard-deleted immediately, instead of soft-deleted. - - - -

- # - users/impersonate -

- - -Generates a URL to impersonate a user. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

- # - users/list-admins -

- - -Lists admin users. - -

- # - users/logout-all -

- - -Logs all users out of the system. - -

- # - users/password-reset-url -

- - -Generates a password reset URL for a user. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

- # - users/set-password -

- - -Changes a user’s password. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

Options

- - ---password -: The user’s new password. - - - -## `utils/ascii-filenames` - - -

- # - utils/ascii-filenames -

- - -Converts all non-ASCII asset filenames to ASCII. - -## `utils/fix-element-uids` - - -

- # - utils/fix-element-uids -

- - -Ensures all elements UIDs are unique. - -## `utils/prune-provisional-drafts` - - -

- # - utils/prune-provisional-drafts -

- - -Prunes provisional drafts for elements that have more than one per user. - -

Options

- - ---dry-run -: Whether this is a dry run. - - - -## `utils/prune-revisions` - - -

- # - utils/prune-revisions -

- - -Prunes excess element revisions. - -

Options

- - ---max-revisions -: The maximum number of revisions an element can have. - - ---dry-run -: Whether this is a dry run. - - - -## `utils/repair` - -Repairs data. - -

- # - utils/repair/category-group-structure -

- - -Repairs structure data for a category group. - -

Parameters

- -handle -: The category group handle. - - - -

Options

- - ---dry-run -: Whether to only do a dry run of the repair process. - - - -

- # - utils/repair/project-config -

- - -Repairs double-packed associative arrays in the project config. - -

Options

- - ---dry-run -: Whether to only do a dry run of the repair process. - - - -

- # - utils/repair/section-structure -

- - -Repairs structure data for a section. - -

Parameters

- -handle -: The section handle. - - - -

Options

- - ---dry-run -: Whether to only do a dry run of the repair process. - - - -## `utils/update-usernames` - - -

- # - utils/update-usernames -

- - -Updates all users’ usernames to ensure they match their email address. - - + +!!!include(docs/.artifacts/cms/3.x/console-commands.md)!!! diff --git a/docs/3.x/dev/controller-actions.md b/docs/3.x/dev/controller-actions.md index f898a476d..404b41de2 100644 --- a/docs/3.x/dev/controller-actions.md +++ b/docs/3.x/dev/controller-actions.md @@ -34,7 +34,7 @@ The following params can be sent with the request: Param | Description ----- | ----------- -`authorId` | The ID of the user account that should be set as the entry author. (Defaults to the entry’s current author, or the logged-in user.) +`author` | The ID of the user account that should be set as the entry author. (Defaults to the entry’s current author, or the logged-in user.) `enabledForSite` | Whether the entry should be enabled for the current site (`1`/`0`), or an array of site IDs that the entry should be enabled for. (Defaults to the `enabled` param.) `enabled` | Whether the entry should be enabled (`1`/`0`). (Defaults to enabled.) `entryId` | Fallback if `sourceId` isn’t passed, for backwards compatibility. diff --git a/docs/3.x/entries.md b/docs/3.x/entries.md index 4f1f88b3e..71775f8b4 100644 --- a/docs/3.x/entries.md +++ b/docs/3.x/entries.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Entries Entries hold the content that you want to display on your web pages. Each entry has an Author, a Post Date, an Expiration Date (if desired), a status (enabled or disabled), and of course, content. @@ -287,1970 +291,5 @@ We can display the 10 most recent entries in a “Blog” section by doing the f Entry queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [after](#after) | Narrows the query results to only entries that were posted on or after a certain date. -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [ancestorDist](#ancestordist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). -| [ancestorOf](#ancestorof) | Narrows the query results to only entries that are ancestors of another entry in its structure. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only entries that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching entries as arrays of data, rather than [Entry](craft3:craft\elements\Entry) objects. -| [authorGroup](#authorgroup) | Narrows the query results based on the user group the entries’ authors belong to. -| [authorGroupId](#authorgroupid) | Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. -| [authorId](#authorid) | Narrows the query results based on the entries’ authors. -| [before](#before) | Narrows the query results to only entries that were posted before a certain date. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#datecreated) | Narrows the query results based on the entries’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the entries’ last-updated dates. -| [descendantDist](#descendantdist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). -| [descendantOf](#descendantof) | Narrows the query results to only entries that are descendants of another entry in its structure. -| [draftCreator](#draftcreator) | Narrows the query results to only drafts created by a given user. -| [draftId](#draftid) | Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). -| [draftOf](#draftof) | Narrows the query results to only drafts of a given entry. -| [drafts](#drafts) | Narrows the query results to only drafts entries. -| [expiryDate](#expirydate) | Narrows the query results based on the entries’ expiry dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the entries have any descendants in their structure. -| [id](#id) | Narrows the query results based on the entries’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [leaves](#leaves) | Narrows the query results based on whether the entries are “leaves” (entries with no descendants). -| [level](#level) | Narrows the query results based on the entries’ level within the structure. -| [limit](#limit) | Determines the number of entries that should be returned. -| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the entry that comes immediately after another entry in its structure. -| [offset](#offset) | Determines how many entries should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`, or the order defined by the section if the [section](#section) or [sectionId](#sectionid) params are set to a single Structure section.) -| [positionedAfter](#positionedafter) | Narrows the query results to only entries that are positioned after another entry in its structure. -| [positionedBefore](#positionedbefore) | Narrows the query results to only entries that are positioned before another entry in its structure. -| [postDate](#postdate) | Narrows the query results based on the entries’ post dates. -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the entry that comes immediately before another entry in its structure. -| [provisionalDrafts](#provisionaldrafts) | Narrows the query results to only provisional drafts. -| [relatedTo](#relatedto) | Narrows the query results to only entries that are related to certain other elements. -| [revisionCreator](#revisioncreator) | Narrows the query results to only revisions created by a given user. -| [revisionId](#revisionid) | Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). -| [revisionOf](#revisionof) | Narrows the query results to only revisions of a given entry. -| [revisions](#revisions) | Narrows the query results to only revision entries. -| [savedDraftsOnly](#saveddraftsonly) | Narrows the query results to only unpublished drafts which have been saved after initial creation. -| [search](#search) | Narrows the query results to only entries that match a search query. -| [section](#section) | Narrows the query results based on the sections the entries belong to. -| [sectionId](#sectionid) | Narrows the query results based on the sections the entries belong to, per the sections’ IDs. -| [siblingOf](#siblingof) | Narrows the query results to only entries that are siblings of another entry in its structure. -| [site](#site) | Determines which site(s) the entries should be queried in. -| [siteId](#siteid) | Determines which site(s) the entries should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the entries’ IDs in the `elements_sites` table. -| [slug](#slug) | Narrows the query results based on the entries’ slugs. -| [status](#status) | Narrows the query results based on the entries’ statuses. -| [title](#title) | Narrows the query results based on the entries’ titles. -| [trashed](#trashed) | Narrows the query results to only entries that have been soft-deleted. -| [type](#type) | Narrows the query results based on the entries’ entry types. -| [typeId](#typeid) | Narrows the query results based on the entries’ entry types, per the types’ IDs. -| [uid](#uid) | Narrows the query results based on the entries’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uri](#uri) | Narrows the query results based on the entries’ URIs. -| [with](#with) | Causes the query to return matching entries eager-loaded with related elements. - - - - - -#### `after` - -Narrows the query results to only entries that were posted on or after a certain date. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'2018-04-01'` | that were posted after 2018-04-01. -| a [DateTime](https://php.net/class.datetime) object | that were posted after the date represented by the object. - - - -::: code -```twig -{# Fetch entries posted this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set entries = craft.entries() - .after(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch entries posted this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$entries = \craft\elements\Entry::find() - ->after($firstDayOfMonth) - ->all(); -``` -::: - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `ancestorDist` - -Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). - - - - - -::: code -```twig -{# Fetch entries above this one #} -{% set entries = craft.entries() - .ancestorOf(myEntry) - .ancestorDist(3) - .all() %} -``` - -```php -// Fetch entries above this one -$entries = \craft\elements\Entry::find() - ->ancestorOf($myEntry) - ->ancestorDist(3) - ->all(); -``` -::: - - -#### `ancestorOf` - -Narrows the query results to only entries that are ancestors of another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | above the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | above the entry represented by the object. - - - -::: code -```twig -{# Fetch entries above this one #} -{% set entries = craft.entries() - .ancestorOf(myEntry) - .all() %} -``` - -```php -// Fetch entries above this one -$entries = \craft\elements\Entry::find() - ->ancestorOf($myEntry) - ->all(); -``` -::: - - - -::: tip -This can be combined with [ancestorDist](#ancestordist) if you want to limit how far away the ancestor entries can be. -::: - - -#### `andRelatedTo` - -Narrows the query results to only entries that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all entries that are related to myCategoryA and myCategoryB #} -{% set entries = craft.entries() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all entries that are related to $myCategoryA and $myCategoryB -$entries = \craft\elements\Entry::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all entries, regardless of status #} -{% set entries = craft.entries() - .anyStatus() - .all() %} -``` - -```php -// Fetch all entries, regardless of status -$entries = \craft\elements\Entry::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching entries as arrays of data, rather than [Entry](craft3:craft\elements\Entry) objects. - - - - - -::: code -```twig -{# Fetch entries as arrays #} -{% set entries = craft.entries() - .asArray() - .all() %} -``` - -```php -// Fetch entries as arrays -$entries = \craft\elements\Entry::find() - ->asArray() - ->all(); -``` -::: - - -#### `authorGroup` - -Narrows the query results based on the user group the entries’ authors belong to. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | with an author in a group with a handle of `foo`. -| `'not foo'` | not with an author in a group with a handle of `foo`. -| `['foo', 'bar']` | with an author in a group with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not with an author in a group with a handle of `foo` or `bar`. -| a [UserGroup](craft3:craft\models\UserGroup) object | with an author in a group represented by the object. - - - -::: code -```twig -{# Fetch entries with an author in the Foo user group #} -{% set entries = craft.entries() - .authorGroup('foo') - .all() %} -``` - -```php -// Fetch entries with an author in the Foo user group -$entries = \craft\elements\Entry::find() - ->authorGroup('foo') - ->all(); -``` -::: - - -#### `authorGroupId` - -Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with an author in a group with an ID of 1. -| `'not 1'` | not with an author in a group with an ID of 1. -| `[1, 2]` | with an author in a group with an ID of 1 or 2. -| `['not', 1, 2]` | not with an author in a group with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch entries with an author in a group with an ID of 1 #} -{% set entries = craft.entries() - .authorGroupId(1) - .all() %} -``` - -```php -// Fetch entries with an author in a group with an ID of 1 -$entries = \craft\elements\Entry::find() - ->authorGroupId(1) - ->all(); -``` -::: - - -#### `authorId` - -Narrows the query results based on the entries’ authors. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with an author with an ID of 1. -| `'not 1'` | not with an author with an ID of 1. -| `[1, 2]` | with an author with an ID of 1 or 2. -| `['not', 1, 2]` | not with an author with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch entries with an author with an ID of 1 #} -{% set entries = craft.entries() - .authorId(1) - .all() %} -``` - -```php -// Fetch entries with an author with an ID of 1 -$entries = \craft\elements\Entry::find() - ->authorId(1) - ->all(); -``` -::: - - -#### `before` - -Narrows the query results to only entries that were posted before a certain date. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'2018-04-01'` | that were posted before 2018-04-01. -| a [DateTime](https://php.net/class.datetime) object | that were posted before the date represented by the object. - - - -::: code -```twig -{# Fetch entries posted before this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set entries = craft.entries() - .before(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch entries posted before this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$entries = \craft\elements\Entry::find() - ->before($firstDayOfMonth) - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `dateCreated` - -Narrows the query results based on the entries’ creation dates. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch entries created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set entries = craft.entries() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch entries created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$entries = \craft\elements\Entry::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the entries’ last-updated dates. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch entries updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set entries = craft.entries() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch entries updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$entries = \craft\elements\Entry::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `descendantDist` - -Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). - - - - - -::: code -```twig -{# Fetch entries below this one #} -{% set entries = craft.entries() - .descendantOf(myEntry) - .descendantDist(3) - .all() %} -``` - -```php -// Fetch entries below this one -$entries = \craft\elements\Entry::find() - ->descendantOf($myEntry) - ->descendantDist(3) - ->all(); -``` -::: - - -#### `descendantOf` - -Narrows the query results to only entries that are descendants of another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | below the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | below the entry represented by the object. - - - -::: code -```twig -{# Fetch entries below this one #} -{% set entries = craft.entries() - .descendantOf(myEntry) - .all() %} -``` - -```php -// Fetch entries below this one -$entries = \craft\elements\Entry::find() - ->descendantOf($myEntry) - ->all(); -``` -::: - - - -::: tip -This can be combined with [descendantDist](#descendantdist) if you want to limit how far away the descendant entries can be. -::: - - -#### `draftCreator` - -Narrows the query results to only drafts created by a given user. - - - -Possible values include: - -| Value | Fetches drafts… -| - | - -| `1` | created by the user with an ID of 1. -| a [craft\elements\User](craft3:craft\elements\User) object | created by the user represented by the object. - - - -::: code -```twig -{# Fetch drafts by the current user #} -{% set entries = craft.entries() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch drafts by the current user -$entries = \craft\elements\Entry::find() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -#### `draftId` - -Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). - - - -Possible values include: - -| Value | Fetches drafts… -| - | - -| `1` | for the draft with an ID of 1. - - - -::: code -```twig -{# Fetch a draft #} -{% set entries = craft.entries() - .draftId(10) - .all() %} -``` - -```php -// Fetch a draft -$entries = \craft\elements\Entry::find() - ->draftId(10) - ->all(); -``` -::: - - -#### `draftOf` - -Narrows the query results to only drafts of a given entry. - - - -Possible values include: - -| Value | Fetches drafts… -| - | - -| `1` | for the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | for the entry represented by the object. -| `'*'` | for any entry -| `false` | that aren’t associated with a published entry - - - -::: code -```twig -{# Fetch drafts of the entry #} -{% set entries = craft.entries() - .draftOf(myEntry) - .all() %} -``` - -```php -// Fetch drafts of the entry -$entries = \craft\elements\Entry::find() - ->draftOf($myEntry) - ->all(); -``` -::: - - -#### `drafts` - -Narrows the query results to only drafts entries. - - - - - -::: code -```twig -{# Fetch a draft entry #} -{% set entries = craft.entries() - .drafts() - .id(123) - .one() %} -``` - -```php -// Fetch a draft entry -$entries = \craft\elements\Entry::find() - ->drafts() - ->id(123) - ->one(); -``` -::: - - -#### `expiryDate` - -Narrows the query results based on the entries’ expiry dates. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `':empty:'` | that don’t have an expiry date. -| `':notempty:'` | that have an expiry date. -| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. -| `'< 2020-05-01'` | that will expire before 2020-05-01 -| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. - - - -::: code -```twig -{# Fetch entries expiring this month #} -{% set nextMonth = date('first day of next month')|atom %} - -{% set entries = craft.entries() - .expiryDate("< #{nextMonth}") - .all() %} -``` - -```php -// Fetch entries expiring this month -$nextMonth = (new \DateTime('first day of next month'))->format(\DateTime::ATOM); - -$entries = \craft\elements\Entry::find() - ->expiryDate("< {$nextMonth}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch entries in a specific order #} -{% set entries = craft.entries() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch entries in a specific order -$entries = \craft\elements\Entry::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `hasDescendants` - -Narrows the query results based on whether the entries have any descendants in their structure. - - - -(This has the opposite effect of calling [leaves](#leaves).) - - - -::: code -```twig -{# Fetch entries that have descendants #} -{% set entries = craft.entries() - .hasDescendants() - .all() %} -``` - -```php -// Fetch entries that have descendants -$entries = \craft\elements\Entry::find() - ->hasDescendants() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the entries’ IDs. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the entry by its ID #} -{% set entry = craft.entries() - .id(1) - .one() %} -``` - -```php -// Fetch the entry by its ID -$entry = \craft\elements\Entry::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch entries in reverse #} -{% set entries = craft.entries() - .inReverse() - .all() %} -``` - -```php -// Fetch entries in reverse -$entries = \craft\elements\Entry::find() - ->inReverse() - ->all(); -``` -::: - - -#### `leaves` - -Narrows the query results based on whether the entries are “leaves” (entries with no descendants). - - - -(This has the opposite effect of calling [hasDescendants](#hasdescendants).) - - - -::: code -```twig -{# Fetch entries that have no descendants #} -{% set entries = craft.entries() - .leaves() - .all() %} -``` - -```php -// Fetch entries that have no descendants -$entries = \craft\elements\Entry::find() - ->leaves() - ->all(); -``` -::: - - -#### `level` - -Narrows the query results based on the entries’ level within the structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with a level of 1. -| `'not 1'` | not with a level of 1. -| `'>= 3'` | with a level greater than or equal to 3. -| `[1, 2]` | with a level of 1 or 2 -| `['not', 1, 2]` | not with level of 1 or 2. - - - -::: code -```twig -{# Fetch entries positioned at level 3 or above #} -{% set entries = craft.entries() - .level('>= 3') - .all() %} -``` - -```php -// Fetch entries positioned at level 3 or above -$entries = \craft\elements\Entry::find() - ->level('>= 3') - ->all(); -``` -::: - - -#### `limit` - -Determines the number of entries that should be returned. - - - -::: code -```twig -{# Fetch up to 10 entries #} -{% set entries = craft.entries() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 entries -$entries = \craft\elements\Entry::find() - ->limit(10) - ->all(); -``` -::: - - -#### `nextSiblingOf` - -Narrows the query results to only the entry that comes immediately after another entry in its structure. - - - -Possible values include: - -| Value | Fetches the entry… -| - | - -| `1` | after the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | after the entry represented by the object. - - - -::: code -```twig -{# Fetch the next entry #} -{% set entry = craft.entries() - .nextSiblingOf(myEntry) - .one() %} -``` - -```php -// Fetch the next entry -$entry = \craft\elements\Entry::find() - ->nextSiblingOf($myEntry) - ->one(); -``` -::: - - -#### `offset` - -Determines how many entries should be skipped in the results. - - - -::: code -```twig -{# Fetch all entries except for the first 3 #} -{% set entries = craft.entries() - .offset(3) - .all() %} -``` - -```php -// Fetch all entries except for the first 3 -$entries = \craft\elements\Entry::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`, or the order defined by the section if the [section](#section) or [sectionId](#sectionid) params are set to a single Structure section.) - - - -::: code -```twig -{# Fetch all entries in order of date created #} -{% set entries = craft.entries() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all entries in order of date created -$entries = \craft\elements\Entry::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `positionedAfter` - -Narrows the query results to only entries that are positioned after another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | after the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | after the entry represented by the object. - - - -::: code -```twig -{# Fetch entries after this one #} -{% set entries = craft.entries() - .positionedAfter(myEntry) - .all() %} -``` - -```php -// Fetch entries after this one -$entries = \craft\elements\Entry::find() - ->positionedAfter($myEntry) - ->all(); -``` -::: - - -#### `positionedBefore` - -Narrows the query results to only entries that are positioned before another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | before the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | before the entry represented by the object. - - - -::: code -```twig -{# Fetch entries before this one #} -{% set entries = craft.entries() - .positionedBefore(myEntry) - .all() %} -``` - -```php -// Fetch entries before this one -$entries = \craft\elements\Entry::find() - ->positionedBefore($myEntry) - ->all(); -``` -::: - - -#### `postDate` - -Narrows the query results based on the entries’ post dates. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. -| `'< 2018-05-01'` | that were posted before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch entries posted last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set entries = craft.entries() - .postDate(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch entries posted last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$entries = \craft\elements\Entry::find() - ->postDate(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique entries from Site A, or Site B if they don’t exist in Site A #} -{% set entries = craft.entries() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique entries from Site A, or Site B if they don’t exist in Site A -$entries = \craft\elements\Entry::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prevSiblingOf` - -Narrows the query results to only the entry that comes immediately before another entry in its structure. - - - -Possible values include: - -| Value | Fetches the entry… -| - | - -| `1` | before the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | before the entry represented by the object. - - - -::: code -```twig -{# Fetch the previous entry #} -{% set entry = craft.entries() - .prevSiblingOf(myEntry) - .one() %} -``` - -```php -// Fetch the previous entry -$entry = \craft\elements\Entry::find() - ->prevSiblingOf($myEntry) - ->one(); -``` -::: - - -#### `provisionalDrafts` - -Narrows the query results to only provisional drafts. - - - - - -::: code -```twig -{# Fetch provisional drafts created by the current user #} -{% set entries = craft.entries() - .provisionalDrafts() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch provisional drafts created by the current user -$entries = \craft\elements\Entry::find() - ->provisionalDrafts() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only entries that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all entries that are related to myCategory #} -{% set entries = craft.entries() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all entries that are related to $myCategory -$entries = \craft\elements\Entry::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `revisionCreator` - -Narrows the query results to only revisions created by a given user. - - - -Possible values include: - -| Value | Fetches revisions… -| - | - -| `1` | created by the user with an ID of 1. -| a [craft\elements\User](craft3:craft\elements\User) object | created by the user represented by the object. - - - -::: code -```twig -{# Fetch revisions by the current user #} -{% set entries = craft.entries() - .revisionCreator(currentUser) - .all() %} -``` - -```php -// Fetch revisions by the current user -$entries = \craft\elements\Entry::find() - ->revisionCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -#### `revisionId` - -Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). - - - -Possible values include: - -| Value | Fetches revisions… -| - | - -| `1` | for the revision with an ID of 1. - - - -::: code -```twig -{# Fetch a revision #} -{% set entries = craft.entries() - .revisionId(10) - .all() %} -``` - -```php -// Fetch a revision -$entries = \craft\elements\Entry::find() - ->revisionIf(10) - ->all(); -``` -::: - - -#### `revisionOf` - -Narrows the query results to only revisions of a given entry. - - - -Possible values include: - -| Value | Fetches revisions… -| - | - -| `1` | for the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | for the entry represented by the object. - - - -::: code -```twig -{# Fetch revisions of the entry #} -{% set entries = craft.entries() - .revisionOf(myEntry) - .all() %} -``` - -```php -// Fetch revisions of the entry -$entries = \craft\elements\Entry::find() - ->revisionOf($myEntry) - ->all(); -``` -::: - - -#### `revisions` - -Narrows the query results to only revision entries. - - - - - -::: code -```twig -{# Fetch a revision entry #} -{% set entries = craft.entries() - .revisions() - .id(123) - .one() %} -``` - -```php -// Fetch a revision entry -$entries = \craft\elements\Entry::find() - ->revisions() - ->id(123) - ->one(); -``` -::: - - -#### `savedDraftsOnly` - -Narrows the query results to only unpublished drafts which have been saved after initial creation. - - - - - -::: code -```twig -{# Fetch saved, unpublished draft entries #} -{% set entries = craft.entries() - .draftOf(false) - .savedDraftsOnly() - .all() %} -``` - -```php -// Fetch saved, unpublished draft entries -$entries = \craft\elements\Entry::find() - ->draftOf(false) - ->savedDraftsOnly() - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only entries that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all entries that match the search query #} -{% set entries = craft.entries() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all entries that match the search query -$entries = \craft\elements\Entry::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `section` - -Narrows the query results based on the sections the entries belong to. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | in a section with a handle of `foo`. -| `'not foo'` | not in a section with a handle of `foo`. -| `['foo', 'bar']` | in a section with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a section with a handle of `foo` or `bar`. -| a [Section](craft3:craft\models\Section) object | in a section represented by the object. - - - -::: code -```twig -{# Fetch entries in the Foo section #} -{% set entries = craft.entries() - .section('foo') - .all() %} -``` - -```php -// Fetch entries in the Foo section -$entries = \craft\elements\Entry::find() - ->section('foo') - ->all(); -``` -::: - - -#### `sectionId` - -Narrows the query results based on the sections the entries belong to, per the sections’ IDs. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | in a section with an ID of 1. -| `'not 1'` | not in a section with an ID of 1. -| `[1, 2]` | in a section with an ID of 1 or 2. -| `['not', 1, 2]` | not in a section with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch entries in the section with an ID of 1 #} -{% set entries = craft.entries() - .sectionId(1) - .all() %} -``` - -```php -// Fetch entries in the section with an ID of 1 -$entries = \craft\elements\Entry::find() - ->sectionId(1) - ->all(); -``` -::: - - -#### `siblingOf` - -Narrows the query results to only entries that are siblings of another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | beside the entry with an ID of 1. -| a [Entry](craft3:craft\elements\Entry) object | beside the entry represented by the object. - - - -::: code -```twig -{# Fetch entries beside this one #} -{% set entries = craft.entries() - .siblingOf(myEntry) - .all() %} -``` - -```php -// Fetch entries beside this one -$entries = \craft\elements\Entry::find() - ->siblingOf($myEntry) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the entries should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch entries from the Foo site #} -{% set entries = craft.entries() - .site('foo') - .all() %} -``` - -```php -// Fetch entries from the Foo site -$entries = \craft\elements\Entry::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the entries should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch entries from the site with an ID of 1 #} -{% set entries = craft.entries() - .siteId(1) - .all() %} -``` - -```php -// Fetch entries from the site with an ID of 1 -$entries = \craft\elements\Entry::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the entries’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the entry by its ID in the elements_sites table #} -{% set entry = craft.entries() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the entry by its ID in the elements_sites table -$entry = \craft\elements\Entry::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `slug` - -Narrows the query results based on the entries’ slugs. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | with a slug of `foo`. -| `'foo*'` | with a slug that begins with `foo`. -| `'*foo'` | with a slug that ends with `foo`. -| `'*foo*'` | with a slug that contains `foo`. -| `'not *foo*'` | with a slug that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested entry slug from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the entry with that slug #} -{% set entry = craft.entries() - .slug(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested entry slug from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the entry with that slug -$entry = \craft\elements\Entry::find() - ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the entries’ statuses. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'live'` _(default)_ | that are live. -| `'pending'` | that are pending (enabled with a Post Date in the future). -| `'expired'` | that are expired (enabled with an Expiry Date in the past). -| `'disabled'` | that are disabled. -| `['live', 'pending']` | that are live or pending. -| `['not', 'live', 'pending']` | that are not live or pending. - - - -::: code -```twig -{# Fetch disabled entries #} -{% set entries = craft.entries() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled entries -$entries = \craft\elements\Entry::find() - ->status('disabled') - ->all(); -``` -::: - - -#### `title` - -Narrows the query results based on the entries’ titles. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch entries with a title that contains "Foo" #} -{% set entries = craft.entries() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch entries with a title that contains "Foo" -$entries = \craft\elements\Entry::find() - ->title('*Foo*') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only entries that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed entries #} -{% set entries = craft.entries() - .trashed() - .all() %} -``` - -```php -// Fetch trashed entries -$entries = \craft\elements\Entry::find() - ->trashed() - ->all(); -``` -::: - - -#### `type` - -Narrows the query results based on the entries’ entry types. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | of a type with a handle of `foo`. -| `'not foo'` | not of a type with a handle of `foo`. -| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. -| an [EntryType](craft3:craft\models\EntryType) object | of a type represented by the object. - - - -::: code -```twig -{# Fetch entries in the Foo section with a Bar entry type #} -{% set entries = craft.entries() - .section('foo') - .type('bar') - .all() %} -``` - -```php -// Fetch entries in the Foo section with a Bar entry type -$entries = \craft\elements\Entry::find() - ->section('foo') - ->type('bar') - ->all(); -``` -::: - - -#### `typeId` - -Narrows the query results based on the entries’ entry types, per the types’ IDs. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | of a type with an ID of 1. -| `'not 1'` | not of a type with an ID of 1. -| `[1, 2]` | of a type with an ID of 1 or 2. -| `['not', 1, 2]` | not of a type with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch entries of the entry type with an ID of 1 #} -{% set entries = craft.entries() - .typeId(1) - .all() %} -``` - -```php -// Fetch entries of the entry type with an ID of 1 -$entries = \craft\elements\Entry::find() - ->typeId(1) - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the entries’ UIDs. - - - - - -::: code -```twig -{# Fetch the entry by its UID #} -{% set entry = craft.entries() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the entry by its UID -$entry = \craft\elements\Entry::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique entries across all sites #} -{% set entries = craft.entries() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique entries across all sites -$entries = \craft\elements\Entry::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `uri` - -Narrows the query results based on the entries’ URIs. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the entry with that URI #} -{% set entry = craft.entries() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the entry with that URI -$entry = \craft\elements\Entry::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching entries eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch entries eager-loaded with the "Related" field’s relations #} -{% set entries = craft.entries() - .with(['related']) - .all() %} -``` - -```php -// Fetch entries eager-loaded with the "Related" field’s relations -$entries = \craft\elements\Entry::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/3.x/entries.md)!!! diff --git a/docs/3.x/extend/changelogs-and-updates.md b/docs/3.x/extend/changelogs-and-updates.md index e1161a0d9..0da9d817a 100644 --- a/docs/3.x/extend/changelogs-and-updates.md +++ b/docs/3.x/extend/changelogs-and-updates.md @@ -39,22 +39,22 @@ All content that follows a version heading (up to the next H2) will be treated a When writing release notes, we recommend that you follow the guidelines at [keepachangelog.com](https://keepachangelog.com/), but all forms of [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) are allowed. The only thing that is *not* allowed is actual HTML code, which will be escaped. -### Notes, Warnings, and Tips +### Alerts -You can include important notes, warnings, and tips in your release notes using this syntax: +You can include notes and warnings in your release notes using [GitHub’s alert syntax](https://github.com/orgs/community/discussions/16925): ```markdown -> **Note** -> An important note. +> [!NOTE] +> Highlights information that users should take into account, even when skimming. -> **Warning** -> A word of warning. +> [!IMPORTANT] +> Crucial information necessary for users to succeed. -> **Tip** -> A helpful tip. +> [!WARNING] +> Critical content demanding immediate user attention due to potential risks. ``` -These notes will each be styled appropriately within the plugin’s changelog in the Plugin Store and within the Updates utility. The Updates utility will also auto-expand any updates that contain a note. +These alerts will each be styled appropriately within the plugin’s changelog in the Plugin Store and within the Updates utility. Updates which contain alerts will automatically be expanded in the Updates utility. ### Links diff --git a/docs/3.x/extend/plugin-store.md b/docs/3.x/extend/plugin-store.md index 6029fe189..2428ae9b7 100644 --- a/docs/3.x/extend/plugin-store.md +++ b/docs/3.x/extend/plugin-store.md @@ -4,20 +4,28 @@ If you want to make your plugin available in the in-app Plugin Store, and on [pl ## Choose a License -All plugins in the Plugin Store must have one of two licenses: +All plugins in the Plugin Store must select a software license. -- **[MIT](https://opensource.org/licenses/MIT)** – Use this if you aren’t planning on ever charging for your plugin, and you’re OK with other people pretty much doing whatever they want with your code, as long as they give credit back to you. ([Example](https://github.com/craftcms/element-api/blob/v2/LICENSE.md)) -- **[Craft](https://craftcms.github.io/license/)** – Use this if you are planning on charging for your plugin, and want to prevent people from using your code without paying up. ([Example](https://github.com/craftcms/cms/blob/develop/LICENSE.md)) +Commercial plugins are recommended to use the [Craft license](https://raw.githubusercontent.com/craftcms/license/master/index.md). -Create a `LICENSE.md` file at the root of your plugin’s repository, and paste in the license text, beginning with a copyright notice. +To use the Craft license: -``` -Copyright © -``` +1. Copy the license text into a `LICENSE.md` file at the root of your repository, and replace `[YOUR_NAME_HERE]` with your personal/organization name. +2. Set the `license` value in `composer.json` to `"proprietary"`. -::: tip -If you are going with the Craft License, don’t forget to change the `license` value in your `composer.json` file from `MIT` to `proprietary`. -::: +The following open source licenses are also allowed: + +- [Apache-2.0](https://raw.githubusercontent.com/licenses/license-templates/master/templates/apache.txt) +- [GPL-2.0](https://raw.githubusercontent.com/licenses/license-templates/master/templates/gpl2.txt) +- [GPL-3.0](https://raw.githubusercontent.com/licenses/license-templates/master/templates/gpl3.txt) +- [MIT](https://raw.githubusercontent.com/licenses/license-templates/master/templates/mit.txt) + +The MIT license is generally recommended, unless you have a good reason to use something else. + +To use an open source license: + +1. Copy the license text into a `LICENSE.txt` file at the root of your repository, prefixed with a copyright notice (e.g. `Copyright (c) Pixel & Tonic, Inc.`). +2. Set the `license` value in `composer.json` to the appropriate [license name](https://getcomposer.org/doc/04-schema.md#license). ## Registering your Plugin diff --git a/docs/3.x/globals.md b/docs/3.x/globals.md index 1fd79299a..cfe294421 100644 --- a/docs/3.x/globals.md +++ b/docs/3.x/globals.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Globals Globals store content that is available globally throughout your templates. They’re a convenient way to make non-Entry content easily editable via the control panel. @@ -100,759 +104,5 @@ All global sets are already available as global variables to Twig templates. So Global set queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only global sets that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](craft3:craft\elements\GlobalSet) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#datecreated) | Narrows the query results based on the global sets’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the global sets’ last-updated dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [handle](#handle) | Narrows the query results based on the global sets’ handles. -| [id](#id) | Narrows the query results based on the global sets’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [limit](#limit) | Determines the number of global sets that should be returned. -| [offset](#offset) | Determines how many global sets should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the global sets should be returned in. (If empty, defaults to `name ASC`.) -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [relatedTo](#relatedto) | Narrows the query results to only global sets that are related to certain other elements. -| [search](#search) | Narrows the query results to only global sets that match a search query. -| [site](#site) | Determines which site(s) the global sets should be queried in. -| [siteId](#siteid) | Determines which site(s) the global sets should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the global sets’ IDs in the `elements_sites` table. -| [trashed](#trashed) | Narrows the query results to only global sets that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the global sets’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [with](#with) | Causes the query to return matching global sets eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only global sets that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all global sets that are related to myCategoryA and myCategoryB #} -{% set globalSets = craft.globalSets() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all global sets that are related to $myCategoryA and $myCategoryB -$globalSets = \craft\elements\GlobalSet::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all global sets, regardless of status #} -{% set globalSets = craft.globalSets() - .anyStatus() - .all() %} -``` - -```php -// Fetch all global sets, regardless of status -$globalSets = \craft\elements\GlobalSet::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](craft3:craft\elements\GlobalSet) objects. - - - - - -::: code -```twig -{# Fetch global sets as arrays #} -{% set globalSets = craft.globalSets() - .asArray() - .all() %} -``` - -```php -// Fetch global sets as arrays -$globalSets = \craft\elements\GlobalSet::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `dateCreated` - -Narrows the query results based on the global sets’ creation dates. - - - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch global sets created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set globalSets = craft.globalSets() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch global sets created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$globalSets = \craft\elements\GlobalSet::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the global sets’ last-updated dates. - - - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch global sets updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set globalSets = craft.globalSets() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch global sets updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$globalSets = \craft\elements\GlobalSet::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch global sets in a specific order #} -{% set globalSets = craft.globalSets() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch global sets in a specific order -$globalSets = \craft\elements\GlobalSet::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `handle` - -Narrows the query results based on the global sets’ handles. - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `'foo'` | with a handle of `foo`. -| `'not foo'` | not with a handle of `foo`. -| `['foo', 'bar']` | with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not with a handle of `foo` or `bar`. - - - -::: code -```twig -{# Fetch the global set with a handle of 'foo' #} -{% set globalSet = craft.globalSets() - .handle('foo') - .one() %} -``` - -```php -// Fetch the global set with a handle of 'foo' -$globalSet = \craft\elements\GlobalSet::find() - ->handle('foo') - ->one(); -``` -::: - - -#### `id` - -Narrows the query results based on the global sets’ IDs. - - - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the global set by its ID #} -{% set globalSet = craft.globalSets() - .id(1) - .one() %} -``` - -```php -// Fetch the global set by its ID -$globalSet = \craft\elements\GlobalSet::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch global sets in reverse #} -{% set globalSets = craft.globalSets() - .inReverse() - .all() %} -``` - -```php -// Fetch global sets in reverse -$globalSets = \craft\elements\GlobalSet::find() - ->inReverse() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of global sets that should be returned. - - - -::: code -```twig -{# Fetch up to 10 global sets #} -{% set globalSets = craft.globalSets() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 global sets -$globalSets = \craft\elements\GlobalSet::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many global sets should be skipped in the results. - - - -::: code -```twig -{# Fetch all global sets except for the first 3 #} -{% set globalSets = craft.globalSets() - .offset(3) - .all() %} -``` - -```php -// Fetch all global sets except for the first 3 -$globalSets = \craft\elements\GlobalSet::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the global sets should be returned in. (If empty, defaults to `name ASC`.) - - - -::: code -```twig -{# Fetch all global sets in order of date created #} -{% set globalSets = craft.globalSets() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all global sets in order of date created -$globalSets = \craft\elements\GlobalSet::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique global sets from Site A, or Site B if they don’t exist in Site A #} -{% set globalSets = craft.globalSets() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique global sets from Site A, or Site B if they don’t exist in Site A -$globalSets = \craft\elements\GlobalSet::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only global sets that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all global sets that are related to myCategory #} -{% set globalSets = craft.globalSets() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all global sets that are related to $myCategory -$globalSets = \craft\elements\GlobalSet::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only global sets that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all global sets that match the search query #} -{% set globalSets = craft.globalSets() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all global sets that match the search query -$globalSets = \craft\elements\GlobalSet::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the global sets should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch global sets from the Foo site #} -{% set globalSets = craft.globalSets() - .site('foo') - .all() %} -``` - -```php -// Fetch global sets from the Foo site -$globalSets = \craft\elements\GlobalSet::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the global sets should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch global sets from the site with an ID of 1 #} -{% set globalSets = craft.globalSets() - .siteId(1) - .all() %} -``` - -```php -// Fetch global sets from the site with an ID of 1 -$globalSets = \craft\elements\GlobalSet::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the global sets’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the global set by its ID in the elements_sites table #} -{% set globalSet = craft.globalSets() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the global set by its ID in the elements_sites table -$globalSet = \craft\elements\GlobalSet::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `trashed` - -Narrows the query results to only global sets that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed global sets #} -{% set globalSets = craft.globalSets() - .trashed() - .all() %} -``` - -```php -// Fetch trashed global sets -$globalSets = \craft\elements\GlobalSet::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the global sets’ UIDs. - - - - - -::: code -```twig -{# Fetch the global set by its UID #} -{% set globalSet = craft.globalSets() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the global set by its UID -$globalSet = \craft\elements\GlobalSet::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique global sets across all sites #} -{% set globalSets = craft.globalSets() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique global sets across all sites -$globalSets = \craft\elements\GlobalSet::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching global sets eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch global sets eager-loaded with the "Related" field’s relations #} -{% set globalSets = craft.globalSets() - .with(['related']) - .all() %} -``` - -```php -// Fetch global sets eager-loaded with the "Related" field’s relations -$globalSets = \craft\elements\GlobalSet::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/3.x/globals.md)!!! diff --git a/docs/3.x/graphql.md b/docs/3.x/graphql.md index 82823c2a5..21efa6f6e 100644 --- a/docs/3.x/graphql.md +++ b/docs/3.x/graphql.md @@ -1,5 +1,6 @@ --- keywords: headless +containsGeneratedContent: yes --- # GraphQL API Pro @@ -1220,6 +1221,7 @@ This is the interface implemented by all entries. | `isDraft`| `Boolean` | Returns whether this is a draft. | `isRevision`| `Boolean` | Returns whether this is a revision. | `revisionId`| `Int` | The revision ID (from the `revisions` table). +| `revisionNotes`| `String` | The revision notes (from the `revisions` table). | `draftId`| `Int` | The draft ID (from the `drafts` table). | `isUnpublishedDraft`| `Boolean` | Returns whether this is an unpublished draft. | `isUnsavedDraft`| `Boolean` | Returns whether this is an unpublished draft. **This field is deprecated.** `isUnpublishedDraft` should be used instead. diff --git a/docs/3.x/matrix-blocks.md b/docs/3.x/matrix-blocks.md index 3b0c18ebd..1e6a1cede 100644 --- a/docs/3.x/matrix-blocks.md +++ b/docs/3.x/matrix-blocks.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Matrix Blocks If you’ve ever worked with a hairball of content and markup managed in an increasingly-fragile WYSIWYG field, you’re probably going to like Matrix blocks. @@ -58,981 +62,5 @@ In order for the returned Matrix block(s) to be populated with their custom fiel Matrix block queries support the following parameters: - - - - - - -| Param | Description -| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [allowOwnerDrafts](#allowownerdrafts) | Narrows the query results based on whether the Matrix blocks’ owners are drafts. -| [allowOwnerRevisions](#allowownerrevisions) | Narrows the query results based on whether the Matrix blocks’ owners are revisions. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](craft3:craft\elements\MatrixBlock) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#datecreated) | Narrows the query results based on the Matrix blocks’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the Matrix blocks’ last-updated dates. -| [field](#field) | Narrows the query results based on the field the Matrix blocks belong to. -| [fieldId](#fieldid) | Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [id](#id) | Narrows the query results based on the Matrix blocks’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [limit](#limit) | Determines the number of Matrix blocks that should be returned. -| [offset](#offset) | Determines how many Matrix blocks should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) -| [owner](#owner) | Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. -| [ownerId](#ownerid) | Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [relatedTo](#relatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. -| [search](#search) | Narrows the query results to only Matrix blocks that match a search query. -| [site](#site) | Determines which site(s) the Matrix blocks should be queried in. -| [siteId](#siteid) | Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the Matrix blocks’ IDs in the `elements_sites` table. -| [status](#status) | Narrows the query results based on the Matrix blocks’ statuses. -| [trashed](#trashed) | Narrows the query results to only Matrix blocks that have been soft-deleted. -| [type](#type) | Narrows the query results based on the Matrix blocks’ block types. -| [typeId](#typeid) | Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. -| [uid](#uid) | Narrows the query results based on the Matrix blocks’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [with](#with) | Causes the query to return matching Matrix blocks eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `allowOwnerDrafts` - -Narrows the query results based on whether the Matrix blocks’ owners are drafts. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `true` | which can belong to a draft. -| `false` | which cannot belong to a draft. - - - - -#### `allowOwnerRevisions` - -Narrows the query results based on whether the Matrix blocks’ owners are revisions. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `true` | which can belong to a revision. -| `false` | which cannot belong to a revision. - - - - -#### `andRelatedTo` - -Narrows the query results to only Matrix blocks that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all Matrix blocks that are related to myCategoryA and myCategoryB #} -{% set MatrixBlocks = craft.matrixBlocks() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all Matrix blocks that are related to $myCategoryA and $myCategoryB -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all Matrix blocks, regardless of status #} -{% set MatrixBlocks = craft.matrixBlocks() - .anyStatus() - .all() %} -``` - -```php -// Fetch all Matrix blocks, regardless of status -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](craft3:craft\elements\MatrixBlock) objects. - - - - - -::: code -```twig -{# Fetch Matrix blocks as arrays #} -{% set MatrixBlocks = craft.matrixBlocks() - .asArray() - .all() %} -``` - -```php -// Fetch Matrix blocks as arrays -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `dateCreated` - -Narrows the query results based on the Matrix blocks’ creation dates. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch Matrix blocks created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set MatrixBlocks = craft.matrixBlocks() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch Matrix blocks created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the Matrix blocks’ last-updated dates. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch Matrix blocks updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set MatrixBlocks = craft.matrixBlocks() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch Matrix blocks updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `field` - -Narrows the query results based on the field the Matrix blocks belong to. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'foo'` | in a field with a handle of `foo`. -| `'not foo'` | not in a field with a handle of `foo`. -| `['foo', 'bar']` | in a field with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a field with a handle of `foo` or `bar`. -| a [craft\fields\Matrix](craft3:craft\fields\Matrix) object | in a field represented by the object. - - - -::: code -```twig -{# Fetch Matrix blocks in the Foo field #} -{% set MatrixBlocks = craft.matrixBlocks() - .field('foo') - .all() %} -``` - -```php -// Fetch Matrix blocks in the Foo field -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->field('foo') - ->all(); -``` -::: - - -#### `fieldId` - -Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | in a field with an ID of 1. -| `'not 1'` | not in a field with an ID of 1. -| `[1, 2]` | in a field with an ID of 1 or 2. -| `['not', 1, 2]` | not in a field with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch Matrix blocks in the field with an ID of 1 #} -{% set MatrixBlocks = craft.matrixBlocks() - .fieldId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks in the field with an ID of 1 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->fieldId(1) - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch Matrix blocks in a specific order #} -{% set MatrixBlocks = craft.matrixBlocks() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch Matrix blocks in a specific order -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the Matrix blocks’ IDs. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the Matrix block by its ID #} -{% set MatrixBlock = craft.matrixBlocks() - .id(1) - .one() %} -``` - -```php -// Fetch the Matrix block by its ID -$MatrixBlock = \craft\elements\MatrixBlock::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch Matrix blocks in reverse #} -{% set MatrixBlocks = craft.matrixBlocks() - .inReverse() - .all() %} -``` - -```php -// Fetch Matrix blocks in reverse -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->inReverse() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of Matrix blocks that should be returned. - - - -::: code -```twig -{# Fetch up to 10 Matrix blocks #} -{% set MatrixBlocks = craft.matrixBlocks() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 Matrix blocks -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many Matrix blocks should be skipped in the results. - - - -::: code -```twig -{# Fetch all Matrix blocks except for the first 3 #} -{% set MatrixBlocks = craft.matrixBlocks() - .offset(3) - .all() %} -``` - -```php -// Fetch all Matrix blocks except for the first 3 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) - - - -::: code -```twig -{# Fetch all Matrix blocks in order of date created #} -{% set MatrixBlocks = craft.matrixBlocks() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all Matrix blocks in order of date created -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `owner` - -Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. - - - -::: code -```twig -{# Fetch Matrix blocks created for this entry #} -{% set MatrixBlocks = craft.matrixBlocks() - .owner(myEntry) - .all() %} -``` - -```php -// Fetch Matrix blocks created for this entry -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->owner($myEntry) - ->all(); -``` -::: - - -#### `ownerId` - -Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | created for an element with an ID of 1. -| `'not 1'` | not created for an element with an ID of 1. -| `[1, 2]` | created for an element with an ID of 1 or 2. -| `['not', 1, 2]` | not created for an element with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch Matrix blocks created for an element with an ID of 1 #} -{% set MatrixBlocks = craft.matrixBlocks() - .ownerId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks created for an element with an ID of 1 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->ownerId(1) - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique Matrix blocks from Site A, or Site B if they don’t exist in Site A #} -{% set MatrixBlocks = craft.matrixBlocks() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique Matrix blocks from Site A, or Site B if they don’t exist in Site A -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only Matrix blocks that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all Matrix blocks that are related to myCategory #} -{% set MatrixBlocks = craft.matrixBlocks() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all Matrix blocks that are related to $myCategory -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only Matrix blocks that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all Matrix blocks that match the search query #} -{% set MatrixBlocks = craft.matrixBlocks() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all Matrix blocks that match the search query -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the Matrix blocks should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch Matrix blocks from the Foo site #} -{% set MatrixBlocks = craft.matrixBlocks() - .site('foo') - .all() %} -``` - -```php -// Fetch Matrix blocks from the Foo site -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch Matrix blocks from the site with an ID of 1 #} -{% set MatrixBlocks = craft.matrixBlocks() - .siteId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks from the site with an ID of 1 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the Matrix blocks’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the Matrix block by its ID in the elements_sites table #} -{% set MatrixBlock = craft.matrixBlocks() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the Matrix block by its ID in the elements_sites table -$MatrixBlock = \craft\elements\MatrixBlock::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the Matrix blocks’ statuses. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'enabled'` _(default)_ | that are enabled. -| `'disabled'` | that are disabled. -| `['not', 'disabled']` | that are not disabled. - - - -::: code -```twig -{# Fetch disabled Matrix blocks #} -{% set MatrixBlocks = craft.matrixBlocks() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled Matrix blocks -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->status('disabled') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only Matrix blocks that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed Matrix blocks #} -{% set MatrixBlocks = craft.matrixBlocks() - .trashed() - .all() %} -``` - -```php -// Fetch trashed Matrix blocks -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->trashed() - ->all(); -``` -::: - - -#### `type` - -Narrows the query results based on the Matrix blocks’ block types. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'foo'` | of a type with a handle of `foo`. -| `'not foo'` | not of a type with a handle of `foo`. -| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. -| an [MatrixBlockType](craft3:craft\models\MatrixBlockType) object | of a type represented by the object. - - - -::: code -```twig -{# Fetch Matrix blocks with a Foo block type #} -{% set MatrixBlocks = myEntry.myMatrixField - .type('foo') - .all() %} -``` - -```php -// Fetch Matrix blocks with a Foo block type -$MatrixBlocks = $myEntry->myMatrixField - ->type('foo') - ->all(); -``` -::: - - -#### `typeId` - -Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | of a type with an ID of 1. -| `'not 1'` | not of a type with an ID of 1. -| `[1, 2]` | of a type with an ID of 1 or 2. -| `['not', 1, 2]` | not of a type with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch Matrix blocks of the block type with an ID of 1 #} -{% set MatrixBlocks = myEntry.myMatrixField - .typeId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks of the block type with an ID of 1 -$MatrixBlocks = $myEntry->myMatrixField - ->typeId(1) - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the Matrix blocks’ UIDs. - - - - - -::: code -```twig -{# Fetch the Matrix block by its UID #} -{% set MatrixBlock = craft.matrixBlocks() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the Matrix block by its UID -$MatrixBlock = \craft\elements\MatrixBlock::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique Matrix blocks across all sites #} -{% set MatrixBlocks = craft.matrixBlocks() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique Matrix blocks across all sites -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching Matrix blocks eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch Matrix blocks eager-loaded with the "Related" field’s relations #} -{% set MatrixBlocks = craft.matrixBlocks() - .with(['related']) - .all() %} -``` - -```php -// Fetch Matrix blocks eager-loaded with the "Related" field’s relations -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/3.x/matrix-blocks.md)!!! diff --git a/docs/3.x/tags.md b/docs/3.x/tags.md index 170c9d8d9..3a6d27a99 100644 --- a/docs/3.x/tags.md +++ b/docs/3.x/tags.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Tags You can create folksonomies for your [entries](entries.md), [users](users.md), and [assets](assets.md) using Tags. @@ -66,875 +70,5 @@ We can display a list of the tags in a “Blog Tags” tag group by doing the fo Tag queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only tags that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching tags as arrays of data, rather than [Tag](craft3:craft\elements\Tag) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#datecreated) | Narrows the query results based on the tags’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the tags’ last-updated dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [group](#group) | Narrows the query results based on the tag groups the tags belong to. -| [groupId](#groupid) | Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. -| [id](#id) | Narrows the query results based on the tags’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [limit](#limit) | Determines the number of tags that should be returned. -| [offset](#offset) | Determines how many tags should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [relatedTo](#relatedto) | Narrows the query results to only tags that are related to certain other elements. -| [search](#search) | Narrows the query results to only tags that match a search query. -| [site](#site) | Determines which site(s) the tags should be queried in. -| [siteId](#siteid) | Determines which site(s) the tags should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the tags’ IDs in the `elements_sites` table. -| [title](#title) | Narrows the query results based on the tags’ titles. -| [trashed](#trashed) | Narrows the query results to only tags that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the tags’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uri](#uri) | Narrows the query results based on the tags’ URIs. -| [with](#with) | Causes the query to return matching tags eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only tags that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all tags that are related to myCategoryA and myCategoryB #} -{% set tags = craft.tags() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all tags that are related to $myCategoryA and $myCategoryB -$tags = \craft\elements\Tag::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all tags, regardless of status #} -{% set tags = craft.tags() - .anyStatus() - .all() %} -``` - -```php -// Fetch all tags, regardless of status -$tags = \craft\elements\Tag::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching tags as arrays of data, rather than [Tag](craft3:craft\elements\Tag) objects. - - - - - -::: code -```twig -{# Fetch tags as arrays #} -{% set tags = craft.tags() - .asArray() - .all() %} -``` - -```php -// Fetch tags as arrays -$tags = \craft\elements\Tag::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `dateCreated` - -Narrows the query results based on the tags’ creation dates. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch tags created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set tags = craft.tags() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch tags created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$tags = \craft\elements\Tag::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the tags’ last-updated dates. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch tags updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set tags = craft.tags() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch tags updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$tags = \craft\elements\Tag::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch tags in a specific order #} -{% set tags = craft.tags() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch tags in a specific order -$tags = \craft\elements\Tag::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `group` - -Narrows the query results based on the tag groups the tags belong to. - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'foo'` | in a group with a handle of `foo`. -| `'not foo'` | not in a group with a handle of `foo`. -| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. -| a [TagGroup](craft3:craft\models\TagGroup) object | in a group represented by the object. - - - -::: code -```twig -{# Fetch tags in the Foo group #} -{% set tags = craft.tags() - .group('foo') - .all() %} -``` - -```php -// Fetch tags in the Foo group -$tags = \craft\elements\Tag::find() - ->group('foo') - ->all(); -``` -::: - - -#### `groupId` - -Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. - -Possible values include: - -| Value | Fetches tags… -| - | - -| `1` | in a group with an ID of 1. -| `'not 1'` | not in a group with an ID of 1. -| `[1, 2]` | in a group with an ID of 1 or 2. -| `['not', 1, 2]` | not in a group with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch tags in the group with an ID of 1 #} -{% set tags = craft.tags() - .groupId(1) - .all() %} -``` - -```php -// Fetch tags in the group with an ID of 1 -$tags = \craft\elements\Tag::find() - ->groupId(1) - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the tags’ IDs. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the tag by its ID #} -{% set tag = craft.tags() - .id(1) - .one() %} -``` - -```php -// Fetch the tag by its ID -$tag = \craft\elements\Tag::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch tags in reverse #} -{% set tags = craft.tags() - .inReverse() - .all() %} -``` - -```php -// Fetch tags in reverse -$tags = \craft\elements\Tag::find() - ->inReverse() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of tags that should be returned. - - - -::: code -```twig -{# Fetch up to 10 tags #} -{% set tags = craft.tags() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 tags -$tags = \craft\elements\Tag::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many tags should be skipped in the results. - - - -::: code -```twig -{# Fetch all tags except for the first 3 #} -{% set tags = craft.tags() - .offset(3) - .all() %} -``` - -```php -// Fetch all tags except for the first 3 -$tags = \craft\elements\Tag::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) - - - -::: code -```twig -{# Fetch all tags in order of date created #} -{% set tags = craft.tags() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all tags in order of date created -$tags = \craft\elements\Tag::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique tags from Site A, or Site B if they don’t exist in Site A #} -{% set tags = craft.tags() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique tags from Site A, or Site B if they don’t exist in Site A -$tags = \craft\elements\Tag::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only tags that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all tags that are related to myCategory #} -{% set tags = craft.tags() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all tags that are related to $myCategory -$tags = \craft\elements\Tag::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only tags that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all tags that match the search query #} -{% set tags = craft.tags() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all tags that match the search query -$tags = \craft\elements\Tag::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the tags should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft3:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch tags from the Foo site #} -{% set tags = craft.tags() - .site('foo') - .all() %} -``` - -```php -// Fetch tags from the Foo site -$tags = \craft\elements\Tag::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the tags should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches tags… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch tags from the site with an ID of 1 #} -{% set tags = craft.tags() - .siteId(1) - .all() %} -``` - -```php -// Fetch tags from the site with an ID of 1 -$tags = \craft\elements\Tag::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the tags’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the tag by its ID in the elements_sites table #} -{% set tag = craft.tags() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the tag by its ID in the elements_sites table -$tag = \craft\elements\Tag::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `title` - -Narrows the query results based on the tags’ titles. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch tags with a title that contains "Foo" #} -{% set tags = craft.tags() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch tags with a title that contains "Foo" -$tags = \craft\elements\Tag::find() - ->title('*Foo*') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only tags that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed tags #} -{% set tags = craft.tags() - .trashed() - .all() %} -``` - -```php -// Fetch trashed tags -$tags = \craft\elements\Tag::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the tags’ UIDs. - - - - - -::: code -```twig -{# Fetch the tag by its UID #} -{% set tag = craft.tags() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the tag by its UID -$tag = \craft\elements\Tag::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique tags across all sites #} -{% set tags = craft.tags() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique tags across all sites -$tags = \craft\elements\Tag::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `uri` - -Narrows the query results based on the tags’ URIs. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the tag with that URI #} -{% set tag = craft.tags() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the tag with that URI -$tag = \craft\elements\Tag::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching tags eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch tags eager-loaded with the "Related" field’s relations #} -{% set tags = craft.tags() - .with(['related']) - .all() %} -``` - -```php -// Fetch tags eager-loaded with the "Related" field’s relations -$tags = \craft\elements\Tag::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/3.x/tags.md)!!! diff --git a/docs/3.x/users.md b/docs/3.x/users.md index 5361a770d..5d6fc1dbf 100644 --- a/docs/3.x/users.md +++ b/docs/3.x/users.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Users Users are Craft’s representation of people. @@ -58,992 +62,5 @@ We can display a list of the users in an “Authors” user group by doing the f User queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [admin](#admin) | Narrows the query results to only users that have admin accounts. -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only users that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching users as arrays of data, rather than [User](craft3:craft\elements\User) objects. -| [cache](#cache) | Enables query cache for this Query. -| [can](#can) | Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#datecreated) | Narrows the query results based on the users’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the users’ last-updated dates. -| [email](#email) | Narrows the query results based on the users’ email addresses. -| [firstName](#firstname) | Narrows the query results based on the users’ first names. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [group](#group) | Narrows the query results based on the user group the users belong to. -| [groupId](#groupid) | Narrows the query results based on the user group the users belong to, per the groups’ IDs. -| [hasPhoto](#hasphoto) | Narrows the query results to only users that have (or don’t have) a user photo. -| [id](#id) | Narrows the query results based on the users’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching users as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [lastLoginDate](#lastlogindate) | Narrows the query results based on the users’ last login dates. -| [lastName](#lastname) | Narrows the query results based on the users’ last names. -| [limit](#limit) | Determines the number of users that should be returned. -| [offset](#offset) | Determines how many users should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) -| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. -| [relatedTo](#relatedto) | Narrows the query results to only users that are related to certain other elements. -| [search](#search) | Narrows the query results to only users that match a search query. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the users’ IDs in the `elements_sites` table. -| [status](#status) | Narrows the query results based on the users’ statuses. -| [trashed](#trashed) | Narrows the query results to only users that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the users’ UIDs. -| [username](#username) | Narrows the query results based on the users’ usernames. -| [with](#with) | Causes the query to return matching users eager-loaded with related elements. -| [withGroups](#withgroups) | Causes the query to return matching users eager-loaded with their user groups. - - - - - -#### `admin` - -Narrows the query results to only users that have admin accounts. - - - -::: code -```twig -{# Fetch admins #} -{% set users = craft.users() - .admin() - .all() %} -``` - -```php -// Fetch admins -$users = \craft\elements\User::find() - ->admin() - ->all(); -``` -::: - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only users that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all users that are related to myCategoryA and myCategoryB #} -{% set users = craft.users() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all users that are related to $myCategoryA and $myCategoryB -$users = \craft\elements\User::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all users, regardless of status #} -{% set users = craft.users() - .anyStatus() - .all() %} -``` - -```php -// Fetch all users, regardless of status -$users = \craft\elements\User::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching users as arrays of data, rather than [User](craft3:craft\elements\User) objects. - - - - - -::: code -```twig -{# Fetch users as arrays #} -{% set users = craft.users() - .asArray() - .all() %} -``` - -```php -// Fetch users as arrays -$users = \craft\elements\User::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `can` - -Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. - -See [User Management](https://craftcms.com/docs/3.x/user-management.html) for a full list of available user permissions defined by Craft. - - - -::: code -```twig -{# Fetch users that can access the control panel #} -{% set users = craft.users() - .can('accessCp') - .all() %} -``` - -```php -// Fetch users that can access the control panel -$users = \craft\elements\User::find() - ->can('accessCp') - ->all(); -``` -::: - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `dateCreated` - -Narrows the query results based on the users’ creation dates. - - - -Possible values include: - -| Value | Fetches users… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch users created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set users = craft.users() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch users created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$users = \craft\elements\User::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the users’ last-updated dates. - - - -Possible values include: - -| Value | Fetches users… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch users updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set users = craft.users() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch users updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$users = \craft\elements\User::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `email` - -Narrows the query results based on the users’ email addresses. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'me@domain.tld'` | with an email of `me@domain.tld`. -| `'not me@domain.tld'` | not with an email of `me@domain.tld`. -| `'*@domain.tld'` | with an email that ends with `@domain.tld`. - - - -::: code -```twig -{# Fetch users with a .co.uk domain on their email address #} -{% set users = craft.users() - .email('*.co.uk') - .all() %} -``` - -```php -// Fetch users with a .co.uk domain on their email address -$users = \craft\elements\User::find() - ->email('*.co.uk') - ->all(); -``` -::: - - -#### `firstName` - -Narrows the query results based on the users’ first names. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'Jane'` | with a first name of `Jane`. -| `'not Jane'` | not with a first name of `Jane`. - - - -::: code -```twig -{# Fetch all the Jane's #} -{% set users = craft.users() - .firstName('Jane') - .all() %} -``` - -```php -// Fetch all the Jane's -$users = \craft\elements\User::find() - ->firstName('Jane') - ->one(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch users in a specific order #} -{% set users = craft.users() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch users in a specific order -$users = \craft\elements\User::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `group` - -Narrows the query results based on the user group the users belong to. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'foo'` | in a group with a handle of `foo`. -| `'not foo'` | not in a group with a handle of `foo`. -| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. -| `['and', 'foo', 'bar']` | in both groups with handles of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. -| a [UserGroup](craft3:craft\models\UserGroup) object | in a group represented by the object. - - - -::: code -```twig -{# Fetch users in the Foo user group #} -{% set users = craft.users() - .group('foo') - .all() %} -``` - -```php -// Fetch users in the Foo user group -$users = \craft\elements\User::find() - ->group('foo') - ->all(); -``` -::: - - -#### `groupId` - -Narrows the query results based on the user group the users belong to, per the groups’ IDs. - -Possible values include: - -| Value | Fetches users… -| - | - -| `1` | in a group with an ID of 1. -| `'not 1'` | not in a group with an ID of 1. -| `[1, 2]` | in a group with an ID of 1 or 2. -| `['and', 1, 2]` | in both groups with IDs of 1 or 2. -| `['not', 1, 2]` | not in a group with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch users in a group with an ID of 1 #} -{% set users = craft.users() - .groupId(1) - .all() %} -``` - -```php -// Fetch users in a group with an ID of 1 -$users = \craft\elements\User::find() - ->groupId(1) - ->all(); -``` -::: - - -#### `hasPhoto` - -Narrows the query results to only users that have (or don’t have) a user photo. - - - -::: code -```twig -{# Fetch users with photos #} -{% set users = craft.users() - .hasPhoto() - .all() %} -``` - -```php -// Fetch users without photos -$users = \craft\elements\User::find() - ->hasPhoto() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the users’ IDs. - - - -Possible values include: - -| Value | Fetches users… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the user by its ID #} -{% set user = craft.users() - .id(1) - .one() %} -``` - -```php -// Fetch the user by its ID -$user = \craft\elements\User::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching users as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch users in reverse #} -{% set users = craft.users() - .inReverse() - .all() %} -``` - -```php -// Fetch users in reverse -$users = \craft\elements\User::find() - ->inReverse() - ->all(); -``` -::: - - -#### `lastLoginDate` - -Narrows the query results based on the users’ last login dates. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'>= 2018-04-01'` | that last logged-in on or after 2018-04-01. -| `'< 2018-05-01'` | that last logged-in before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that last logged-in between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch users that logged in recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set users = craft.users() - .lastLoginDate(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch users that logged in recently -$aWeekAgo = (new \DateTime('7 days ago'))->format(\DateTime::ATOM); - -$users = \craft\elements\User::find() - ->lastLoginDate(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `lastName` - -Narrows the query results based on the users’ last names. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'Doe'` | with a last name of `Doe`. -| `'not Doe'` | not with a last name of `Doe`. - - - -::: code -```twig -{# Fetch all the Doe's #} -{% set users = craft.users() - .lastName('Doe') - .all() %} -``` - -```php -// Fetch all the Doe's -$users = \craft\elements\User::find() - ->lastName('Doe') - ->one(); -``` -::: - - -#### `limit` - -Determines the number of users that should be returned. - - - -::: code -```twig -{# Fetch up to 10 users #} -{% set users = craft.users() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 users -$users = \craft\elements\User::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many users should be skipped in the results. - - - -::: code -```twig -{# Fetch all users except for the first 3 #} -{% set users = craft.users() - .offset(3) - .all() %} -``` - -```php -// Fetch all users except for the first 3 -$users = \craft\elements\User::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) - - - -::: code -```twig -{# Fetch all users in order of date created #} -{% set users = craft.users() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all users in order of date created -$users = \craft\elements\User::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique users from Site A, or Site B if they don’t exist in Site A #} -{% set users = craft.users() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique users from Site A, or Site B if they don’t exist in Site A -$users = \craft\elements\User::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only users that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all users that are related to myCategory #} -{% set users = craft.users() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all users that are related to $myCategory -$users = \craft\elements\User::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only users that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all users that match the search query #} -{% set users = craft.users() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all users that match the search query -$users = \craft\elements\User::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the users’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches users… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the user by its ID in the elements_sites table #} -{% set user = craft.users() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the user by its ID in the elements_sites table -$user = \craft\elements\User::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the users’ statuses. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'active'` _(default)_ | with active accounts. -| `'suspended'` | with suspended accounts. -| `'pending'` | with accounts that are still pending activation. -| `'locked'` | with locked accounts (regardless of whether they’re active or suspended). -| `['active', 'suspended']` | with active or suspended accounts. -| `['not', 'active', 'suspended']` | without active or suspended accounts. - - - -::: code -```twig -{# Fetch active and locked users #} -{% set users = craft.users() - .status(['active', 'locked']) - .all() %} -``` - -```php -// Fetch active and locked users -$users = \craft\elements\User::find() - ->status(['active', 'locked']) - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only users that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed users #} -{% set users = craft.users() - .trashed() - .all() %} -``` - -```php -// Fetch trashed users -$users = \craft\elements\User::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the users’ UIDs. - - - - - -::: code -```twig -{# Fetch the user by its UID #} -{% set user = craft.users() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the user by its UID -$user = \craft\elements\User::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `username` - -Narrows the query results based on the users’ usernames. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'foo'` | with a username of `foo`. -| `'not foo'` | not with a username of `foo`. - - - -::: code -```twig -{# Get the requested username #} -{% set requestedUsername = craft.app.request.getSegment(2) %} - -{# Fetch that user #} -{% set user = craft.users() - .username(requestedUsername|literal) - .one() %} -``` - -```php -// Get the requested username -$requestedUsername = \Craft::$app->request->getSegment(2); - -// Fetch that user -$user = \craft\elements\User::find() - ->username(\craft\helpers\Db::escapeParam($requestedUsername)) - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching users eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch users eager-loaded with the "Related" field’s relations #} -{% set users = craft.users() - .with(['related']) - .all() %} -``` - -```php -// Fetch users eager-loaded with the "Related" field’s relations -$users = \craft\elements\User::find() - ->with(['related']) - ->all(); -``` -::: - - -#### `withGroups` - -Causes the query to return matching users eager-loaded with their user groups. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'>= 2018-04-01'` | that last logged-in on or after 2018-04-01. -| `'< 2018-05-01'` | that last logged-in before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that last logged-in between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# fetch users with their user groups #} -{% set users = craft.users() - .withGroups() - .all() %} -``` - -```php -// fetch users with their user groups -$users = \craft\elements\User::find() - ->withGroups() - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/3.x/users.md)!!! diff --git a/docs/4.x/addresses.md b/docs/4.x/addresses.md index 6d9f92052..016319529 100644 --- a/docs/4.x/addresses.md +++ b/docs/4.x/addresses.md @@ -4,6 +4,7 @@ related: label: Using addresses in Craft Commerce - uri: /4.x/dev/controller-actions.md label: Controller actions reference +containsGeneratedContent: yes --- # Addresses @@ -97,736 +98,8 @@ Protect your users’ personal information by carefully auditing queries and dis Address queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [administrativeArea](#administrativearea) | Narrows the query results based on the administrative area the assets belong to. -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only addresses that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching addresses as arrays of data, rather than [Address](craft4:craft\elements\Address) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [collect](#collect) | -| [countryCode](#countrycode) | Narrows the query results based on the country the assets belong to. -| [dateCreated](#datecreated) | Narrows the query results based on the addresses’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the addresses’ last-updated dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [id](#id) | Narrows the query results based on the addresses’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching addresses as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [limit](#limit) | Determines the number of addresses that should be returned. -| [offset](#offset) | Determines how many addresses should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the addresses should be returned in. (If empty, defaults to `dateCreated DESC`.) -| [owner](#owner) | Sets the [ownerId](#ownerid) parameter based on a given owner element. -| [ownerId](#ownerid) | Narrows the query results based on the addresses’ owner elements, per their IDs. -| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [relatedTo](#relatedto) | Narrows the query results to only addresses that are related to certain other elements. -| [search](#search) | Narrows the query results to only addresses that match a search query. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the addresses’ IDs in the `elements_sites` table. -| [trashed](#trashed) | Narrows the query results to only addresses that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the addresses’ UIDs. -| [with](#with) | Causes the query to return matching addresses eager-loaded with related elements. - - - - - -#### `administrativeArea` - -Narrows the query results based on the administrative area the assets belong to. - -Possible values include: - -| Value | Fetches addresses… -| - | - -| `'AU'` | with a administrativeArea of `AU`. -| `'not US'` | not in a administrativeArea of `US`. -| `['AU', 'US']` | in a administrativeArea of `AU` or `US`. -| `['not', 'AU', 'US']` | not in a administrativeArea of `AU` or `US`. - - - -::: code -```twig -{# Fetch addresses in the AU #} -{% set addresses = craft.addresses() - .administrativeArea('AU') - .all() %} -``` - -```php -// Fetch addresses in the AU -$addresses = \craft\elements\Address::find() - ->administrativeArea('AU') - ->all(); -``` -::: - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only addresses that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all addresses that are related to myCategoryA and myCategoryB #} -{% set addresses = craft.addresses() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all addresses that are related to $myCategoryA and $myCategoryB -$addresses = \craft\elements\Address::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching addresses as arrays of data, rather than [Address](craft4:craft\elements\Address) objects. - - - - - -::: code -```twig -{# Fetch addresses as arrays #} -{% set addresses = craft.addresses() - .asArray() - .all() %} -``` - -```php -// Fetch addresses as arrays -$addresses = \craft\elements\Address::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `collect` - - - - - - - - -#### `countryCode` - -Narrows the query results based on the country the assets belong to. - -Possible values include: - -| Value | Fetches addresses… -| - | - -| `'AU'` | with a countryCode of `AU`. -| `'not US'` | not in a countryCode of `US`. -| `['AU', 'US']` | in a countryCode of `AU` or `US`. -| `['not', 'AU', 'US']` | not in a countryCode of `AU` or `US`. - - - -::: code -```twig -{# Fetch addresses in the AU #} -{% set addresses = craft.addresses() - .countryCode('AU') - .all() %} -``` - -```php -// Fetch addresses in the AU -$addresses = \craft\elements\Address::find() - ->countryCode('AU') - ->all(); -``` -::: - - -#### `dateCreated` - -Narrows the query results based on the addresses’ creation dates. - - - -Possible values include: - -| Value | Fetches addresses… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch addresses created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set addresses = craft.addresses() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch addresses created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$addresses = \craft\elements\Address::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the addresses’ last-updated dates. - - - -Possible values include: - -| Value | Fetches addresses… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch addresses updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set addresses = craft.addresses() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch addresses updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$addresses = \craft\elements\Address::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch addresses in a specific order #} -{% set addresses = craft.addresses() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch addresses in a specific order -$addresses = \craft\elements\Address::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the addresses’ IDs. - - - -Possible values include: - -| Value | Fetches addresses… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the address by its ID #} -{% set address = craft.addresses() - .id(1) - .one() %} -``` - -```php -// Fetch the address by its ID -$address = \craft\elements\Address::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching addresses as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch addresses in reverse #} -{% set addresses = craft.addresses() - .inReverse() - .all() %} -``` - -```php -// Fetch addresses in reverse -$addresses = \craft\elements\Address::find() - ->inReverse() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of addresses that should be returned. - - - -::: code -```twig -{# Fetch up to 10 addresses #} -{% set addresses = craft.addresses() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 addresses -$addresses = \craft\elements\Address::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many addresses should be skipped in the results. - - - -::: code -```twig -{# Fetch all addresses except for the first 3 #} -{% set addresses = craft.addresses() - .offset(3) - .all() %} -``` - -```php -// Fetch all addresses except for the first 3 -$addresses = \craft\elements\Address::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the addresses should be returned in. (If empty, defaults to `dateCreated DESC`.) - - - -::: code -```twig -{# Fetch all addresses in order of date created #} -{% set addresses = craft.addresses() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all addresses in order of date created -$addresses = \craft\elements\Address::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `owner` - -Sets the [ownerId](#ownerid) parameter based on a given owner element. - - - -::: code -```twig -{# Fetch addresses for the current user #} -{% set addresses = craft.addresses() - .owner(currentUser) - .all() %} -``` - -```php -// Fetch addresses created for the current user -$addresses = \craft\elements\Address::find() - ->owner(Craft::$app->user->identity) - ->all(); -``` -::: - - -#### `ownerId` - -Narrows the query results based on the addresses’ owner elements, per their IDs. - -Possible values include: - -| Value | Fetches addresses… -| - | - -| `1` | created for an element with an ID of 1. -| `[1, 2]` | created for an element with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch addresses created for an element with an ID of 1 #} -{% set addresses = craft.addresses() - .ownerId(1) - .all() %} -``` - -```php -// Fetch addresses created for an element with an ID of 1 -$addresses = \craft\elements\Address::find() - ->ownerId(1) - ->all(); -``` -::: - - -#### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique addresses from Site A, or Site B if they don’t exist in Site A #} -{% set addresses = craft.addresses() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique addresses from Site A, or Site B if they don’t exist in Site A -$addresses = \craft\elements\Address::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `relatedTo` - -Narrows the query results to only addresses that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all addresses that are related to myCategory #} -{% set addresses = craft.addresses() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all addresses that are related to $myCategory -$addresses = \craft\elements\Address::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only addresses that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all addresses that match the search query #} -{% set addresses = craft.addresses() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all addresses that match the search query -$addresses = \craft\elements\Address::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the addresses’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches addresses… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the address by its ID in the elements_sites table #} -{% set address = craft.addresses() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the address by its ID in the elements_sites table -$address = \craft\elements\Address::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `trashed` - -Narrows the query results to only addresses that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed addresses #} -{% set addresses = craft.addresses() - .trashed() - .all() %} -``` - -```php -// Fetch trashed addresses -$addresses = \craft\elements\Address::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the addresses’ UIDs. - - - - - -::: code -```twig -{# Fetch the address by its UID #} -{% set address = craft.addresses() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the address by its UID -$address = \craft\elements\Address::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching addresses eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch addresses eager-loaded with the "Related" field’s relations #} -{% set addresses = craft.addresses() - .with(['related']) - .all() %} -``` - -```php -// Fetch addresses eager-loaded with the "Related" field’s relations -$addresses = \craft\elements\Address::find() - ->with(['related']) - ->all(); -``` -::: - - - - - + +!!!include(docs/.artifacts/cms/4.x/addresses.md)!!! ## Address Repository diff --git a/docs/4.x/assets.md b/docs/4.x/assets.md index ceab3fb9b..23422fa5f 100644 --- a/docs/4.x/assets.md +++ b/docs/4.x/assets.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Assets Craft lets you manage media and document files (“assets”) just like entries and other content types. Assets can live anywhere—a directory on the web server, or a remote storage service like Amazon S3. @@ -230,1255 +234,5 @@ You can cache-bust asset URLs automatically by enabling the [revAssetUrls](confi Asset queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only assets that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching assets as arrays of data, rather than [Asset](craft4:craft\elements\Asset) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [collect](#collect) | -| [dateCreated](#datecreated) | Narrows the query results based on the assets’ creation dates. -| [dateModified](#datemodified) | Narrows the query results based on the assets’ files’ last-modified dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the assets’ last-updated dates. -| [filename](#filename) | Narrows the query results based on the assets’ filenames. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [folderId](#folderid) | Narrows the query results based on the folders the assets belong to, per the folders’ IDs. -| [folderPath](#folderpath) | Narrows the query results based on the folders the assets belong to, per the folders’ paths. -| [hasAlt](#hasalt) | Narrows the query results based on whether the assets have alternative text. -| [height](#height) | Narrows the query results based on the assets’ image heights. -| [id](#id) | Narrows the query results based on the assets’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [includeSubfolders](#includesubfolders) | Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). -| [kind](#kind) | Narrows the query results based on the assets’ file kinds. -| [limit](#limit) | Determines the number of assets that should be returned. -| [offset](#offset) | Determines how many assets should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [relatedTo](#relatedto) | Narrows the query results to only assets that are related to certain other elements. -| [savable](#savable) | Sets the [savable](https://docs.craftcms.com/api/v3/craft-elements-db-assetquery.html#savable) property. -| [search](#search) | Narrows the query results to only assets that match a search query. -| [site](#site) | Determines which site(s) the assets should be queried in. -| [siteId](#siteid) | Determines which site(s) the assets should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the assets’ IDs in the `elements_sites` table. -| [size](#size) | Narrows the query results based on the assets’ file sizes (in bytes). -| [title](#title) | Narrows the query results based on the assets’ titles. -| [trashed](#trashed) | Narrows the query results to only assets that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the assets’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uploader](#uploader) | Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. -| [volume](#volume) | Narrows the query results based on the volume the assets belong to. -| [volumeId](#volumeid) | Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. -| [width](#width) | Narrows the query results based on the assets’ image widths. -| [with](#with) | Causes the query to return matching assets eager-loaded with related elements. -| [withTransforms](#withtransforms) | Causes the query to return matching assets eager-loaded with image transform indexes. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only assets that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all assets that are related to myCategoryA and myCategoryB #} -{% set assets = craft.assets() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all assets that are related to $myCategoryA and $myCategoryB -$assets = \craft\elements\Asset::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching assets as arrays of data, rather than [Asset](craft4:craft\elements\Asset) objects. - - - - - -::: code -```twig -{# Fetch assets as arrays #} -{% set assets = craft.assets() - .asArray() - .all() %} -``` - -```php -// Fetch assets as arrays -$assets = \craft\elements\Asset::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `collect` - - - - - - - - -#### `dateCreated` - -Narrows the query results based on the assets’ creation dates. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch assets created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set assets = craft.assets() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch assets created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$assets = \craft\elements\Asset::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateModified` - -Narrows the query results based on the assets’ files’ last-modified dates. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'>= 2018-04-01'` | that were modified on or after 2018-04-01. -| `'< 2018-05-01'` | that were modified before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were modified between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were modified at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch assets modified in the last month #} -{% set start = date('30 days ago')|atom %} - -{% set assets = craft.assets() - .dateModified(">= #{start}") - .all() %} -``` - -```php -// Fetch assets modified in the last month -$start = (new \DateTime('30 days ago'))->format(\DateTime::ATOM); - -$assets = \craft\elements\Asset::find() - ->dateModified(">= {$start}") - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the assets’ last-updated dates. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch assets updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set assets = craft.assets() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch assets updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$assets = \craft\elements\Asset::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `filename` - -Narrows the query results based on the assets’ filenames. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'foo.jpg'` | with a filename of `foo.jpg`. -| `'foo*'` | with a filename that begins with `foo`. -| `'*.jpg'` | with a filename that ends with `.jpg`. -| `'*foo*'` | with a filename that contains `foo`. -| `'not *foo*'` | with a filename that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a filename that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a filename that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Fetch all the hi-res images #} -{% set assets = craft.assets() - .filename('*@2x*') - .all() %} -``` - -```php -// Fetch all the hi-res images -$assets = \craft\elements\Asset::find() - ->filename('*@2x*') - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch assets in a specific order #} -{% set assets = craft.assets() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch assets in a specific order -$assets = \craft\elements\Asset::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `folderId` - -Narrows the query results based on the folders the assets belong to, per the folders’ IDs. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | in a folder with an ID of 1. -| `'not 1'` | not in a folder with an ID of 1. -| `[1, 2]` | in a folder with an ID of 1 or 2. -| `['not', 1, 2]` | not in a folder with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch assets in the folder with an ID of 1 #} -{% set assets = craft.assets() - .folderId(1) - .all() %} -``` - -```php -// Fetch assets in the folder with an ID of 1 -$assets = \craft\elements\Asset::find() - ->folderId(1) - ->all(); -``` -::: - - - -::: tip -This can be combined with [includeSubfolders](#includesubfolders) if you want to include assets in all the subfolders of a certain folder. -::: -#### `folderPath` - -Narrows the query results based on the folders the assets belong to, per the folders’ paths. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `foo/` | in a `foo/` folder (excluding nested folders). -| `foo/*` | in a `foo/` folder (including nested folders). -| `'not foo/*'` | not in a `foo/` folder (including nested folders). -| `['foo/*', 'bar/*']` | in a `foo/` or `bar/` folder (including nested folders). -| `['not', 'foo/*', 'bar/*']` | not in a `foo/` or `bar/` folder (including nested folders). - - - -::: code -```twig -{# Fetch assets in the foo/ folder or its nested folders #} -{% set assets = craft.assets() - .folderPath('foo/*') - .all() %} -``` - -```php -// Fetch assets in the foo/ folder or its nested folders -$assets = \craft\elements\Asset::find() - ->folderPath('foo/*') - ->all(); -``` -::: - - -#### `hasAlt` - -Narrows the query results based on whether the assets have alternative text. - - - - - - -#### `height` - -Narrows the query results based on the assets’ image heights. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `100` | with a height of 100. -| `'>= 100'` | with a height of at least 100. -| `['>= 100', '<= 1000']` | with a height between 100 and 1,000. - - - -::: code -```twig -{# Fetch XL images #} -{% set assets = craft.assets() - .kind('image') - .height('>= 1000') - .all() %} -``` - -```php -// Fetch XL images -$assets = \craft\elements\Asset::find() - ->kind('image') - ->height('>= 1000') - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the assets’ IDs. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the asset by its ID #} -{% set asset = craft.assets() - .id(1) - .one() %} -``` - -```php -// Fetch the asset by its ID -$asset = \craft\elements\Asset::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching assets as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch assets in reverse #} -{% set assets = craft.assets() - .inReverse() - .all() %} -``` - -```php -// Fetch assets in reverse -$assets = \craft\elements\Asset::find() - ->inReverse() - ->all(); -``` -::: - - -#### `includeSubfolders` - -Broadens the query results to include assets from any of the subfolders of the folder specified by [folderId](#folderid). - - - -::: code -```twig -{# Fetch assets in the folder with an ID of 1 (including its subfolders) #} -{% set assets = craft.assets() - .folderId(1) - .includeSubfolders() - .all() %} -``` - -```php -// Fetch assets in the folder with an ID of 1 (including its subfolders) -$assets = \craft\elements\Asset::find() - ->folderId(1) - ->includeSubfolders() - ->all(); -``` -::: - - - -::: warning -This will only work if [folderId](#folderid) was set to a single folder ID. -::: -#### `kind` - -Narrows the query results based on the assets’ file kinds. - -Supported file kinds: -- `access` -- `audio` -- `compressed` -- `excel` -- `flash` -- `html` -- `illustrator` -- `image` -- `javascript` -- `json` -- `pdf` -- `photoshop` -- `php` -- `powerpoint` -- `text` -- `video` -- `word` -- `xml` -- `unknown` - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'image'` | with a file kind of `image`. -| `'not image'` | not with a file kind of `image`.. -| `['image', 'pdf']` | with a file kind of `image` or `pdf`. -| `['not', 'image', 'pdf']` | not with a file kind of `image` or `pdf`. - - - -::: code -```twig -{# Fetch all the images #} -{% set assets = craft.assets() - .kind('image') - .all() %} -``` - -```php -// Fetch all the images -$assets = \craft\elements\Asset::find() - ->kind('image') - ->all(); -``` -::: - - -#### `limit` - -Determines the number of assets that should be returned. - - - -::: code -```twig -{# Fetch up to 10 assets #} -{% set assets = craft.assets() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 assets -$assets = \craft\elements\Asset::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many assets should be skipped in the results. - - - -::: code -```twig -{# Fetch all assets except for the first 3 #} -{% set assets = craft.assets() - .offset(3) - .all() %} -``` - -```php -// Fetch all assets except for the first 3 -$assets = \craft\elements\Asset::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the assets should be returned in. (If empty, defaults to `dateCreated DESC`.) - - - -::: code -```twig -{# Fetch all assets in order of date created #} -{% set assets = craft.assets() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all assets in order of date created -$assets = \craft\elements\Asset::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique assets from Site A, or Site B if they don’t exist in Site A #} -{% set assets = craft.assets() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique assets from Site A, or Site B if they don’t exist in Site A -$assets = \craft\elements\Asset::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `relatedTo` - -Narrows the query results to only assets that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all assets that are related to myCategory #} -{% set assets = craft.assets() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all assets that are related to $myCategory -$assets = \craft\elements\Asset::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `savable` - -Sets the [savable](https://docs.craftcms.com/api/v3/craft-elements-db-assetquery.html#savable) property. - - - - - - -#### `search` - -Narrows the query results to only assets that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all assets that match the search query #} -{% set assets = craft.assets() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all assets that match the search query -$assets = \craft\elements\Asset::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the assets should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch assets from the Foo site #} -{% set assets = craft.assets() - .site('foo') - .all() %} -``` - -```php -// Fetch assets from the Foo site -$assets = \craft\elements\Asset::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the assets should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch assets from the site with an ID of 1 #} -{% set assets = craft.assets() - .siteId(1) - .all() %} -``` - -```php -// Fetch assets from the site with an ID of 1 -$assets = \craft\elements\Asset::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the assets’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the asset by its ID in the elements_sites table #} -{% set asset = craft.assets() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the asset by its ID in the elements_sites table -$asset = \craft\elements\Asset::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `size` - -Narrows the query results based on the assets’ file sizes (in bytes). - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1000` | with a size of 1,000 bytes (1KB). -| `'< 1000000'` | with a size of less than 1,000,000 bytes (1MB). -| `['>= 1000', '< 1000000']` | with a size between 1KB and 1MB. - - - -::: code -```twig -{# Fetch assets that are smaller than 1KB #} -{% set assets = craft.assets() - .size('< 1000') - .all() %} -``` - -```php -// Fetch assets that are smaller than 1KB -$assets = \craft\elements\Asset::find() - ->size('< 1000') - ->all(); -``` -::: - - -#### `title` - -Narrows the query results based on the assets’ titles. - - - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch assets with a title that contains "Foo" #} -{% set assets = craft.assets() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch assets with a title that contains "Foo" -$assets = \craft\elements\Asset::find() - ->title('*Foo*') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only assets that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed assets #} -{% set assets = craft.assets() - .trashed() - .all() %} -``` - -```php -// Fetch trashed assets -$assets = \craft\elements\Asset::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the assets’ UIDs. - - - - - -::: code -```twig -{# Fetch the asset by its UID #} -{% set asset = craft.assets() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the asset by its UID -$asset = \craft\elements\Asset::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique assets across all sites #} -{% set assets = craft.assets() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique assets across all sites -$assets = \craft\elements\Asset::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `uploader` - -Narrows the query results based on the user the assets were uploaded by, per the user’s IDs. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | uploaded by the user with an ID of 1. -| a [craft\elements\User](craft4:craft\elements\User) object | uploaded by the user represented by the object. - - - -::: code -```twig -{# Fetch assets uploaded by the user with an ID of 1 #} -{% set assets = craft.assets() - .uploader(1) - .all() %} -``` - -```php -// Fetch assets uploaded by the user with an ID of 1 -$assets = \craft\elements\Asset::find() - ->uploader(1) - ->all(); -``` -::: - - -#### `volume` - -Narrows the query results based on the volume the assets belong to. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `'foo'` | in a volume with a handle of `foo`. -| `'not foo'` | not in a volume with a handle of `foo`. -| `['foo', 'bar']` | in a volume with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a volume with a handle of `foo` or `bar`. -| a [craft\models\Volume](craft4:craft\models\Volume) object | in a volume represented by the object. - - - -::: code -```twig -{# Fetch assets in the Foo volume #} -{% set assets = craft.assets() - .volume('foo') - .all() %} -``` - -```php -// Fetch assets in the Foo group -$assets = \craft\elements\Asset::find() - ->volume('foo') - ->all(); -``` -::: - - -#### `volumeId` - -Narrows the query results based on the volumes the assets belong to, per the volumes’ IDs. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `1` | in a volume with an ID of 1. -| `'not 1'` | not in a volume with an ID of 1. -| `[1, 2]` | in a volume with an ID of 1 or 2. -| `['not', 1, 2]` | not in a volume with an ID of 1 or 2. -| `':empty:'` | that haven’t been stored in a volume yet - - - -::: code -```twig -{# Fetch assets in the volume with an ID of 1 #} -{% set assets = craft.assets() - .volumeId(1) - .all() %} -``` - -```php -// Fetch assets in the volume with an ID of 1 -$assets = \craft\elements\Asset::find() - ->volumeId(1) - ->all(); -``` -::: - - -#### `width` - -Narrows the query results based on the assets’ image widths. - -Possible values include: - -| Value | Fetches assets… -| - | - -| `100` | with a width of 100. -| `'>= 100'` | with a width of at least 100. -| `['>= 100', '<= 1000']` | with a width between 100 and 1,000. - - - -::: code -```twig -{# Fetch XL images #} -{% set assets = craft.assets() - .kind('image') - .width('>= 1000') - .all() %} -``` - -```php -// Fetch XL images -$assets = \craft\elements\Asset::find() - ->kind('image') - ->width('>= 1000') - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching assets eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch assets eager-loaded with the "Related" field’s relations #} -{% set assets = craft.assets() - .with(['related']) - .all() %} -``` - -```php -// Fetch assets eager-loaded with the "Related" field’s relations -$assets = \craft\elements\Asset::find() - ->with(['related']) - ->all(); -``` -::: - - -#### `withTransforms` - -Causes the query to return matching assets eager-loaded with image transform indexes. - -This can improve performance when displaying several image transforms at once, if the transforms -have already been generated. - -Transforms can be specified as their handle or an object that contains `width` and/or `height` properties. - -You can include `srcset`-style sizes (e.g. `100w` or `2x`) following a normal transform definition, for example: - -::: code - -```twig -[{width: 1000, height: 600}, '1.5x', '2x', '3x'] -``` - -```php -[['width' => 1000, 'height' => 600], '1.5x', '2x', '3x'] -``` - -::: - -When a `srcset`-style size is encountered, the preceding normal transform definition will be used as a -reference when determining the resulting transform dimensions. - - - -::: code -```twig -{# Fetch assets with the 'thumbnail' and 'hiResThumbnail' transform data preloaded #} -{% set assets = craft.assets() - .kind('image') - .withTransforms(['thumbnail', 'hiResThumbnail']) - .all() %} -``` - -```php -// Fetch assets with the 'thumbnail' and 'hiResThumbnail' transform data preloaded -$assets = \craft\elements\Asset::find() - ->kind('image') - ->withTransforms(['thumbnail', 'hiResThumbnail']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/4.x/assets.md)!!! diff --git a/docs/4.x/categories.md b/docs/4.x/categories.md index 31e3abc5a..17526baa7 100644 --- a/docs/4.x/categories.md +++ b/docs/4.x/categories.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Categories Craft supports user-managed, hierarchical taxonomies for content via **categories**. @@ -155,1340 +159,5 @@ For example, if we were building a blog with dedicated “Topic” (category) pa Category queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [ancestorDist](#ancestordist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). -| [ancestorOf](#ancestorof) | Narrows the query results to only categories that are ancestors of another category in its structure. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only categories that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching categories as arrays of data, rather than [Category](craft4:craft\elements\Category) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [collect](#collect) | -| [dateCreated](#datecreated) | Narrows the query results based on the categories’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the categories’ last-updated dates. -| [descendantDist](#descendantdist) | Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). -| [descendantOf](#descendantof) | Narrows the query results to only categories that are descendants of another category in its structure. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [group](#group) | Narrows the query results based on the category groups the categories belong to. -| [groupId](#groupid) | Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. -| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the categories have any descendants in their structure. -| [id](#id) | Narrows the query results based on the categories’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [leaves](#leaves) | Narrows the query results based on whether the categories are “leaves” (categories with no descendants). -| [level](#level) | Narrows the query results based on the categories’ level within the structure. -| [limit](#limit) | Determines the number of categories that should be returned. -| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the category that comes immediately after another category in its structure. -| [offset](#offset) | Determines how many categories should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`, or the order defined by the category group if the [group](#group) or [groupId](#groupid) params are set to a single group.) -| [positionedAfter](#positionedafter) | Narrows the query results to only categories that are positioned after another category in its structure. -| [positionedBefore](#positionedbefore) | Narrows the query results to only categories that are positioned before another category in its structure. -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the category that comes immediately before another category in its structure. -| [relatedTo](#relatedto) | Narrows the query results to only categories that are related to certain other elements. -| [search](#search) | Narrows the query results to only categories that match a search query. -| [siblingOf](#siblingof) | Narrows the query results to only categories that are siblings of another category in its structure. -| [site](#site) | Determines which site(s) the categories should be queried in. -| [siteId](#siteid) | Determines which site(s) the categories should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the categories’ IDs in the `elements_sites` table. -| [slug](#slug) | Narrows the query results based on the categories’ slugs. -| [status](#status) | Narrows the query results based on the categories’ statuses. -| [title](#title) | Narrows the query results based on the categories’ titles. -| [trashed](#trashed) | Narrows the query results to only categories that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the categories’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uri](#uri) | Narrows the query results based on the categories’ URIs. -| [with](#with) | Causes the query to return matching categories eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `ancestorDist` - -Narrows the query results to only categories that are up to a certain distance away from the category specified by [ancestorOf](#ancestorof). - - - - - -::: code -```twig -{# Fetch categories above this one #} -{% set categories = craft.categories() - .ancestorOf(myCategory) - .ancestorDist(3) - .all() %} -``` - -```php -// Fetch categories above this one -$categories = \craft\elements\Category::find() - ->ancestorOf($myCategory) - ->ancestorDist(3) - ->all(); -``` -::: - - -#### `ancestorOf` - -Narrows the query results to only categories that are ancestors of another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | above the category with an ID of 1. -| a [Category](craft4:craft\elements\Category) object | above the category represented by the object. - - - -::: code -```twig -{# Fetch categories above this one #} -{% set categories = craft.categories() - .ancestorOf(myCategory) - .all() %} -``` - -```php -// Fetch categories above this one -$categories = \craft\elements\Category::find() - ->ancestorOf($myCategory) - ->all(); -``` -::: - - - -::: tip -This can be combined with [ancestorDist](#ancestordist) if you want to limit how far away the ancestor categories can be. -::: - - -#### `andRelatedTo` - -Narrows the query results to only categories that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all categories that are related to myCategoryA and myCategoryB #} -{% set categories = craft.categories() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all categories that are related to $myCategoryA and $myCategoryB -$categories = \craft\elements\Category::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching categories as arrays of data, rather than [Category](craft4:craft\elements\Category) objects. - - - - - -::: code -```twig -{# Fetch categories as arrays #} -{% set categories = craft.categories() - .asArray() - .all() %} -``` - -```php -// Fetch categories as arrays -$categories = \craft\elements\Category::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `collect` - - - - - - - - -#### `dateCreated` - -Narrows the query results based on the categories’ creation dates. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch categories created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set categories = craft.categories() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch categories created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$categories = \craft\elements\Category::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the categories’ last-updated dates. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch categories updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set categories = craft.categories() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch categories updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$categories = \craft\elements\Category::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `descendantDist` - -Narrows the query results to only categories that are up to a certain distance away from the category specified by [descendantOf](#descendantof). - - - - - -::: code -```twig -{# Fetch categories below this one #} -{% set categories = craft.categories() - .descendantOf(myCategory) - .descendantDist(3) - .all() %} -``` - -```php -// Fetch categories below this one -$categories = \craft\elements\Category::find() - ->descendantOf($myCategory) - ->descendantDist(3) - ->all(); -``` -::: - - -#### `descendantOf` - -Narrows the query results to only categories that are descendants of another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | below the category with an ID of 1. -| a [Category](craft4:craft\elements\Category) object | below the category represented by the object. - - - -::: code -```twig -{# Fetch categories below this one #} -{% set categories = craft.categories() - .descendantOf(myCategory) - .all() %} -``` - -```php -// Fetch categories below this one -$categories = \craft\elements\Category::find() - ->descendantOf($myCategory) - ->all(); -``` -::: - - - -::: tip -This can be combined with [descendantDist](#descendantdist) if you want to limit how far away the descendant categories can be. -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch categories in a specific order #} -{% set categories = craft.categories() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch categories in a specific order -$categories = \craft\elements\Category::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `group` - -Narrows the query results based on the category groups the categories belong to. - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'foo'` | in a group with a handle of `foo`. -| `'not foo'` | not in a group with a handle of `foo`. -| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. -| a [CategoryGroup](craft4:craft\models\CategoryGroup) object | in a group represented by the object. - - - -::: code -```twig -{# Fetch categories in the Foo group #} -{% set categories = craft.categories() - .group('foo') - .all() %} -``` - -```php -// Fetch categories in the Foo group -$categories = \craft\elements\Category::find() - ->group('foo') - ->all(); -``` -::: - - -#### `groupId` - -Narrows the query results based on the category groups the categories belong to, per the groups’ IDs. - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | in a group with an ID of 1. -| `'not 1'` | not in a group with an ID of 1. -| `[1, 2]` | in a group with an ID of 1 or 2. -| `['not', 1, 2]` | not in a group with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch categories in the group with an ID of 1 #} -{% set categories = craft.categories() - .groupId(1) - .all() %} -``` - -```php -// Fetch categories in the group with an ID of 1 -$categories = \craft\elements\Category::find() - ->groupId(1) - ->all(); -``` -::: - - -#### `hasDescendants` - -Narrows the query results based on whether the categories have any descendants in their structure. - - - -(This has the opposite effect of calling [leaves](#leaves).) - - - -::: code -```twig -{# Fetch categories that have descendants #} -{% set categories = craft.categories() - .hasDescendants() - .all() %} -``` - -```php -// Fetch categories that have descendants -$categories = \craft\elements\Category::find() - ->hasDescendants() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the categories’ IDs. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the category by its ID #} -{% set category = craft.categories() - .id(1) - .one() %} -``` - -```php -// Fetch the category by its ID -$category = \craft\elements\Category::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching categories as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch categories in reverse #} -{% set categories = craft.categories() - .inReverse() - .all() %} -``` - -```php -// Fetch categories in reverse -$categories = \craft\elements\Category::find() - ->inReverse() - ->all(); -``` -::: - - -#### `leaves` - -Narrows the query results based on whether the categories are “leaves” (categories with no descendants). - - - -(This has the opposite effect of calling [hasDescendants](#hasdescendants).) - - - -::: code -```twig -{# Fetch categories that have no descendants #} -{% set categories = craft.categories() - .leaves() - .all() %} -``` - -```php -// Fetch categories that have no descendants -$categories = \craft\elements\Category::find() - ->leaves() - ->all(); -``` -::: - - -#### `level` - -Narrows the query results based on the categories’ level within the structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | with a level of 1. -| `'not 1'` | not with a level of 1. -| `'>= 3'` | with a level greater than or equal to 3. -| `[1, 2]` | with a level of 1 or 2 -| `['not', 1, 2]` | not with level of 1 or 2. - - - -::: code -```twig -{# Fetch categories positioned at level 3 or above #} -{% set categories = craft.categories() - .level('>= 3') - .all() %} -``` - -```php -// Fetch categories positioned at level 3 or above -$categories = \craft\elements\Category::find() - ->level('>= 3') - ->all(); -``` -::: - - -#### `limit` - -Determines the number of categories that should be returned. - - - -::: code -```twig -{# Fetch up to 10 categories #} -{% set categories = craft.categories() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 categories -$categories = \craft\elements\Category::find() - ->limit(10) - ->all(); -``` -::: - - -#### `nextSiblingOf` - -Narrows the query results to only the category that comes immediately after another category in its structure. - - - -Possible values include: - -| Value | Fetches the category… -| - | - -| `1` | after the category with an ID of 1. -| a [Category](craft4:craft\elements\Category) object | after the category represented by the object. - - - -::: code -```twig -{# Fetch the next category #} -{% set category = craft.categories() - .nextSiblingOf(myCategory) - .one() %} -``` - -```php -// Fetch the next category -$category = \craft\elements\Category::find() - ->nextSiblingOf($myCategory) - ->one(); -``` -::: - - -#### `offset` - -Determines how many categories should be skipped in the results. - - - -::: code -```twig -{# Fetch all categories except for the first 3 #} -{% set categories = craft.categories() - .offset(3) - .all() %} -``` - -```php -// Fetch all categories except for the first 3 -$categories = \craft\elements\Category::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the categories should be returned in. (If empty, defaults to `dateCreated DESC`, or the order defined by the category group if the [group](#group) or [groupId](#groupid) params are set to a single group.) - - - -::: code -```twig -{# Fetch all categories in order of date created #} -{% set categories = craft.categories() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all categories in order of date created -$categories = \craft\elements\Category::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `positionedAfter` - -Narrows the query results to only categories that are positioned after another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | after the category with an ID of 1. -| a [Category](craft4:craft\elements\Category) object | after the category represented by the object. - - - -::: code -```twig -{# Fetch categories after this one #} -{% set categories = craft.categories() - .positionedAfter(myCategory) - .all() %} -``` - -```php -// Fetch categories after this one -$categories = \craft\elements\Category::find() - ->positionedAfter($myCategory) - ->all(); -``` -::: - - -#### `positionedBefore` - -Narrows the query results to only categories that are positioned before another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | before the category with an ID of 1. -| a [Category](craft4:craft\elements\Category) object | before the category represented by the object. - - - -::: code -```twig -{# Fetch categories before this one #} -{% set categories = craft.categories() - .positionedBefore(myCategory) - .all() %} -``` - -```php -// Fetch categories before this one -$categories = \craft\elements\Category::find() - ->positionedBefore($myCategory) - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique categories from Site A, or Site B if they don’t exist in Site A #} -{% set categories = craft.categories() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique categories from Site A, or Site B if they don’t exist in Site A -$categories = \craft\elements\Category::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `prevSiblingOf` - -Narrows the query results to only the category that comes immediately before another category in its structure. - - - -Possible values include: - -| Value | Fetches the category… -| - | - -| `1` | before the category with an ID of 1. -| a [Category](craft4:craft\elements\Category) object | before the category represented by the object. - - - -::: code -```twig -{# Fetch the previous category #} -{% set category = craft.categories() - .prevSiblingOf(myCategory) - .one() %} -``` - -```php -// Fetch the previous category -$category = \craft\elements\Category::find() - ->prevSiblingOf($myCategory) - ->one(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only categories that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all categories that are related to myCategory #} -{% set categories = craft.categories() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all categories that are related to $myCategory -$categories = \craft\elements\Category::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only categories that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all categories that match the search query #} -{% set categories = craft.categories() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all categories that match the search query -$categories = \craft\elements\Category::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `siblingOf` - -Narrows the query results to only categories that are siblings of another category in its structure. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | beside the category with an ID of 1. -| a [Category](craft4:craft\elements\Category) object | beside the category represented by the object. - - - -::: code -```twig -{# Fetch categories beside this one #} -{% set categories = craft.categories() - .siblingOf(myCategory) - .all() %} -``` - -```php -// Fetch categories beside this one -$categories = \craft\elements\Category::find() - ->siblingOf($myCategory) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the categories should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch categories from the Foo site #} -{% set categories = craft.categories() - .site('foo') - .all() %} -``` - -```php -// Fetch categories from the Foo site -$categories = \craft\elements\Category::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the categories should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch categories from the site with an ID of 1 #} -{% set categories = craft.categories() - .siteId(1) - .all() %} -``` - -```php -// Fetch categories from the site with an ID of 1 -$categories = \craft\elements\Category::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the categories’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the category by its ID in the elements_sites table #} -{% set category = craft.categories() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the category by its ID in the elements_sites table -$category = \craft\elements\Category::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `slug` - -Narrows the query results based on the categories’ slugs. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'foo'` | with a slug of `foo`. -| `'foo*'` | with a slug that begins with `foo`. -| `'*foo'` | with a slug that ends with `foo`. -| `'*foo*'` | with a slug that contains `foo`. -| `'not *foo*'` | with a slug that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested category slug from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the category with that slug #} -{% set category = craft.categories() - .slug(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested category slug from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the category with that slug -$category = \craft\elements\Category::find() - ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the categories’ statuses. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'enabled'` _(default)_ | that are enabled. -| `'disabled'` | that are disabled. -| `['not', 'disabled']` | that are not disabled. - - - -::: code -```twig -{# Fetch disabled categories #} -{% set categories = craft.categories() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled categories -$categories = \craft\elements\Category::find() - ->status('disabled') - ->all(); -``` -::: - - -#### `title` - -Narrows the query results based on the categories’ titles. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch categories with a title that contains "Foo" #} -{% set categories = craft.categories() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch categories with a title that contains "Foo" -$categories = \craft\elements\Category::find() - ->title('*Foo*') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only categories that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed categories #} -{% set categories = craft.categories() - .trashed() - .all() %} -``` - -```php -// Fetch trashed categories -$categories = \craft\elements\Category::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the categories’ UIDs. - - - - - -::: code -```twig -{# Fetch the category by its UID #} -{% set category = craft.categories() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the category by its UID -$category = \craft\elements\Category::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique categories across all sites #} -{% set categories = craft.categories() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique categories across all sites -$categories = \craft\elements\Category::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `uri` - -Narrows the query results based on the categories’ URIs. - - - -Possible values include: - -| Value | Fetches categories… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the category with that URI #} -{% set category = craft.categories() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the category with that URI -$category = \craft\elements\Category::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching categories eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch categories eager-loaded with the "Related" field’s relations #} -{% set categories = craft.categories() - .with(['related']) - .all() %} -``` - -```php -// Fetch categories eager-loaded with the "Related" field’s relations -$categories = \craft\elements\Category::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/4.x/categories.md)!!! diff --git a/docs/4.x/config/app.md b/docs/4.x/config/app.md index 91514a3ea..ac7422082 100644 --- a/docs/4.x/config/app.md +++ b/docs/4.x/config/app.md @@ -452,30 +452,27 @@ If your queue driver supplies its own worker, set the , which means it will work natively in [load-balanced environments](kb:configuring-load-balanced-environments#mutex-locks). -::: tip -A [NullMutex](craft4:craft\mutex\NullMutex) driver is used when Dev Mode is enabled, since mutex drivers aren’t necessary for local development and we’ve seen issues with mutex in some Windows and Linux filesystems. +::: warning +Prior to 4.6, enabling `devMode` would automatically switch from the default `FileMutex` driver to a special `NullMutex` driver to help avoid some virtualization bugs. Now, `NullMutex` is only used when a database connection is not available (i.e. prior to installation). ::: -You can configure a custom mutex driver by configuring the `mutex` component’s nested `$mutex` property: +You can configure a custom mutex driver by overriding the `mutex` component’s nested `$mutex` property: ```php -// Use mutex driver provided by yii2-redis return [ 'components' => [ 'mutex' => function() { + $generalConfig = Craft::$app->getConfig()->getGeneral(); + $config = [ - 'class' => craft\mutex\Mutex::class, + 'class' => craft\mutex\File::class, + // Alter just this nested property of the main mutex component: 'mutex' => [ - 'class' => yii\redis\Mutex::class, - // set the max duration to 15 minutes for console requests - 'expire' => Craft::$app->request->isConsoleRequest ? 900 : 30, - 'redis' => [ - 'hostname' => App::env('REDIS_HOSTNAME') ?: 'localhost', - 'port' => 6379, - 'password' => App::env('REDIS_PASSWORD') ?: null, - ], + 'class' => yii\mutex\FileMutex::class, + 'fileMode' => $generalConfig->defaultFileMode, + 'dirMode' => $generalConfig->defaultDirMode, ], ]; @@ -483,11 +480,14 @@ return [ return Craft::createObject($config); }, ], + // ... ]; ``` +The specific properties that you can (or must) use in the configuration object will differ based on the specified mutex class—check the driver’s documentation for instructions. + ::: warning -Pay careful attention to the structure, here—we’re only modifying the existing component’s `mutex` _property_ and leaving the rest of its config as-is. +The primary mutex _component_ should always be an instance of . We’re only modifying the existing `mutex` component’s nested _driver_ property and leaving the rest of its config as-is! ::: ## Modules diff --git a/docs/4.x/config/db.md b/docs/4.x/config/db.md index 4cec98142..8a7bfac19 100644 --- a/docs/4.x/config/db.md +++ b/docs/4.x/config/db.md @@ -56,517 +56,5 @@ Finer-grain control of Craft’s database connection is possible by configuring ## Supported Settings - - -### `attributes` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [DbConfig::$attributes](craft4:craft\config\DbConfig::$attributes) - -
- -An array of key-value pairs of PDO attributes to pass into the PDO constructor. - -For example, when using the [MySQL PDO driver](https://php.net/manual/en/ref.pdo-mysql.php), if you wanted to enable a SSL database connection -(assuming [SSL is enabled in MySQL](https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-secure-connections.html) and `'user'` can connect via SSL, -you’d set these: - -```php -->attributes([ - PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem', - PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem', - PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem', -]) -``` - - - -### `charset` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'utf8'` - -Defined by -: [DbConfig::$charset](craft4:craft\config\DbConfig::$charset) - -
- -The charset to use when creating tables. - -::: tip -You can change the character set and collation across all existing database tables using this terminal command: - -```bash -php craft db/convert-charset -``` -::: - -::: code -```php Static Config -->charset('utf8mb4') -``` -```shell Environment Override -CRAFT_DB_CHARSET=utf8mb4 -``` -::: - - - -### `collation` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$collation](craft4:craft\config\DbConfig::$collation) - -Since -: 3.6.4 - -
- -The collation to use when creating tables. - -This is only used by MySQL. If null, the [charset’s](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#charset) default collation will be used. - -| Charset | Default collation | -| --------- | -------------------- | -| `utf8` | `utf8_general_ci` | -| `utf8mb4` | `utf8mb4_0900_ai_ci` | - -::: tip -You can change the character set and collation across all existing database tables using this terminal command: - -```bash -php craft db/convert-charset -``` -::: - -::: code -```php Static Config -->collation('utf8mb4_0900_ai_ci') -``` -```shell Environment Override -CRAFT_DB_COLLATION=utf8mb4_0900_ai_ci -``` -::: - - - -### `database` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$database](craft4:craft\config\DbConfig::$database) - -
- -The name of the database to select. - -::: code -```php Static Config -->database('mydatabase') -``` -```shell Environment Override -CRAFT_DB_DATABASE=mydatabase -``` -::: - - - -### `driver` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$driver](craft4:craft\config\DbConfig::$driver) - -
- -The database driver to use. Either `mysql` for MySQL or `pgsql` for PostgreSQL. - -::: code -```php Static Config -->driver('mysql') -``` -```shell Environment Override -CRAFT_DB_DRIVER=mysql -``` -::: - - - -### `dsn` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$dsn](craft4:craft\config\DbConfig::$dsn) - -
- -The Data Source Name (“DSN”) that tells Craft how to connect to the database. - -DSNs should begin with a driver prefix (`mysql:` or `pgsql:`), followed by driver-specific parameters. -For example, `mysql:host=127.0.0.1;port=3306;dbname=acme_corp`. - -- MySQL parameters: -- PostgreSQL parameters: - -::: code -```php Static Config -->dsn('mysql:host=127.0.0.1;port=3306;dbname=acme_corp') -``` -```shell Environment Override -CRAFT_DB_DSN=mysql:host=127.0.0.1;port=3306;dbname=acme_corp -``` -::: - - - -### `password` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [DbConfig::$password](craft4:craft\config\DbConfig::$password) - -
- -The database password to connect with. - -::: code -```php Static Config -->password('super-secret') -``` -```shell Environment Override -CRAFT_DB_PASSWORD=super-secret -``` -::: - - - -### `port` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$port](craft4:craft\config\DbConfig::$port) - -
- -The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. - -::: code -```php Static Config -->port(3306) -``` -```shell Environment Override -CRAFT_DB_PORT=3306 -``` -::: - - - -### `schema` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `'public'` - -Defined by -: [DbConfig::$schema](craft4:craft\config\DbConfig::$schema) - -
- -The schema that Postgres is configured to use by default (PostgreSQL only). - -::: tip -To force Craft to use the specified schema regardless of PostgreSQL’s `search_path` setting, you must enable -the [setSchemaOnConnect()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-setschemaonconnect) setting. -::: - -::: code -```php Static Config -->schema('myschema,public') -``` -```shell Environment Override -CRAFT_DB_SCHEMA=myschema,public -``` -::: - - - -### `server` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$server](craft4:craft\config\DbConfig::$server) - -
- -The database server name or IP address. Usually `localhost` or `127.0.0.1`. - -::: code -```php Static Config -->server('localhost') -``` -```shell Environment Override -CRAFT_DB_SERVER=localhost -``` -::: - - - -### `setSchemaOnConnect` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [DbConfig::$setSchemaOnConnect](craft4:craft\config\DbConfig::$setSchemaOnConnect) - -Since -: 3.7.27 - -
- -Whether the [schema()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-schema) should be explicitly used for database queries (PostgreSQL only). - -::: warning -This will cause an extra `SET search_path` SQL query to be executed per database connection. Ideally, -PostgreSQL’s `search_path` setting should be configured to prioritize the desired schema. -::: - -::: code -```php Static Config -->setSchemaOnConnect(true) -``` -```shell Environment Override -CRAFT_DB_SET_SCHEMA_ON_CONNECT=true -``` -::: - - - -### `tablePrefix` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$tablePrefix](craft4:craft\config\DbConfig::$tablePrefix) - -
- -If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), -you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase. - -::: code -```php Static Config -->tablePrefix('craft_') -``` -```shell Environment Override -CRAFT_DB_TABLE_PREFIX=craft_ -``` -::: - - - -### `unixSocket` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$unixSocket](craft4:craft\config\DbConfig::$unixSocket) - -
- -MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of -the server and port. If this is specified, then `server` and `port` settings are ignored. - -::: code -```php Static Config -->unixSocket('/Applications/MAMP/tmp/mysql/mysql.sock') -``` -```shell Environment Override -CRAFT_DB_UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock -``` -::: - - - -### `url` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [DbConfig::$url](craft4:craft\config\DbConfig::$url) - -
- -The database connection URL, if one was provided by your hosting environment. - -If this is set, the values for [driver()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-driver), [user()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-user), [database()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-database), [server()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-server), [port()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-port), and [database()](https://docs.craftcms.com/api/v3/craft-config-dbconfig.html#method-database) will be extracted from it. - -::: code -```php Static Config -->url('jdbc:mysql://database.foo:3306/mydb') -``` -```shell Environment Override -CRAFT_DB_URL=jdbc:mysql://database.foo:3306/mydb -``` -::: - - - -### `useUnbufferedConnections` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [DbConfig::$useUnbufferedConnections](craft4:craft\config\DbConfig::$useUnbufferedConnections) - -Since -: 3.7.0 - -
- -Whether batched queries should be executed on a separate, unbuffered database connection. - -This setting only applies to MySQL. It can be enabled when working with high volume content, to prevent -PHP from running out of memory when querying too much data at once. (See - for an explanation -of MySQL’s batch query limitations.) - -For more on Craft batch queries, see . - -::: code -```php Static Config -->useUnbufferedConnections(true) -``` -```shell Environment Override -CRAFT_DB_USE_UNBUFFERED_CONNECTIONS=true -``` -::: - - - -### `user` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'root'` - -Defined by -: [DbConfig::$user](craft4:craft\config\DbConfig::$user) - -
- -The database username to connect with. - -::: code -```php Static Config -->user('db') -``` -```shell Environment Override -CRAFT_DB_USER=db -``` -::: - - - - - + +!!!include(docs/.artifacts/cms/4.x/config-db.md)!!! diff --git a/docs/4.x/config/general.md b/docs/4.x/config/general.md index 61545863d..5940f7ad0 100644 --- a/docs/4.x/config/general.md +++ b/docs/4.x/config/general.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # General Settings This group of settings affects a wide variety of Craft’s features and behaviors. If you are uncertain about whether something is configurable or not, refer to the categories in the table of contents. @@ -20,4899 +24,5 @@ return GeneralConfig::create() There are a number of [ways to provide configuration](./README.md). This file uses the new “[fluent](./README.md#style-map-vs-fluent)” syntax, and contains references to [environment variables](./README.md#env) for settings that may change between environments. ::: - - -## System - -### `accessibilityDefaults` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[ - 'alwaysShowFocusRings' => false, - 'useShapes' => false, - 'underlineLinks' => false, - 'notificationDuration' => 5000, -]` - -Defined by -: [GeneralConfig::$accessibilityDefaults](craft4:craft\config\GeneralConfig::$accessibilityDefaults) - -Since -: 3.6.4 - -
- -The default user accessibility preferences that should be applied to users that haven’t saved their preferences yet. - -The array can contain the following keys: - -- `alwaysShowFocusRings` - Whether focus rings should always be shown when an element has focus. -- `useShapes` – Whether shapes should be used to represent statuses. -- `underlineLinks` – Whether links should be underlined. -- `notificationDuration` – How long notifications should be shown before they disappear automatically (in - milliseconds). Set to `0` to show them indefinitely. - -```php -->accessibilityDefaults([ - 'useShapes' => true, -]) -``` - - - -### `allowAdminChanges` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$allowAdminChanges](craft4:craft\config\GeneralConfig::$allowAdminChanges) - -Since -: 3.1.0 - -
- -Whether admins should be allowed to make administrative changes to the system. - -When this is disabled, the Settings section will be hidden, the Craft edition and Craft/plugin versions will be locked, -and the project config and Plugin Store will become read-only—though Craft and plugin licenses may still be purchased. - -It’s best to disable this in production environments with a deployment workflow that runs `composer install` and -[propagates project config updates](../project-config.md#propagating-changes) on deploy. - -::: warning -Don’t disable this setting until **all** environments have been updated to Craft 3.1.0 or later. -::: - -::: code -```php Static Config -->allowAdminChanges(false) -``` -```shell Environment Override -CRAFT_ALLOW_ADMIN_CHANGES=false -``` -::: - - - -### `allowSimilarTags` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$allowSimilarTags](craft4:craft\config\GeneralConfig::$allowSimilarTags) - -
- -Whether users should be allowed to create similarly-named tags. - -::: code -```php Static Config -->allowSimilarTags(true) -``` -```shell Environment Override -CRAFT_ALLOW_SIMILAR_TAGS=1 -``` -::: - - - -### `allowUpdates` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$allowUpdates](craft4:craft\config\GeneralConfig::$allowUpdates) - -
- -Whether Craft should allow system and plugin updates in the control panel, and plugin installation from the Plugin Store. - -This setting will automatically be disabled if is disabled. - -::: code -```php Static Config -->allowUpdates(false) -``` -```shell Environment Override -CRAFT_ALLOW_UPDATES=false -``` -::: - - - -### `autoLoginAfterAccountActivation` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$autoLoginAfterAccountActivation](craft4:craft\config\GeneralConfig::$autoLoginAfterAccountActivation) - -
- -Whether users should automatically be logged in after activating their account or resetting their password. - -::: code -```php Static Config -->autoLoginAfterAccountActivation(true) -``` -```shell Environment Override -CRAFT_ALLOW_AUTO_LOGIN_AFTER_ACCOUNT_ACTIVATION=true -``` -::: - - - -### `autosaveDrafts` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$autosaveDrafts](craft4:craft\config\GeneralConfig::$autosaveDrafts) - -Since -: 3.5.6 - -Deprecated -: in 4.0.0 - -
- -Whether drafts should be saved automatically as they are edited. - -::: warning -Disabling this will also disable Live Preview. -::: - -::: code -```php Static Config -->autosaveDrafts(false) -``` -```shell Environment Override -CRAFT_AUTOSAVE_DRAFTS=false -``` -::: - - - -### `backupOnUpdate` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$backupOnUpdate](craft4:craft\config\GeneralConfig::$backupOnUpdate) - -
- -Whether Craft should create a database backup before applying a new system update. - -::: code -```php Static Config -->backupOnUpdate(false) -``` -```shell Environment Override -CRAFT_BACKUP_ON_UPDATE=false -``` -::: - - - -### `cacheDuration` - -
- -Allowed types -: `mixed` - -Default value -: `86400` (1 day) - -Defined by -: [GeneralConfig::$cacheDuration](craft4:craft\config\GeneralConfig::$cacheDuration) - -
- -The default length of time Craft will store data, RSS feed, and template caches. - -If set to `0`, data and RSS feed caches will be stored indefinitely; template caches will be stored for one year. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -->cacheDuration(0) -``` -```shell Environment Override -CRAFT_CACHE_DURATION=0 -``` -::: - - - -### `cpHeadTags` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$cpHeadTags](craft4:craft\config\GeneralConfig::$cpHeadTags) - -Since -: 3.5.0 - -
- -List of additional HTML tags that should be included in the `` of control panel pages. - -Each tag can be specified as an array of the tag name and its attributes. - -For example, you can give the control panel a custom favicon (etc.) like this: - -```php Static Config -->cpHeadTags([ - // Traditional favicon - ['link', ['rel' => 'icon', 'href' => '/icons/favicon.ico']], - // Scalable favicon for browsers that support them - ['link', ['rel' => 'icon', 'type' => 'image/svg+xml', 'sizes' => 'any', 'href' => '/icons/favicon.svg']], - // Touch icon for mobile devices - ['link', ['rel' => 'apple-touch-icon', 'sizes' => '180x180', 'href' => '/icons/touch-icon.svg']], - // Pinned tab icon for Safari - ['link', ['rel' => 'mask-icon', 'href' => '/icons/mask-icon.svg', 'color' => '#663399']], -]) -``` - - - -### `defaultCountryCode` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'US'` - -Defined by -: [GeneralConfig::$defaultCountryCode](craft4:craft\config\GeneralConfig::$defaultCountryCode) - -Since -: 4.5.0 - -
- -The two-letter country code that addresses will be set to by default. - -See for a list of acceptable country codes. - -::: code -```php Static Config -->defaultCountryCode('GB') -``` -```shell Environment Override -CRAFT_DEFAULT_COUNTRY_CODE=GB -``` -::: - - - -### `defaultCpLanguage` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$defaultCpLanguage](craft4:craft\config\GeneralConfig::$defaultCpLanguage) - -
- -The default language the control panel should use for users who haven’t set a preferred language yet. - -::: code -```php Static Config -->defaultCpLanguage('en-US') -``` -```shell Environment Override -CRAFT_DEFAULT_CP_LANGUAGE=en-US -``` -::: - - - -### `defaultCpLocale` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$defaultCpLocale](craft4:craft\config\GeneralConfig::$defaultCpLocale) - -Since -: 3.5.0 - -
- -The default locale the control panel should use for date/number formatting, for users who haven’t set -a preferred language or formatting locale. - -If this is `null`, the config setting will determine which locale is used for date/number formatting by default. - -::: code -```php Static Config -->defaultCpLocale('en-US') -``` -```shell Environment Override -CRAFT_DEFAULT_CP_LOCALE=en-US -``` -::: - - - -### `defaultDirMode` - -
- -Allowed types -: `mixed` - -Default value -: `0775` - -Defined by -: [GeneralConfig::$defaultDirMode](craft4:craft\config\GeneralConfig::$defaultDirMode) - -
- -The default permission to be set for newly-generated directories. - -If set to `null`, the permission will be determined by the current environment. - -::: code -```php Static Config -->defaultDirMode(0744) -``` -```shell Environment Override -CRAFT_DEFAULT_DIR_MODE=0744 -``` -::: - - - -### `defaultFileMode` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$defaultFileMode](craft4:craft\config\GeneralConfig::$defaultFileMode) - -
- -The default permission to be set for newly-generated files. - -If set to `null`, the permission will be determined by the current environment. - -::: code -```php Static Config -->defaultFileMode(0744) -``` -```shell Environment Override -CRAFT_DEFAULT_FILE_MODE=0744 -``` -::: - - - -### `defaultSearchTermOptions` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$defaultSearchTermOptions](craft4:craft\config\GeneralConfig::$defaultSearchTermOptions) - -
- -The default options that should be applied to each search term. - -Options include: - -- `subLeft` – Whether to include keywords that contain the term, with additional characters before it. (`false` by default) -- `subRight` – Whether to include keywords that contain the term, with additional characters after it. (`true` by default) -- `exclude` – Whether search results should *exclude* records with this term. (`false` by default) -- `exact` – Whether the term must be an exact match (only applies if the search term specifies an attribute). (`false` by default) - -```php Static Config -->defaultSearchTermOptions([ - 'subLeft' => true, - 'exclude' => 'secret', -]) -``` - - - -### `defaultTemplateExtensions` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[ - 'html', - 'twig', -]` - -Defined by -: [GeneralConfig::$defaultTemplateExtensions](craft4:craft\config\GeneralConfig::$defaultTemplateExtensions) - -
- -The template file extensions Craft will look for when matching a template path to a file on the front end. - -::: code -```php Static Config -->defaultTemplateExtensions(['html', 'twig', 'txt']) -``` -```shell Environment Override -CRAFT_DEFAULT_TEMPLATE_EXTENSIONS=html,twig,txt -``` -::: - - - -### `defaultWeekStartDay` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `1` (Monday) - -Defined by -: [GeneralConfig::$defaultWeekStartDay](craft4:craft\config\GeneralConfig::$defaultWeekStartDay) - -
- -The default day new users should have set as their Week Start Day. - -This should be set to one of the following integers: - -- `0` – Sunday -- `1` – Monday -- `2` – Tuesday -- `3` – Wednesday -- `4` – Thursday -- `5` – Friday -- `6` – Saturday - -::: code -```php Static Config -->defaultWeekStartDay(0) -``` -```shell Environment Override -CRAFT_DEFAULT_WEEK_START_DAY=0 -``` -::: - - - -### `devMode` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$devMode](craft4:craft\config\GeneralConfig::$devMode) - -
- -Whether the system should run in [Dev Mode](https://craftcms.com/support/dev-mode). - -::: code -```php Static Config -->devMode(true) -``` -```shell Environment Override -CRAFT_DEV_MODE=true -``` -::: - - - -### `disabledPlugins` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$disabledPlugins](craft4:craft\config\GeneralConfig::$disabledPlugins) - -Since -: 3.1.9 - -
- -Array of plugin handles that should be disabled, regardless of what the project config says. - -```php -->disabledPlugins([ - 'webhooks', -]) -``` - -This can also be set to `'*'` to disable **all** plugins. - -```php -->disabledPlugins('*') -``` - -::: warning -This should not be set on a per-environment basis, as it could result in plugin schema version mismatches -between environments, which will prevent project config changes from getting applied. -::: - -::: code -```php Static Config -->disabledPlugins([ - 'redactor', - 'webhooks', -]) -``` -```shell Environment Override -CRAFT_DISABLED_PLUGINS=redactor,webhooks -``` -::: - - - -### `disallowRobots` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$disallowRobots](craft4:craft\config\GeneralConfig::$disallowRobots) - -Since -: 3.5.10 - -
- -Whether front end requests should respond with `X-Robots-Tag: none` HTTP headers, indicating that pages should not be indexed, -and links on the page should not be followed, by web crawlers. - -::: tip -This should be set to `true` for development and staging environments. -::: - -::: code -```php Static Config -->disallowRobots(true) -``` -```shell Environment Override -CRAFT_DISALLOW_ROBOTS=1 -``` -::: - - - -### `enableTemplateCaching` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableTemplateCaching](craft4:craft\config\GeneralConfig::$enableTemplateCaching) - -
- -Whether to enable Craft’s template `{% cache %}` tag on a global basis. - -::: code -```php Static Config -->enableTemplateCaching(false) -``` -```shell Environment Override -CRAFT_ENABLE_TEMPLATE_CACHING=false -``` -::: - - - -### `errorTemplatePrefix` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [GeneralConfig::$errorTemplatePrefix](craft4:craft\config\GeneralConfig::$errorTemplatePrefix) - -
- -The prefix that should be prepended to HTTP error status codes when determining the path to look for an error’s template. - -If set to `'_'` your site’s 404 template would live at `templates/_404.twig`, for example. - -::: code -```php Static Config -->errorTemplatePrefix('_') -``` -```shell Environment Override -CRAFT_ERROR_TEMPLATE_PREFIX=_ -``` -::: - - - -### `extraAllowedFileExtensions` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$extraAllowedFileExtensions](craft4:craft\config\GeneralConfig::$extraAllowedFileExtensions) - -
- -List of file extensions that will be merged into the config setting. - -::: code -```php Static Config -->extraAllowedFileExtensions(['mbox', 'xml']) -``` -```shell Environment Override -CRAFT_EXTRA_ALLOWED_FILE_EXTENSIONS=mbox,xml -``` -::: - - - -### `extraAppLocales` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$extraAppLocales](craft4:craft\config\GeneralConfig::$extraAppLocales) - -Since -: 3.0.24 - -
- -List of extra locale IDs that the application should support, and users should be able to select as their Preferred Language. - -::: code -```php Static Config -->extraAppLocales(['uk']) -``` -```shell Environment Override -CRAFT_EXTRA_APP_LOCALES=uk -``` -::: - - - -### `handleCasing` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `GeneralConfig::CAMEL_CASE` - -Defined by -: [GeneralConfig::$handleCasing](craft4:craft\config\GeneralConfig::$handleCasing) - -Since -: 3.6.0 - -
- -The casing to use for autogenerated component handles. - - - -### `headlessMode` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$headlessMode](craft4:craft\config\GeneralConfig::$headlessMode) - -Since -: 3.3.0 - -
- -Whether the system should run in Headless Mode, which optimizes the system and control panel for headless CMS implementations. - -When this is enabled, the following changes will take place: - -- Template settings for sections and category groups will be hidden. -- Template route management will be hidden. -- Front-end routing will skip checks for element and template requests. -- Front-end responses will be JSON-formatted rather than HTML by default. -- Twig will be configured to escape unsafe strings for JavaScript/JSON rather than HTML by default for front-end requests. -- The , , , and settings will be ignored. - -::: tip -With Headless Mode enabled, users may only set passwords and verify email addresses via the control panel. Be sure to grant “Access the control -panel” permission to all content editors and administrators. You’ll also need to set the config setting if the control -panel is located on a different domain than your front end. -::: - -::: code -```php Static Config -->headlessMode(true) -``` -```shell Environment Override -CRAFT_HEADLESS_MODE=1 -``` -::: - - - -### `httpProxy` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$httpProxy](craft4:craft\config\GeneralConfig::$httpProxy) - -Since -: 3.7.0 - -
- -The proxy server that should be used for outgoing HTTP requests. - -This can be set to a URL (`http://localhost`) or a URL plus a port (`http://localhost:8125`). - -::: code -```php Static Config -->httpProxy(' -``` -```shell Environment Override -CRAFT_HTTP_PROXY=http://localhost -``` -::: - - - -### `indexTemplateFilenames` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[ - 'index', -]` - -Defined by -: [GeneralConfig::$indexTemplateFilenames](craft4:craft\config\GeneralConfig::$indexTemplateFilenames) - -
- -The template filenames Craft will look for within a directory to represent the directory’s “index” template when -matching a template path to a file on the front end. - -::: code -```php Static Config -->indexTemplateFilenames(['index', 'default']) -``` -```shell Environment Override -CRAFT_INDEX_TEMPLATE_FILENAMES=index,default -``` -::: - - - -### `ipHeaders` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$ipHeaders](craft4:craft\config\GeneralConfig::$ipHeaders) - -
- -List of headers where proxies store the real client IP. - -See [yii\web\Request::$ipHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$ipHeaders-detail) for more details. - -If not set, the default [craft\web\Request::$ipHeaders](https://docs.craftcms.com/api/v3/craft-web-request.html#ipheaders) value will be used. - -::: code -```php Static Config -->ipHeaders(['X-Forwarded-For', 'CF-Connecting-IP']) -``` -```shell Environment Override -CRAFT_IP_HEADERS=X-Forwarded-For,CF-Connecting-IP -``` -::: - - - -### `isSystemLive` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$isSystemLive](craft4:craft\config\GeneralConfig::$isSystemLive) - -
- -Whether the site is currently live. If set to `true` or `false`, it will take precedence over the System Status setting -in Settings → General. - -::: code -```php Static Config -->isSystemLive(true) -``` -```shell Environment Override -CRAFT_IS_SYSTEM_LIVE=true -``` -::: - - - -### `limitAutoSlugsToAscii` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$limitAutoSlugsToAscii](craft4:craft\config\GeneralConfig::$limitAutoSlugsToAscii) - -
- -Whether non-ASCII characters in auto-generated slugs should be converted to ASCII (i.e. ñ → n). - -::: tip -This only affects the JavaScript auto-generated slugs. Non-ASCII characters can still be used in slugs if entered manually. -::: - -::: code -```php Static Config -->limitAutoSlugsToAscii(true) -``` -```shell Environment Override -CRAFT_LIMIT_AUTO_SLUGS_TO_ASCII=1 -``` -::: - - - -### `maxBackups` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [false](https://php.net/language.types.boolean) - -Default value -: `20` - -Defined by -: [GeneralConfig::$maxBackups](craft4:craft\config\GeneralConfig::$maxBackups) - -
- -The number of backups Craft should make before it starts deleting the oldest backups. If set to `false`, Craft will -not delete any backups. - -::: code -```php Static Config -->maxBackups(5) -``` -```shell Environment Override -CRAFT_MAX_BACKUPS=5 -``` -::: - - - -### `maxRevisions` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [null](https://php.net/language.types.null) - -Default value -: `50` - -Defined by -: [GeneralConfig::$maxRevisions](craft4:craft\config\GeneralConfig::$maxRevisions) - -Since -: 3.2.0 - -
- -The maximum number of revisions that should be stored for each element. - -Set to `0` if you want to store an unlimited number of revisions. - -::: code -```php Static Config -->maxRevisions(25) -``` -```shell Environment Override -CRAFT_MAX_REVISIONS=25 -``` -::: - - - -### `maxSlugIncrement` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `100` - -Defined by -: [GeneralConfig::$maxSlugIncrement](craft4:craft\config\GeneralConfig::$maxSlugIncrement) - -
- -The highest number Craft will tack onto a slug in order to make it unique before giving up and throwing an error. - -::: code -```php Static Config -->maxSlugIncrement(10) -``` -```shell Environment Override -CRAFT_MAX_SLUG_INCREMENT=10 -``` -::: - - - -### `permissionsPolicyHeader` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$permissionsPolicyHeader](craft4:craft\config\GeneralConfig::$permissionsPolicyHeader) - -Since -: 3.6.14 - -
- -The `Permissions-Policy` header that should be sent for web responses. - -::: code -```php Static Config -->permissionsPolicyHeader('Permissions-Policy: geolocation=(self)') -``` -```shell Environment Override -CRAFT_PERMISSIONS_POLICY_HEADER=Permissions-Policy: geolocation=(self) -``` -::: - - - -### `phpMaxMemoryLimit` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$phpMaxMemoryLimit](craft4:craft\config\GeneralConfig::$phpMaxMemoryLimit) - -
- -The maximum amount of memory Craft will try to reserve during memory-intensive operations such as zipping, -unzipping and updating. Defaults to an empty string, which means it will use as much memory as it can. - -See for a list of acceptable values. - -::: code -```php Static Config -->phpMaxMemoryLimit('512M') -``` -```shell Environment Override -CRAFT_PHP_MAX_MEMORY_LIMIT=512M -``` -::: - - - -### `preloadSingles` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$preloadSingles](craft4:craft\config\GeneralConfig::$preloadSingles) - -Since -: 4.4.0 - -
- -Whether Single section entries should be preloaded for Twig templates. - -When enabled, Craft will make an educated guess on which Singles should be preloaded for each template based on -the variable names that are referenced. - -::: warning -You will need to clear your compiled templates from the Caches utility before this setting will take effect. -::: - -::: code -```php Static Config -->preloadSingles() -``` -```shell Environment Override -CRAFT_PRELOAD_SINGLES=true -``` -::: - - - -### `previewIframeResizerOptions` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$previewIframeResizerOptions](craft4:craft\config\GeneralConfig::$previewIframeResizerOptions) - -Since -: 3.5.0 - -
- -Custom [iFrame Resizer options](http://davidjbradshaw.github.io/iframe-resizer/#options) that should be used for preview iframes. - -```php Static Config -->previewIframeResizerOptions([ - 'autoResize' => false, -]) -``` - - - -### `privateTemplateTrigger` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'_'` - -Defined by -: [GeneralConfig::$privateTemplateTrigger](craft4:craft\config\GeneralConfig::$privateTemplateTrigger) - -
- -The template path segment prefix that should be used to identify “private” templates, which are templates that are not -directly accessible via a matching URL. - -Set to an empty value to disable public template routing. - -::: code -```php Static Config -->privateTemplateTrigger('') -``` -```shell Environment Override -CRAFT_PRIVATE_TEMPLATE_TRIGGER= -``` -::: - - - -### `runQueueAutomatically` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$runQueueAutomatically](craft4:craft\config\GeneralConfig::$runQueueAutomatically) - -
- -Whether Craft should run pending queue jobs automatically when someone visits the control panel. - -If disabled, an alternate queue worker *must* be set up separately, either as an -[always-running daemon](https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/worker.md), or a cron job that runs the -`queue/run` command every minute: - -```cron -* * * * * /path/to/project/craft queue/run -``` - -::: tip -This setting should be disabled for servers running Win32, or with Apache’s mod_deflate/mod_gzip installed, -where PHP’s [flush()](https://php.net/manual/en/function.flush.php) method won’t work. -::: - -::: code -```php Static Config -->runQueueAutomatically(false) -``` -```shell Environment Override -CRAFT_RUN_QUEUE_AUTOMATICALLY=false -``` -::: - - - -### `sameSiteCookieValue` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$sameSiteCookieValue](craft4:craft\config\GeneralConfig::$sameSiteCookieValue) - -Since -: 3.1.33 - -
- -The [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) value that should be set on Craft cookies, if any. - - - -### `sendContentLengthHeader` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$sendContentLengthHeader](craft4:craft\config\GeneralConfig::$sendContentLengthHeader) - -Since -: 3.7.3 - -
- -Whether a `Content-Length` header should be sent with responses. - -::: code -```php Static Config -->sendContentLengthHeader(true) -``` -```shell Environment Override -CRAFT_SEND_CONTENT_LENGTH_HEADER=1 -``` -::: - - - -### `sendPoweredByHeader` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$sendPoweredByHeader](craft4:craft\config\GeneralConfig::$sendPoweredByHeader) - -
- -Whether an `X-Powered-By: Craft CMS` header should be sent, helping services like [BuiltWith](https://builtwith.com/) and -[Wappalyzer](https://www.wappalyzer.com/) identify that the site is running on Craft. - -::: code -```php Static Config -->sendPoweredByHeader(false) -``` -```shell Environment Override -CRAFT_SEND_POWERED_BY_HEADER=false -``` -::: - - - -### `slugWordSeparator` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'-'` - -Defined by -: [GeneralConfig::$slugWordSeparator](craft4:craft\config\GeneralConfig::$slugWordSeparator) - -
- -The character(s) that should be used to separate words in slugs. - -::: code -```php Static Config -->slugWordSeparator('.') -``` -```shell Environment Override -CRAFT_SLUG_WORD_SEPARATOR=. -``` -::: - - - -### `testToEmailAddress` - -
- -Allowed types -: [string](https://php.net/language.types.string), [array](https://php.net/language.types.array), [null](https://php.net/language.types.null), [false](https://php.net/language.types.boolean) - -Default value -: `null` - -Defined by -: [GeneralConfig::$testToEmailAddress](craft4:craft\config\GeneralConfig::$testToEmailAddress) - -
- -Configures Craft to send all system emails to either a single email address or an array of email addresses -for testing purposes. - -By default, the recipient name(s) will be “Test Recipient”, but you can customize that by setting the value with the format -`['me@domain.tld' => 'Name']`. - -::: code -```php Static Config -->testToEmailAddress('me@domain.tld') -``` -```shell Environment Override -CRAFT_TEST_TO_EMAIL_ADDRESS=me@domain.tld -``` -::: - - - -### `timezone` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$timezone](craft4:craft\config\GeneralConfig::$timezone) - -
- -The timezone of the site. If set, it will take precedence over the Timezone setting in Settings → General. - -This can be set to one of PHP’s [supported timezones](https://php.net/manual/en/timezones.php). - -::: code -```php Static Config -->timezone('Europe/London') -``` -```shell Environment Override -CRAFT_TIMEZONE=Europe/London -``` -::: - - - -### `translationDebugOutput` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$translationDebugOutput](craft4:craft\config\GeneralConfig::$translationDebugOutput) - -
- -Whether translated messages should be wrapped in special characters to help find any strings that are not being run through -`Craft::t()` or the `|translate` filter. - -::: code -```php Static Config -->translationDebugOutput(true) -``` -```shell Environment Override -CRAFT_TRANSLATION_DEBUG_OUTPUT=1 -``` -::: - - - -### `useEmailAsUsername` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$useEmailAsUsername](craft4:craft\config\GeneralConfig::$useEmailAsUsername) - -
- -Whether Craft should set users’ usernames to their email addresses, rather than let them set their username separately. - -If you enable this setting after user accounts already exist, run this terminal command to update existing usernames: - -```bash -php craft utils/update-usernames -``` - -::: code -```php Static Config -->useEmailAsUsername(true) -``` -```shell Environment Override -CRAFT_USE_EMAIL_AS_USERNAME=1 -``` -::: - - - -### `useFileLocks` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$useFileLocks](craft4:craft\config\GeneralConfig::$useFileLocks) - -
- -Whether to grab an exclusive lock on a file when writing to it by using the `LOCK_EX` flag. - -Some file systems, such as NFS, do not support exclusive file locking. - -If `null`, Craft will try to detect if the underlying file system supports exclusive file locking and cache the results. - -::: code -```php Static Config -->useFileLocks(false) -``` -```shell Environment Override -CRAFT_USE_FILE_LOCKS=false -``` -::: - - - -### `useIframeResizer` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$useIframeResizer](craft4:craft\config\GeneralConfig::$useIframeResizer) - -Since -: 3.5.5 - -
- -Whether [iFrame Resizer options](http://davidjbradshaw.github.io/iframe-resizer/#options) should be used for Live Preview. - -Using iFrame Resizer makes it possible for Craft to retain the preview’s scroll position between page loads, for cross-origin web pages. - -It works by setting the height of the iframe to match the height of the inner web page, and the iframe’s container will be scrolled rather -than the iframe document itself. This can lead to some unexpected CSS issues, however, because the previewed viewport height will be taller -than the visible portion of the iframe. - -If you have a [decoupled front end](https://craftcms.com/docs/4.x/entries.html#previewing-decoupled-front-ends), you will need to include -[iframeResizer.contentWindow.min.js](https://raw.github.com/davidjbradshaw/iframe-resizer/master/js/iframeResizer.contentWindow.min.js) on your -page as well for this to work. You can conditionally include it for only Live Preview requests by checking if the requested URL contains a -`x-craft-live-preview` query string parameter. - -::: tip -You can customize the behavior of iFrame Resizer via the config setting. -::: - -::: code -```php Static Config -->useIframeResizer(true) -``` -```shell Environment Override -CRAFT_USE_IFRAME_RESIZER=1 -``` -::: - - - -## Environment - -### `aliases` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$aliases](craft4:craft\config\GeneralConfig::$aliases) - -
- -Any custom Yii [aliases](https://www.yiiframework.com/doc/guide/2.0/en/concept-aliases) that should be defined for every request. - -```php Static Config -->aliases([ - '@webroot' => '/var/www/', -]) -``` - - - -### `backupCommand` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null), [false](https://php.net/language.types.boolean) - -Default value -: `null` - -Defined by -: [GeneralConfig::$backupCommand](craft4:craft\config\GeneralConfig::$backupCommand) - -
- -The shell command that Craft should execute to create a database backup. - -When set to `null` (default), Craft will run `mysqldump` or `pg_dump`, provided that those libraries are in the `$PATH` variable -for the system user running the web server. - -You may provide your own command, which can include several tokens Craft will substitute at runtime: - -- `{file}` - the target backup file path -- `{port}` - the current database port -- `{server}` - the current database hostname -- `{user}` - user that was used to connect to the database -- `{password}` - password for the specified `{user}` -- `{database}` - the current database name -- `{schema}` - the current database schema (if any) - -This can also be set to `false` to disable database backups completely. - -::: code -```php Static Config -->backupCommand(false) -``` -```shell Environment Override -CRAFT_BACKUP_COMMAND=false -``` -::: - - - -### `buildId` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$buildId](craft4:craft\config\GeneralConfig::$buildId) - -Since -: 4.0.0 - -
- -A unique ID representing the current build of the codebase. - -This should be set to something unique to the deployment, e.g. a Git SHA or a deployment timestamp. - -::: code -```php Static Config -->buildId(\craft\helpers\App::env('GIT_SHA')) -``` -```shell Environment Override -CRAFT_BUILD_ID=$GIT_SHA -``` -::: - - - -### `defaultCookieDomain` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [GeneralConfig::$defaultCookieDomain](craft4:craft\config\GeneralConfig::$defaultCookieDomain) - -
- -The domain that cookies generated by Craft should be created for. If blank, it will be left up to the browser to determine -which domain to use (almost always the current). If you want the cookies to work for all subdomains, for example, you could -set this to `'.my-project.tld'`. - -::: code -```php Static Config -->defaultCookieDomain('.my-project.tld') -``` -```shell Environment Override -CRAFT_DEFAULT_COOKIE_DOMAIN=.my-project.tld -``` -::: - - - -### `resourceBasePath` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'@webroot/cpresources'` - -Defined by -: [GeneralConfig::$resourceBasePath](craft4:craft\config\GeneralConfig::$resourceBasePath) - -
- -The path to the root directory that should store published control panel resources. - -::: code -```php Static Config -->resourceBasePath('@webroot/craft-resources') -``` -```shell Environment Override -CRAFT_RESOURCE_BASE_PATH=@webroot/craft-resources -``` -::: - - - -### `resourceBaseUrl` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'@web/cpresources'` - -Defined by -: [GeneralConfig::$resourceBaseUrl](craft4:craft\config\GeneralConfig::$resourceBaseUrl) - -
- -The URL to the root directory that should store published control panel resources. - -::: code -```php Static Config -->resourceBaseUrl('@web/craft-resources') -``` -```shell Environment Override -CRAFT_RESOURCE_BASE_URL=@web/craft-resources -``` -::: - - - -### `restoreCommand` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null), [false](https://php.net/language.types.boolean) - -Default value -: `null` - -Defined by -: [GeneralConfig::$restoreCommand](craft4:craft\config\GeneralConfig::$restoreCommand) - -
- -The shell command Craft should execute to restore a database backup. - -By default Craft will run `mysql` or `psql`, provided those libraries are in the `$PATH` variable for the user the web server is running as. - -There are several tokens you can use that Craft will swap out at runtime: - -- `{path}` - the backup file path -- `{port}` - the current database port -- `{server}` - the current database hostname -- `{user}` - the user to connect to the database -- `{database}` - the current database name -- `{schema}` - the current database schema (if any) - -This can also be set to `false` to disable database restores completely. - -::: code -```php Static Config -->restoreCommand(false) -``` -```shell Environment Override -CRAFT_RESTORE_COMMAND=false -``` -::: - - - -## Routing - -### `actionTrigger` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'actions'` - -Defined by -: [GeneralConfig::$actionTrigger](craft4:craft\config\GeneralConfig::$actionTrigger) - -
- -The URI segment Craft should look for when determining if the current request should be routed to a controller action. - -::: code -```php Static Config -->actionTrigger('do-it') -``` -```shell Environment Override -CRAFT_ACTION_TRIGGER=do-it -``` -::: - - - -### `activateAccountSuccessPath` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$activateAccountSuccessPath](craft4:craft\config\GeneralConfig::$activateAccountSuccessPath) - -
- -The URI that users without access to the control panel should be redirected to after activating their account. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->activateAccountSuccessPath('welcome') -``` -```shell Environment Override -CRAFT_ACTIVATE_ACCOUNT_SUCCESS_PATH=welcome -``` -::: - - - -### `addTrailingSlashesToUrls` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$addTrailingSlashesToUrls](craft4:craft\config\GeneralConfig::$addTrailingSlashesToUrls) - -
- -Whether auto-generated URLs should have trailing slashes. - -::: code -```php Static Config -->addTrailingSlashesToUrls(true) -``` -```shell Environment Override -CRAFT_ADD_TRAILING_SLASHES_TO_URLS=1 -``` -::: - - - -### `allowUppercaseInSlug` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$allowUppercaseInSlug](craft4:craft\config\GeneralConfig::$allowUppercaseInSlug) - -
- -Whether uppercase letters should be allowed in slugs. - -::: code -```php Static Config -->allowUppercaseInSlug(true) -``` -```shell Environment Override -CRAFT_ALLOW_UPPERCASE_IN_SLUG=1 -``` -::: - - - -### `baseCpUrl` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$baseCpUrl](craft4:craft\config\GeneralConfig::$baseCpUrl) - -
- -The base URL Craft should use when generating control panel URLs. - -It will be determined automatically if left blank. - -::: tip -The base control panel URL should **not** include the [control panel trigger word](config4:cpTrigger) (e.g. `/admin`). -::: - -::: code -```php Static Config -->baseCpUrl(' -``` -```shell Environment Override -CRAFT_BASE_CP_URL=https://cms.my-project.tld/ -``` -::: - - - -### `cpTrigger` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `'admin'` - -Defined by -: [GeneralConfig::$cpTrigger](craft4:craft\config\GeneralConfig::$cpTrigger) - -
- -The URI segment Craft should look for when determining if the current request should route to the control panel rather than -the front-end website. - -This can be set to `null` if you have a dedicated hostname for the control panel (e.g. `cms.my-project.tld`), or you are running Craft in -[Headless Mode](config4:headlessMode). If you do that, you will need to ensure that the control panel is being served from its own web root -directory on your server, with an `index.php` file that defines the `CRAFT_CP` PHP constant. - -```php -define('CRAFT_CP', true); -``` - -Alternatively, you can set the config setting, but then you will run the risk of losing access to portions of your -control panel due to URI conflicts with actual folders/files in your main web root. - -(For example, if you have an `assets/` folder, that would conflict with the `/assets` page in the control panel.) - -::: code -```php Static Config -->cpTrigger(null) -``` -```shell Environment Override -CRAFT_CP_TRIGGER= -``` -::: - - - -### `invalidUserTokenPath` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$invalidUserTokenPath](craft4:craft\config\GeneralConfig::$invalidUserTokenPath) - -
- -The URI Craft should redirect to when user token validation fails. A token is used on things like setting and resetting user account -passwords. Note that this only affects front-end site requests. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -// 1 day -->invalidUserTokenPath('nope') -``` -```shell Environment Override -# 1 day -CRAFT_INVALID_USER_TOKEN_PATH=nope -``` -::: - - - -### `loginPath` - -
- -Allowed types -: `mixed` - -Default value -: `'login'` - -Defined by -: [GeneralConfig::$loginPath](craft4:craft\config\GeneralConfig::$loginPath) - -
- -The URI Craft should use for user login on the front end. - -This can be set to `false` to disable front-end login. - -Note that this config setting is ignored when is enabled. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->loginPath(false) -``` -```shell Environment Override -CRAFT_LOGIN_PATH=false -``` -::: - - - -### `logoutPath` - -
- -Allowed types -: `mixed` - -Default value -: `'logout'` - -Defined by -: [GeneralConfig::$logoutPath](craft4:craft\config\GeneralConfig::$logoutPath) - -
- -The URI Craft should use for user logout on the front end. - -This can be set to `false` to disable front-end logout. - -Note that this config setting is ignored when is enabled. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->logoutPath(false) -``` -```shell Environment Override -CRAFT_LOGOUT_PATH=false -``` -::: - - - -### `omitScriptNameInUrls` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$omitScriptNameInUrls](craft4:craft\config\GeneralConfig::$omitScriptNameInUrls) - -
- -Whether generated URLs should omit `index.php` (e.g. `http://my-project.tld/path` instead of `http://my-project.tld/index.php/path`) - -This can only be possible if your server is configured to redirect would-be 404s to `index.php`, for example, with the redirect found -in the `.htaccess` file that came with Craft: - -``` -RewriteEngine On -RewriteCond %{REQUEST_FILENAME} !-f -RewriteCond %{REQUEST_FILENAME} !-d -RewriteRule (.+) /index.php?p= [QSA,L] -``` - -::: code -```php Static Config -->omitScriptNameInUrls(true) -``` -```shell Environment Override -CRAFT_OMIT_SCRIPT_NAME_IN_URLS=1 -``` -::: - -::: tip -Even when this is set to `true`, the script name could still be included in some action URLs. -If you want to ensure that `index.php` is fully omitted from **all** generated URLs, set the -config setting to `null`. -::: - - - -### `pageTrigger` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'p'` - -Defined by -: [GeneralConfig::$pageTrigger](craft4:craft\config\GeneralConfig::$pageTrigger) - -
- -The string preceding a number which Craft will look for when determining if the current request is for a particular page in -a paginated list of pages. - -Example Value | Example URI -------------- | ----------- -`p` | `/news/p5` -`page` | `/news/page5` -`page/` | `/news/page/5` -`?page` | `/news?page=5` - -::: tip -If you want to set this to `?p` (e.g. `/news?p=5`), you’ll also need to change your setting which defaults to `p`. -If your server is running Apache, you’ll need to update the redirect code in your `.htaccess` file to match your new `pathParam` value. -::: - -::: code -```php Static Config -->pageTrigger('page') -``` -```shell Environment Override -CRAFT_PAGE_TRIGGER=page -``` -::: - - - -### `pathParam` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `'p'` - -Defined by -: [GeneralConfig::$pathParam](craft4:craft\config\GeneralConfig::$pathParam) - -
- -The query string param that Craft will check when determining the request’s path. - -This can be set to `null` if your web server is capable of directing traffic to `index.php` without a query string param. -If you’re using Apache, that means you’ll need to change the `RewriteRule` line in your `.htaccess` file to: - -``` -RewriteRule (.+) index.php [QSA,L] -``` - -::: code -```php Static Config -->pathParam(null) -``` -```shell Environment Override -CRAFT_PATH_PARAM= -``` -::: - - - -### `postCpLoginRedirect` - -
- -Allowed types -: `mixed` - -Default value -: `'dashboard'` - -Defined by -: [GeneralConfig::$postCpLoginRedirect](craft4:craft\config\GeneralConfig::$postCpLoginRedirect) - -
- -The path users should be redirected to after logging into the control panel. - -This setting will also come into effect if a user visits the control panel’s login page (`/admin/login`) or the control panel’s -root URL (`/admin`) when they are already logged in. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->postCpLoginRedirect('entries') -``` -```shell Environment Override -CRAFT_POST_CP_LOGIN_REDIRECT=entries -``` -::: - - - -### `postLoginRedirect` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$postLoginRedirect](craft4:craft\config\GeneralConfig::$postLoginRedirect) - -
- -The path users should be redirected to after logging in from the front-end site. - -This setting will also come into effect if the user visits the login page (as specified by the config setting) when -they are already logged in. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->postLoginRedirect('welcome') -``` -```shell Environment Override -CRAFT_POST_LOGIN_REDIRECT=welcome -``` -::: - - - -### `postLogoutRedirect` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$postLogoutRedirect](craft4:craft\config\GeneralConfig::$postLogoutRedirect) - -
- -The path that users should be redirected to after logging out from the front-end site. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->postLogoutRedirect('goodbye') -``` -```shell Environment Override -CRAFT_POST_LOGOUT_REDIRECT=goodbye -``` -::: - - - -### `setPasswordPath` - -
- -Allowed types -: `mixed` - -Default value -: `'setpassword'` - -Defined by -: [GeneralConfig::$setPasswordPath](craft4:craft\config\GeneralConfig::$setPasswordPath) - -
- -The URI or URL that Craft should use for Set Password forms on the front end. - -This setting is ignored when is enabled, unless it’s set to an absolute URL. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: tip -You might also want to set in case a user clicks on an expired password reset link. -::: - -::: code -```php Static Config -->setPasswordPath('set-password') -``` -```shell Environment Override -CRAFT_SET_PASSWORD_PATH=set-password -``` -::: - - - -### `setPasswordRequestPath` - -
- -Allowed types -: `mixed` - -Default value -: `null` - -Defined by -: [GeneralConfig::$setPasswordRequestPath](craft4:craft\config\GeneralConfig::$setPasswordRequestPath) - -Since -: 3.5.14 - -
- -The URI to the page where users can request to change their password. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -If this is set, Craft will redirect [.well-known/change-password requests](https://w3c.github.io/webappsec-change-password-url/) to this URI. - -::: tip -You’ll also need to set [setPasswordPath](config4:setPasswordPath), which determines the URI and template path for the Set Password form -where the user resets their password after following the link in the Password Reset email. -::: - -::: code -```php Static Config -->setPasswordRequestPath('request-password') -``` -```shell Environment Override -CRAFT_SET_PASSWORD_REQUEST_PATH=request-password -``` -::: - - - -### `setPasswordSuccessPath` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$setPasswordSuccessPath](craft4:craft\config\GeneralConfig::$setPasswordSuccessPath) - -
- -The URI Craft should redirect users to after setting their password from the front end. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->setPasswordSuccessPath('password-set') -``` -```shell Environment Override -CRAFT_SET_PASSWORD_SUCCESS_PATH=password-set -``` -::: - - - -### `siteToken` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'siteToken'` - -Defined by -: [GeneralConfig::$siteToken](craft4:craft\config\GeneralConfig::$siteToken) - -Since -: 3.5.0 - -
- -The query string parameter name that site tokens should be set to. - -::: code -```php Static Config -->siteToken('t') -``` -```shell Environment Override -CRAFT_SITE_TOKEN=t -``` -::: - - - -### `tokenParam` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'token'` - -Defined by -: [GeneralConfig::$tokenParam](craft4:craft\config\GeneralConfig::$tokenParam) - -
- -The query string parameter name that Craft tokens should be set to. - -::: code -```php Static Config -->tokenParam('t') -``` -```shell Environment Override -CRAFT_TOKEN_PARAM=t -``` -::: - - - -### `usePathInfo` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$usePathInfo](craft4:craft\config\GeneralConfig::$usePathInfo) - -
- -Whether Craft should specify the path using `PATH_INFO` or as a query string parameter when generating URLs. - -This setting only takes effect if is set to `false`. - -::: code -```php Static Config -->usePathInfo(true) -``` -```shell Environment Override -CRAFT_USE_PATH_INFO=1 -``` -::: - - - -### `useSslOnTokenizedUrls` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean), [string](https://php.net/language.types.string) - -Default value -: `'auto'` - -Defined by -: [GeneralConfig::$useSslOnTokenizedUrls](craft4:craft\config\GeneralConfig::$useSslOnTokenizedUrls) - -
- -Determines what protocol/schema Craft will use when generating tokenized URLs. If set to `'auto'`, Craft will check the -current site’s base URL and the protocol of the current request and if either of them are HTTPS will use `https` in the tokenized URL. If not, -will use `http`. - -If set to `false`, Craft will always use `http`. If set to `true`, then, Craft will always use `https`. - -::: code -```php Static Config -->useSslOnTokenizedUrls(true) -``` -```shell Environment Override -CRAFT_USE_SSL_ON_TOKENIZED_URLS=1 -``` -::: - - - -### `verifyEmailPath` - -
- -Allowed types -: `mixed` - -Default value -: `'verifyemail'` - -Defined by -: [GeneralConfig::$verifyEmailPath](craft4:craft\config\GeneralConfig::$verifyEmailPath) - -Since -: 3.4.0 - -
- -The URI or URL that Craft should use for email verification links on the front end. - -This setting is ignored when is enabled, unless it’s set to an absolute URL. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->verifyEmailPath('verify-email') -``` -```shell Environment Override -CRAFT_VERIFY_EMAIL_PATH=verify-email -``` -::: - - - -### `verifyEmailSuccessPath` - -
- -Allowed types -: `mixed` - -Default value -: `''` - -Defined by -: [GeneralConfig::$verifyEmailSuccessPath](craft4:craft\config\GeneralConfig::$verifyEmailSuccessPath) - -Since -: 3.1.20 - -
- -The URI that users without access to the control panel should be redirected to after verifying a new email address. - -See [craft\helpers\ConfigHelper::localizedValue()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-localizedvalue) for a list of supported value types. - -::: code -```php Static Config -->verifyEmailSuccessPath('verified-email') -``` -```shell Environment Override -CRAFT_VERIFY_EMAIL_SUCCESS_PATH=verified-email -``` -::: - - - -## Session - -### `phpSessionName` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'CraftSessionId'` - -Defined by -: [GeneralConfig::$phpSessionName](craft4:craft\config\GeneralConfig::$phpSessionName) - -
- -The name of the PHP session cookie. - -::: code -```php Static Config -->phpSessionName(null) -``` -```shell Environment Override -CRAFT_PHP_SESSION_NAME= -``` -::: - - - -### `rememberUsernameDuration` - -
- -Allowed types -: `mixed` - -Default value -: `31536000` (1 year) - -Defined by -: [GeneralConfig::$rememberUsernameDuration](craft4:craft\config\GeneralConfig::$rememberUsernameDuration) - -
- -The amount of time Craft will remember a username and pre-populate it on the control panel’s Login page. - -Set to `0` to disable this feature altogether. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -->rememberUsernameDuration(0) -``` -```shell Environment Override -CRAFT_REMEMBER_USERNAME_DURATION=0 -``` -::: - - - -### `rememberedUserSessionDuration` - -
- -Allowed types -: `mixed` - -Default value -: `1209600` (14 days) - -Defined by -: [GeneralConfig::$rememberedUserSessionDuration](craft4:craft\config\GeneralConfig::$rememberedUserSessionDuration) - -
- -The amount of time a user stays logged if “Remember Me” is checked on the login page. - -Set to `0` to disable the “Remember Me” feature altogether. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -->rememberedUserSessionDuration(0) -``` -```shell Environment Override -CRAFT_REMEMBERED_USER_SESSION_DURATION=0 -``` -::: - - - -### `requireMatchingUserAgentForSession` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$requireMatchingUserAgentForSession](craft4:craft\config\GeneralConfig::$requireMatchingUserAgentForSession) - -
- -Whether Craft should require a matching user agent string when restoring a user session from a cookie. - -::: code -```php Static Config -->requireMatchingUserAgentForSession(false) -``` -```shell Environment Override -CRAFT_REQUIRE_MATCHING_USER_AGENT_FOR_SESSION=false -``` -::: - - - -### `requireUserAgentAndIpForSession` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$requireUserAgentAndIpForSession](craft4:craft\config\GeneralConfig::$requireUserAgentAndIpForSession) - -
- -Whether Craft should require the existence of a user agent string and IP address when creating a new user session. - -::: code -```php Static Config -->requireUserAgentAndIpForSession(false) -``` -```shell Environment Override -CRAFT_REQUIRE_USER_AGENT_AND_IP_FOR_SESSION=false -``` -::: - - - -### `userSessionDuration` - -
- -Allowed types -: `mixed` - -Default value -: `3600` (1 hour) - -Defined by -: [GeneralConfig::$userSessionDuration](craft4:craft\config\GeneralConfig::$userSessionDuration) - -
- -The amount of time before a user will get logged out due to inactivity. - -Set to `0` if you want users to stay logged in as long as their browser is open rather than a predetermined amount of time. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -// 3 hours -->userSessionDuration(10800) -``` -```shell Environment Override -# 3 hours -CRAFT_USER_SESSION_DURATION=10800 -``` -::: - - - -## Security - -### `blowfishHashCost` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `13` - -Defined by -: [GeneralConfig::$blowfishHashCost](craft4:craft\config\GeneralConfig::$blowfishHashCost) - -
- -The higher the cost value, the longer it takes to generate a password hash and to verify against it. - -Therefore, higher cost slows down a brute-force attack. - -For best protection against brute force attacks, set it to the highest value that is tolerable on production servers. - -The time taken to compute the hash doubles for every increment by one for this value. - -For example, if the hash takes 1 second to compute when the value is 14 then the compute time varies as -2^(value - 14) seconds. - -::: code -```php Static Config -->blowfishHashCost(15) -``` -```shell Environment Override -CRAFT_BLOWFISH_HASH_COST=15 -``` -::: - - - -### `cooldownDuration` - -
- -Allowed types -: `mixed` - -Default value -: `300` (5 minutes) - -Defined by -: [GeneralConfig::$cooldownDuration](craft4:craft\config\GeneralConfig::$cooldownDuration) - -
- -The amount of time a user must wait before re-attempting to log in after their account is locked due to too many -failed login attempts. - -Set to `0` to keep the account locked indefinitely, requiring an admin to manually unlock the account. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -->cooldownDuration(0) -``` -```shell Environment Override -CRAFT_COOLDOWN_DURATION=0 -``` -::: - - - -### `csrfTokenName` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'CRAFT_CSRF_TOKEN'` - -Defined by -: [GeneralConfig::$csrfTokenName](craft4:craft\config\GeneralConfig::$csrfTokenName) - -
- -The name of CSRF token used for CSRF validation if is set to `true`. - -::: code -```php Static Config -->csrfTokenName('MY_CSRF') -``` -```shell Environment Override -CRAFT_CSRF_TOKEN_NAME=MY_CSRF -``` -::: - - - -### `defaultTokenDuration` - -
- -Allowed types -: `mixed` - -Default value -: `86400` (1 day) - -Defined by -: [GeneralConfig::$defaultTokenDuration](craft4:craft\config\GeneralConfig::$defaultTokenDuration) - -
- -The default amount of time tokens can be used before expiring. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -// One week -->defaultTokenDuration(604800) -``` -```shell Environment Override -# One week -CRAFT_DEFAULT_TOKEN_DURATION=604800 -``` -::: - - - -### `deferPublicRegistrationPassword` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$deferPublicRegistrationPassword](craft4:craft\config\GeneralConfig::$deferPublicRegistrationPassword) - -
- -By default, Craft requires a front-end “password” field for public user registrations. Setting this to `true` -removes that requirement for the initial registration form. - -If you have email verification enabled, new users will set their password once they’ve followed the verification link in the email. -If you don’t, the only way they can set their password is to go through your “forgot password” workflow. - -::: code -```php Static Config -->deferPublicRegistrationPassword(true) -``` -```shell Environment Override -CRAFT_DEFER_PUBLIC_REGISTRATION_PASSWORD=true -``` -::: - - - -### `elevatedSessionDuration` - -
- -Allowed types -: `mixed` - -Default value -: `300` (5 minutes) - -Defined by -: [GeneralConfig::$elevatedSessionDuration](craft4:craft\config\GeneralConfig::$elevatedSessionDuration) - -
- -The amount of time a user’s elevated session will last, which is required for some sensitive actions (e.g. user group/permission assignment). - -Set to `0` to disable elevated session support. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -->elevatedSessionDuration(0) -``` -```shell Environment Override -CRAFT_ELEVATED_SESSION_DURATION=0 -``` -::: - - - -### `enableBasicHttpAuth` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$enableBasicHttpAuth](craft4:craft\config\GeneralConfig::$enableBasicHttpAuth) - -Since -: 3.5.0 - -
- -Whether front-end web requests should support basic HTTP authentication. - -::: code -```php Static Config -->enableBasicHttpAuth(true) -``` -```shell Environment Override -CRAFT_ENABLE_BASIC_HTTP_AUTH=1 -``` -::: - - - -### `enableCsrfCookie` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableCsrfCookie](craft4:craft\config\GeneralConfig::$enableCsrfCookie) - -
- -Whether to use a cookie to persist the CSRF token if is enabled. If false, the CSRF token will be -stored in session under the `csrfTokenName` config setting name. Note that while storing CSRF tokens in session increases security, -it requires starting a session for every page that a CSRF token is needed, which may degrade site performance. - -::: code -```php Static Config -->enableCsrfCookie(false) -``` -```shell Environment Override -CRAFT_ENABLE_CSRF_COOKIE=false -``` -::: - - - -### `enableCsrfProtection` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableCsrfProtection](craft4:craft\config\GeneralConfig::$enableCsrfProtection) - -
- -Whether to enable CSRF protection via hidden form inputs for all forms submitted via Craft. - -::: code -```php Static Config -->enableCsrfProtection(false) -``` -```shell Environment Override -CRAFT_ENABLE_CSRF_PROTECTION=false -``` -::: - - - -### `invalidLoginWindowDuration` - -
- -Allowed types -: `mixed` - -Default value -: `3600` (1 hour) - -Defined by -: [GeneralConfig::$invalidLoginWindowDuration](craft4:craft\config\GeneralConfig::$invalidLoginWindowDuration) - -
- -The amount of time to track invalid login attempts for a user, for determining if Craft should lock an account. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -// 1 day -->invalidLoginWindowDuration(86400) -``` -```shell Environment Override -# 1 day -CRAFT_INVALID_LOGIN_WINDOW_DURATION=86400 -``` -::: - - - -### `maxInvalidLogins` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [false](https://php.net/language.types.boolean) - -Default value -: `5` - -Defined by -: [GeneralConfig::$maxInvalidLogins](craft4:craft\config\GeneralConfig::$maxInvalidLogins) - -
- -The number of invalid login attempts Craft will allow within the specified duration before the account gets locked. - -::: code -```php Static Config -->maxInvalidLogins(3) -``` -```shell Environment Override -CRAFT_MAX_INVALID_LOGINS=3 -``` -::: - - - -### `preventUserEnumeration` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$preventUserEnumeration](craft4:craft\config\GeneralConfig::$preventUserEnumeration) - -
- -When `true`, Craft will always return a successful response in the “forgot password” flow, making it difficult to enumerate users. - -When set to `false` and you go through the “forgot password” flow from the control panel login page, you’ll get distinct messages indicating -whether the username/email exists and whether an email was sent with further instructions. This can be helpful for the user attempting to -log in but allow for username/email enumeration based on the response. - -::: code -```php Static Config -->preventUserEnumeration(true) -``` -```shell Environment Override -CRAFT_PREVENT_USER_ENUMERATION=1 -``` -::: - - - -### `previewTokenDuration` - -
- -Allowed types -: `mixed` - -Default value -: `null` (1 day) - -Defined by -: [GeneralConfig::$previewTokenDuration](craft4:craft\config\GeneralConfig::$previewTokenDuration) - -Since -: 3.7.0 - -
- -The amount of time content preview tokens can be used before expiring. - -Defaults to value. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -// 1 hour -->previewTokenDuration(3600) -``` -```shell Environment Override -# 1 hour -CRAFT_PREVIEW_TOKEN_DURATION=3600 -``` -::: - - - -### `sanitizeCpImageUploads` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$sanitizeCpImageUploads](craft4:craft\config\GeneralConfig::$sanitizeCpImageUploads) - -Since -: 3.6.0 - -
- -Whether images uploaded via the control panel should be sanitized. - -::: code -```php Static Config -->sanitizeCpImageUploads(false) -``` -```shell Environment Override -CRAFT_SANITIZE_CP_IMAGE_UPLOADS=false -``` -::: - - - -### `sanitizeSvgUploads` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$sanitizeSvgUploads](craft4:craft\config\GeneralConfig::$sanitizeSvgUploads) - -
- -Whether Craft should sanitize uploaded SVG files and strip out potential malicious-looking content. - -This should definitely be enabled if you are accepting SVG uploads from untrusted sources. - -::: code -```php Static Config -->sanitizeSvgUploads(false) -``` -```shell Environment Override -CRAFT_SANITIZE_SVG_UPLOADS=false -``` -::: - - - -### `secureHeaders` - -
- -Allowed types -: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$secureHeaders](craft4:craft\config\GeneralConfig::$secureHeaders) - -
- -Lists of headers that are, by default, subject to the trusted host configuration. - -See [yii\web\Request::$secureHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureHeaders-detail) for more details. - -If not set, the default [yii\web\Request::$secureHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureHeaders-detail) value will be used. - -::: code -```php Static Config -->secureHeaders([ - 'X-Forwarded-For', - 'X-Forwarded-Host', - 'X-Forwarded-Proto', - 'X-Rewrite-Url', - 'X-Original-Host', - 'CF-Connecting-IP', -]) -``` -```shell Environment Override -CRAFT_SECURE_HEADERS=X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Proto,X-Rewrite-Url,X-Original-Host,CF-Connecting-IP -``` -::: - - - -### `secureProtocolHeaders` - -
- -Allowed types -: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$secureProtocolHeaders](craft4:craft\config\GeneralConfig::$secureProtocolHeaders) - -
- -List of headers to check for determining whether the connection is made via HTTPS. - -See [yii\web\Request::$secureProtocolHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureProtocolHeaders-detail) for more details. - -If not set, the default [yii\web\Request::$secureProtocolHeaders](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$secureProtocolHeaders-detail) value will be used. - -```php Static Config -->secureProtocolHeaders([ - 'X-Forwarded-Proto' => [ - 'https', - ], - 'Front-End-Https' => [ - 'on', - ], - 'CF-Visitor' => [ - '{\"scheme\":\"https\"}', - ], -]) -``` - - - -### `securityKey` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [GeneralConfig::$securityKey](craft4:craft\config\GeneralConfig::$securityKey) - -
- -A private, random, cryptographically-secure key that is used for hashing and encrypting data in [craft\services\Security](craft4:craft\services\Security). - -This value should be the same across all environments. If this key ever changes, any data that was encrypted with it will be inaccessible. - -```php Static Config -->securityKey('2cf24dba5...') -``` - - - -### `storeUserIps` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$storeUserIps](craft4:craft\config\GeneralConfig::$storeUserIps) - -Since -: 3.1.0 - -
- -Whether user IP addresses should be stored/logged by the system. - -::: code -```php Static Config -->storeUserIps(true) -``` -```shell Environment Override -CRAFT_STORE_USER_IPS=1 -``` -::: - - - -### `trustedHosts` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[ - 'any', -]` - -Defined by -: [GeneralConfig::$trustedHosts](craft4:craft\config\GeneralConfig::$trustedHosts) - -
- -The configuration for trusted security-related headers. - -See [yii\web\Request::$trustedHosts](https://www.yiiframework.com/doc/api/2.0/yii-web-request#$trustedHosts-detail) for more details. - -By default, all hosts are trusted. - -::: code -```php Static Config -->trustedHosts(['trusted-one.foo', 'trusted-two.foo']) -``` -```shell Environment Override -CRAFT_TRUSTED_HOSTS=trusted-one.foo,trusted-two.foo -``` -::: - - - -### `useSecureCookies` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean), [string](https://php.net/language.types.string) - -Default value -: `'auto'` - -Defined by -: [GeneralConfig::$useSecureCookies](craft4:craft\config\GeneralConfig::$useSecureCookies) - -
- -Whether Craft will set the “secure” flag when saving cookies when using `Craft::cookieConfig()` to create a cookie. - -Valid values are `true`, `false`, and `'auto'`. Defaults to `'auto'`, which will set the secure flag if the page you’re currently accessing -is over `https://`. `true` will always set the flag, regardless of protocol and `false` will never automatically set the flag. - -::: code -```php Static Config -->useSecureCookies(true) -``` -```shell Environment Override -CRAFT_USE_SECURE_COOKIES=1 -``` -::: - - - -### `verificationCodeDuration` - -
- -Allowed types -: `mixed` - -Default value -: `86400` (1 day) - -Defined by -: [GeneralConfig::$verificationCodeDuration](craft4:craft\config\GeneralConfig::$verificationCodeDuration) - -
- -The amount of time a user verification code can be used before expiring. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -// 1 hour -->verificationCodeDuration(3600) -``` -```shell Environment Override -# 1 hour -CRAFT_VERIFICATION_CODE_DURATION=3600 -``` -::: - - - -## Assets - -### `allowedFileExtensions` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[ - '7z', - 'aiff', - 'asc', - 'asf', - 'avi', - 'avif', - 'bmp', - 'cap', - 'cin', - 'csv', - 'dfxp', - 'doc', - 'docx', - 'dotm', - 'dotx', - 'fla', - 'flv', - 'gif', - 'gz', - 'gzip', - 'heic', - 'heif', - 'hevc', - 'itt', - 'jp2', - 'jpeg', - 'jpg', - 'jpx', - 'js', - 'json', - 'lrc', - 'm2t', - 'm4a', - 'm4v', - 'mcc', - 'mid', - 'mov', - 'mp3', - 'mp4', - 'mpc', - 'mpeg', - 'mpg', - 'mpsub', - 'ods', - 'odt', - 'ogg', - 'ogv', - 'pdf', - 'png', - 'potx', - 'pps', - 'ppsm', - 'ppsx', - 'ppt', - 'pptm', - 'pptx', - 'ppz', - 'pxd', - 'qt', - 'ram', - 'rar', - 'rm', - 'rmi', - 'rmvb', - 'rt', - 'rtf', - 'sami', - 'sbv', - 'scc', - 'sdc', - 'sitd', - 'smi', - 'srt', - 'stl', - 'sub', - 'svg', - 'swf', - 'sxc', - 'sxw', - 'tar', - 'tds', - 'tgz', - 'tif', - 'tiff', - 'ttml', - 'txt', - 'vob', - 'vsd', - 'vtt', - 'wav', - 'webm', - 'webp', - 'wma', - 'wmv', - 'xls', - 'xlsx', - 'zip', -]` - -Defined by -: [GeneralConfig::$allowedFileExtensions](craft4:craft\config\GeneralConfig::$allowedFileExtensions) - -
- -The file extensions Craft should allow when a user is uploading files. - -```php Static Config -// Nothing bug GIFs! -->allowedFileExtensions([ - 'gif', -]) -``` - - - -### `convertFilenamesToAscii` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$convertFilenamesToAscii](craft4:craft\config\GeneralConfig::$convertFilenamesToAscii) - -
- -Whether uploaded filenames with non-ASCII characters should be converted to ASCII (i.e. `ñ` → `n`). - -::: tip -You can run `php craft utils/ascii-filenames` in your terminal to apply ASCII filenames to all existing assets. -::: - -::: code -```php Static Config -->convertFilenamesToAscii(false) -``` -```shell Environment Override -CRAFT_CONVERT_FILENAMES_TO_ASCII=false -``` -::: - - - -### `extraFileKinds` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[]` - -Defined by -: [GeneralConfig::$extraFileKinds](craft4:craft\config\GeneralConfig::$extraFileKinds) - -Since -: 3.0.37 - -
- -List of additional file kinds Craft should support. This array will get merged with the one defined in -`\craft\helpers\Assets::_buildFileKinds()`. - -```php Static Config -->extraFileKinds([ - // merge .psb into list of Photoshop file kinds - 'photoshop' => [ - 'extensions' => ['psb'], - ], - // register new "Stylesheet" file kind - 'stylesheet' => [ - 'label' => 'Stylesheet', - 'extensions' => ['css', 'less', 'pcss', 'sass', 'scss', 'styl'], - ], -]) -``` - -::: tip -File extensions listed here won’t immediately be allowed to be uploaded. You will also need to list them with -the config setting. -::: - - - -### `filenameWordSeparator` - -
- -Allowed types -: [string](https://php.net/language.types.string), [false](https://php.net/language.types.boolean) - -Default value -: `'-'` - -Defined by -: [GeneralConfig::$filenameWordSeparator](craft4:craft\config\GeneralConfig::$filenameWordSeparator) - -
- -The string to use to separate words when uploading assets. If set to `false`, spaces will be left alone. - -::: code -```php Static Config -->filenameWordSeparator(false) -``` -```shell Environment Override -CRAFT_FILENAME_WORD_SEPARATOR=false -``` -::: - - - -### `maxUploadFileSize` - -
- -Allowed types -: [integer](https://php.net/language.types.integer), [string](https://php.net/language.types.string) - -Default value -: `16777216` (16MB) - -Defined by -: [GeneralConfig::$maxUploadFileSize](craft4:craft\config\GeneralConfig::$maxUploadFileSize) - -
- -The maximum upload file size allowed. - -See [craft\helpers\ConfigHelper::sizeInBytes()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-sizeinbytes) for a list of supported value types. - -::: code -```php Static Config -// 25MB -->maxUploadFileSize(26214400) -``` -```shell Environment Override -# 25MB -CRAFT_MAX_UPLOAD_FILE_SIZE=26214400 -``` -::: - - - -### `revAssetUrls` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$revAssetUrls](craft4:craft\config\GeneralConfig::$revAssetUrls) - -Since -: 3.7.0 - -
- -Whether asset URLs should be revved so browsers don’t load cached versions when they’re modified. - -::: code -```php Static Config -->revAssetUrls(true) -``` -```shell Environment Override -CRAFT_REV_ASSET_URLS=1 -``` -::: - - - -## Image Handling - -### `brokenImagePath` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [GeneralConfig::$brokenImagePath](craft4:craft\config\GeneralConfig::$brokenImagePath) - -Since -: 3.5.0 - -
- -The server path to an image file that should be sent when responding to an image request with a -404 status code. - -This can be set to an aliased path such as `@webroot/assets/404.svg`. - -::: code -```php Static Config -->brokenImagePath('@webroot/assets/404.svg') -``` -```shell Environment Override -CRAFT_BROKEN_IMAGE_PATH=@webroot/assets/404.svg -``` -::: - - - -### `defaultImageQuality` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `82` - -Defined by -: [GeneralConfig::$defaultImageQuality](craft4:craft\config\GeneralConfig::$defaultImageQuality) - -
- -The quality level Craft will use when saving JPG and PNG files. Ranges from 1 (worst quality, smallest file) to -100 (best quality, biggest file). - -::: code -```php Static Config -->defaultImageQuality(90) -``` -```shell Environment Override -CRAFT_DEFAULT_IMAGE_QUALITY=90 -``` -::: - - - -### `generateTransformsBeforePageLoad` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$generateTransformsBeforePageLoad](craft4:craft\config\GeneralConfig::$generateTransformsBeforePageLoad) - -
- -Whether image transforms should be generated before page load. - -::: code -```php Static Config -->generateTransformsBeforePageLoad(true) -``` -```shell Environment Override -CRAFT_GENERATE_TRANSFORMS_BEFORE_PAGE_LOAD=1 -``` -::: - - - -### `imageDriver` - -
- -Allowed types -: `mixed` - -Default value -: `GeneralConfig::IMAGE_DRIVER_AUTO` - -Defined by -: [GeneralConfig::$imageDriver](craft4:craft\config\GeneralConfig::$imageDriver) - -
- -The image driver Craft should use to cleanse and transform images. By default Craft will use ImageMagick if it’s installed -and otherwise fall back to GD. You can explicitly set either `'imagick'` or `'gd'` here to override that behavior. - -::: code -```php Static Config -->imageDriver('imagick') -``` -```shell Environment Override -CRAFT_IMAGE_DRIVER=imagick -``` -::: - - - -### `imageEditorRatios` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `[ - 'Unconstrained' => 'none', - 'Original' => 'original', - 'Square' => 1, - '16:9' => 1.78, - '10:8' => 1.25, - '7:5' => 1.4, - '4:3' => 1.33, - '5:3' => 1.67, - '3:2' => 1.5, -]` - -Defined by -: [GeneralConfig::$imageEditorRatios](craft4:craft\config\GeneralConfig::$imageEditorRatios) - -
- -An array containing the selectable image aspect ratios for the image editor. The array must be in the format -of `label` => `ratio`, where ratio must be a float or a string. For string values, only values of “none” and “original” are allowed. - -```php Static Config -->imageEditorRatios([ - 'Unconstrained' => 'none', - 'Original' => 'original', - 'Square' => 1, - 'IMAX' => 1.9, - 'Widescreen' => 1.78, -]) -``` - - - -### `maxCachedCloudImageSize` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `2000` - -Defined by -: [GeneralConfig::$maxCachedCloudImageSize](craft4:craft\config\GeneralConfig::$maxCachedCloudImageSize) - -
- -The maximum dimension size to use when caching images from external sources to use in transforms. Set to `0` to never cache them. - -::: code -```php Static Config -->maxCachedCloudImageSize(0) -``` -```shell Environment Override -CRAFT_MAX_CACHED_CLOUD_IMAGE_SIZE=0 -``` -::: - - - -### `optimizeImageFilesize` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$optimizeImageFilesize](craft4:craft\config\GeneralConfig::$optimizeImageFilesize) - -
- -Whether Craft should optimize images for reduced file sizes without noticeably reducing image quality. (Only supported when -ImageMagick is used.) - -::: code -```php Static Config -->optimizeImageFilesize(false) -``` -```shell Environment Override -CRAFT_OPTIMIZE_IMAGE_FILESIZE=1 -``` -::: - - - -### `preserveCmykColorspace` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$preserveCmykColorspace](craft4:craft\config\GeneralConfig::$preserveCmykColorspace) - -Since -: 3.0.8 - -
- -Whether CMYK should be preserved as the colorspace when manipulating images. - -Setting this to `true` will prevent Craft from transforming CMYK images to sRGB, but on some ImageMagick versions it can cause -image color distortion. This will only have an effect if ImageMagick is in use. - -::: code -```php Static Config -->preserveCmykColorspace(true) -``` -```shell Environment Override -CRAFT_PRESERVE_CMYK_COLORSPACE=1 -``` -::: - - - -### `preserveExifData` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$preserveExifData](craft4:craft\config\GeneralConfig::$preserveExifData) - -
- -Whether the EXIF data should be preserved when manipulating and uploading images. - -Setting this to `true` will result in larger image file sizes. - -This will only have effect if ImageMagick is in use. - -::: code -```php Static Config -->preserveExifData(true) -``` -```shell Environment Override -CRAFT_PRESERVE_EXIF_DATA=1 -``` -::: - - - -### `preserveImageColorProfiles` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$preserveImageColorProfiles](craft4:craft\config\GeneralConfig::$preserveImageColorProfiles) - -
- -Whether the embedded Image Color Profile (ICC) should be preserved when manipulating images. - -Setting this to `false` will reduce the image size a little bit, but on some ImageMagick versions can cause images to be saved with -an incorrect gamma value, which causes the images to become very dark. This will only have effect if ImageMagick is in use. - -::: code -```php Static Config -->preserveImageColorProfiles(false) -``` -```shell Environment Override -CRAFT_PRESERVE_IMAGE_COLOR_PROFILES=false -``` -::: - - - -### `rasterizeSvgThumbs` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$rasterizeSvgThumbs](craft4:craft\config\GeneralConfig::$rasterizeSvgThumbs) - -Since -: 3.6.0 - -
- -Whether SVG thumbnails should be rasterized. - -This will only work if ImageMagick is installed, and is set to either `auto` or `imagick`. - -::: code -```php Static Config -->rasterizeSvgThumbs(true) -``` -```shell Environment Override -CRAFT_RASTERIZE_SVG_THUMBS=1 -``` -::: - - - -### `rotateImagesOnUploadByExifData` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$rotateImagesOnUploadByExifData](craft4:craft\config\GeneralConfig::$rotateImagesOnUploadByExifData) - -
- -Whether Craft should rotate images according to their EXIF data on upload. - -::: code -```php Static Config -->rotateImagesOnUploadByExifData(false) -``` -```shell Environment Override -CRAFT_ROTATE_IMAGES_ON_UPLOAD_BY_EXIF_DATA=false -``` -::: - - - -### `transformGifs` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$transformGifs](craft4:craft\config\GeneralConfig::$transformGifs) - -Since -: 3.0.7 - -
- -Whether GIF files should be cleansed/transformed. - -::: code -```php Static Config -->transformGifs(false) -``` -```shell Environment Override -CRAFT_TRANSFORM_GIFS=false -``` -::: - - - -### `transformSvgs` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$transformSvgs](craft4:craft\config\GeneralConfig::$transformSvgs) - -Since -: 3.7.1 - -
- -Whether SVG files should be transformed. - -::: code -```php Static Config -->transformSvgs(false) -``` -```shell Environment Override -CRAFT_TRANSFORM_SVGS=false -``` -::: - - - -### `upscaleImages` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$upscaleImages](craft4:craft\config\GeneralConfig::$upscaleImages) - -Since -: 3.4.0 - -
- -Whether image transforms should allow upscaling by default, for images that are smaller than the transform dimensions. - -::: code -```php Static Config -->upscaleImages(false) -``` -```shell Environment Override -CRAFT_UPSCALE_IMAGES=false -``` -::: - - - -## GraphQL - -### `allowedGraphqlOrigins` - -
- -Allowed types -: [string](https://php.net/language.types.string)[], [null](https://php.net/language.types.null), [false](https://php.net/language.types.boolean) - -Default value -: `null` - -Defined by -: [GeneralConfig::$allowedGraphqlOrigins](craft4:craft\config\GeneralConfig::$allowedGraphqlOrigins) - -Since -: 3.5.0 - -
- -The Ajax origins that should be allowed to access the GraphQL API, if enabled. - -If this is set to an array, then `graphql/api` requests will only include the current request’s [origin](https://www.yiiframework.com/doc/api/2.0/yii-web-request#getOrigin()-detail) -in the `Access-Control-Allow-Origin` response header if it’s listed here. - -If this is set to `false`, then the `Access-Control-Allow-Origin` response header will never be sent. - -::: code -```php Static Config -->allowedGraphqlOrigins(false) -``` -```shell Environment Override -CRAFT_ALLOW_GRAPHQL_ORIGINS=false -``` -::: - - - -### `disableGraphqlTransformDirective` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$disableGraphqlTransformDirective](craft4:craft\config\GeneralConfig::$disableGraphqlTransformDirective) - -Since -: 3.6.0 - -
- -Whether the `transform` directive should be disabled for the GraphQL API. - -::: code -```php Static Config -->disableGraphqlTransformDirective(true) -``` -```shell Environment Override -CRAFT_DISABLE_GRAPHQL_TRANSFORM_DIRECTIVE=1 -``` -::: - - - -### `enableGql` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableGql](craft4:craft\config\GeneralConfig::$enableGql) - -Since -: 3.3.1 - -
- -Whether the GraphQL API should be enabled. - -The GraphQL API is only available for Craft Pro. - -::: code -```php Static Config -->enableGql(false) -``` -```shell Environment Override -CRAFT_ENABLE_GQL=false -``` -::: - - - -### `enableGraphqlCaching` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableGraphqlCaching](craft4:craft\config\GeneralConfig::$enableGraphqlCaching) - -Since -: 3.3.12 - -
- -Whether Craft should cache GraphQL queries. - -If set to `true`, Craft will cache the results for unique GraphQL queries per access token. The cache is automatically invalidated any time -an element is saved, the site structure is updated, or a GraphQL schema is saved. - -This setting will have no effect if a plugin is using the [craft\services\Gql::EVENT_BEFORE_EXECUTE_GQL_QUERY](https://docs.craftcms.com/api/v3/craft-services-gql.html#event-before-execute-gql-query) event to provide its own -caching logic and setting the `result` property. - -::: code -```php Static Config -->enableGraphqlCaching(false) -``` -```shell Environment Override -CRAFT_ENABLE_GRAPHQL_CACHING=false -``` -::: - - - -### `enableGraphqlIntrospection` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$enableGraphqlIntrospection](craft4:craft\config\GeneralConfig::$enableGraphqlIntrospection) - -Since -: 3.6.0 - -
- -Whether GraphQL introspection queries are allowed. Defaults to `true` and is always allowed in the control panel. - -::: code -```php Static Config -->enableGraphqlIntrospection(false) -``` -```shell Environment Override -CRAFT_ENABLE_GRAPHQL_INTROSPECTION=false -``` -::: - - - -### `gqlTypePrefix` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [GeneralConfig::$gqlTypePrefix](craft4:craft\config\GeneralConfig::$gqlTypePrefix) - -
- -Prefix to use for all type names returned by GraphQL. - -::: code -```php Static Config -->gqlTypePrefix('craft_') -``` -```shell Environment Override -CRAFT_GQL_TYPE_PREFIX=craft_ -``` -::: - - - -### `maxGraphqlComplexity` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `0` - -Defined by -: [GeneralConfig::$maxGraphqlComplexity](craft4:craft\config\GeneralConfig::$maxGraphqlComplexity) - -
- -The maximum allowed complexity a GraphQL query is allowed to have. Set to `0` to allow any complexity. - - - -### `maxGraphqlDepth` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `0` - -Defined by -: [GeneralConfig::$maxGraphqlDepth](craft4:craft\config\GeneralConfig::$maxGraphqlDepth) - -Since -: 3.6.0 - -
- -The maximum allowed depth a GraphQL query is allowed to reach. Set to `0` to allow any depth. - -::: code -```php Static Config -->maxGraphqlDepth(5) -``` -```shell Environment Override -CRAFT_MAX_GRAPHQL_DEPTH=5 -``` -::: - - - -### `maxGraphqlResults` - -
- -Allowed types -: [integer](https://php.net/language.types.integer) - -Default value -: `0` - -Defined by -: [GeneralConfig::$maxGraphqlResults](craft4:craft\config\GeneralConfig::$maxGraphqlResults) - -Since -: 3.6.0 - -
- -The maximum allowed results for a single GraphQL query. Set to `0` to disable any limits. - -::: code -```php Static Config -->maxGraphqlResults(100) -``` -```shell Environment Override -CRAFT_MAX_GRAPHQL_RESULTS=100 -``` -::: - - - -### `prefixGqlRootTypes` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [GeneralConfig::$prefixGqlRootTypes](craft4:craft\config\GeneralConfig::$prefixGqlRootTypes) - -Since -: 3.6.6 - -
- -Whether the config setting should have an impact on `query`, `mutation`, and `subscription` types. - -::: code -```php Static Config -->prefixGqlRootTypes(false) -``` -```shell Environment Override -CRAFT_PREFIX_GQL_ROOT_TYPES=false -``` -::: - - - -### `setGraphqlDatesToSystemTimeZone` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [GeneralConfig::$setGraphqlDatesToSystemTimeZone](craft4:craft\config\GeneralConfig::$setGraphqlDatesToSystemTimeZone) - -Since -: 3.7.0 - -
- -Whether dates returned by the GraphQL API should be set to the system time zone by default, rather than UTC. - -::: code -```php Static Config -->setGraphqlDatesToSystemTimeZone(true) -``` -```shell Environment Override -CRAFT_SET_GRAPHQL_DATES_TO_SYSTEM_TIMEZONE=1 -``` -::: - - - -## Garbage Collection - -### `purgePendingUsersDuration` - -
- -Allowed types -: `mixed` - -Default value -: `0` - -Defined by -: [GeneralConfig::$purgePendingUsersDuration](craft4:craft\config\GeneralConfig::$purgePendingUsersDuration) - -
- -The amount of time to wait before Craft purges pending users from the system that have not activated. - -Any content assigned to a pending user will be deleted as well when the given time interval passes. - -Set to `0` to disable this feature. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: tip -Users will only be purged when [garbage collection](https://craftcms.com/docs/4.x/gc.html) is run. -::: - -::: code -```php Static Config -// 2 weeks -->purgePendingUsersDuration(1209600) -``` -```shell Environment Override -# 2 weeks -CRAFT_PURGE_PENDING_USERS_DURATION=1209600 -``` -::: - - - -### `purgeStaleUserSessionDuration` - -
- -Allowed types -: `mixed` - -Default value -: `7776000` (90 days) - -Defined by -: [GeneralConfig::$purgeStaleUserSessionDuration](craft4:craft\config\GeneralConfig::$purgeStaleUserSessionDuration) - -Since -: 3.3.0 - -
- -The amount of time to wait before Craft purges stale user sessions from the sessions table in the database. - -Set to `0` to disable this feature. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -// 1 week -->purgeStaleUserSessionDuration(604800) -``` -```shell Environment Override -# 1 week -CRAFT_PURGE_STALE_USER_SESSION_DURATION=604800 -``` -::: - - - -### `purgeUnsavedDraftsDuration` - -
- -Allowed types -: `mixed` - -Default value -: `2592000` (30 days) - -Defined by -: [GeneralConfig::$purgeUnsavedDraftsDuration](craft4:craft\config\GeneralConfig::$purgeUnsavedDraftsDuration) - -Since -: 3.2.0 - -
- -The amount of time to wait before Craft purges unpublished drafts that were never updated with content. - -Set to `0` to disable this feature. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -->purgeUnsavedDraftsDuration(0) -``` -```shell Environment Override -CRAFT_PURGE_UNSAVED_DRAFTS_DURATION=0 -``` -::: - - - -### `softDeleteDuration` - -
- -Allowed types -: `mixed` - -Default value -: `2592000` (30 days) - -Defined by -: [GeneralConfig::$softDeleteDuration](craft4:craft\config\GeneralConfig::$softDeleteDuration) - -Since -: 3.1.0 - -
- -The amount of time before a soft-deleted item will be up for hard-deletion by garbage collection. - -Set to `0` if you don’t ever want to delete soft-deleted items. - -See [craft\helpers\ConfigHelper::durationInSeconds()](https://docs.craftcms.com/api/v3/craft-helpers-confighelper.html#method-durationinseconds) for a list of supported value types. - -::: code -```php Static Config -->softDeleteDuration(0) -``` -```shell Environment Override -CRAFT_SOFT_DELETE_DURATION=0 -``` -::: - - - -## Users - -### `extraLastNamePrefixes` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[]` - -Defined by -: [GeneralConfig::$extraLastNamePrefixes](craft4:craft\config\GeneralConfig::$extraLastNamePrefixes) - -Since -: 4.3.0 - -
- -Any additional last name prefixes that should be supported by the name parser. - -::: code -```php Static Config -->extraLastNamePrefixes(['Dal', 'Van Der']) -``` -```shell Environment Override -CRAFT_EXTRA_LAST_NAME_PREFIXES="Dal,Van Der" -``` -::: - - - -### `extraNameSalutations` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[]` - -Defined by -: [GeneralConfig::$extraNameSalutations](craft4:craft\config\GeneralConfig::$extraNameSalutations) - -Since -: 4.3.0 - -
- -Any additional name salutations that should be supported by the name parser. - -::: code -```php Static Config -->extraNameSalutations(['Lady', 'Sire']) -``` -```shell Environment Override -CRAFT_EXTRA_NAME_SALUTATIONS=Lady,Sire -``` -::: - - - -### `extraNameSuffixes` - -
- -Allowed types -: [string](https://php.net/language.types.string)[] - -Default value -: `[]` - -Defined by -: [GeneralConfig::$extraNameSuffixes](craft4:craft\config\GeneralConfig::$extraNameSuffixes) - -Since -: 4.3.0 - -
- -Any additional name suffixes that should be supported by the name parser. - -::: code -```php Static Config -->extraNameSuffixes(['CCNA', 'OBE']) -``` -```shell Environment Override -CRAFT_EXTRA_NAME_SUFFIXES=CCNA,OBE -``` -::: - - - - - + +!!!include(docs/.artifacts/cms/4.x/config-general.md)!!! diff --git a/docs/4.x/console-commands.md b/docs/4.x/console-commands.md index c28edff0c..adf215c4b 100644 --- a/docs/4.x/console-commands.md +++ b/docs/4.x/console-commands.md @@ -1,5 +1,6 @@ --- keywords: cli +containsGeneratedContent: yes --- # Console Commands @@ -69,3025 +70,5 @@ All commands support the following options: `--silent-exit-on-exception` : Force a nominal exit code (`0`), even if an exception occurred. Useful when inconsequential failures would otherwise block chained commands in automated environments. - - - -## `cache` - -Allows you to flush caches. - -

- # - cache/flush -

- - -Flushes given cache components. - -Example: - -```sh -# flushes caches by ID: “first”, “second”, “third” -php craft cache/flush first second third -``` - -

- # - cache/flush-all -

- - -Flushes all caches registered in the system. - -

- # - cache/flush-schema -

- - -Clears DB schema cache for a given connection component. - -```sh -php craft cache/flush-schema -# identical to `php craft cache/flush-schema db` -``` - -

Parameters

- -componentId -: ID of the connection component. (Defaults to `db`.) - - - -

- # - cache -

- - -Lists the caches that can be flushed. - -## `clear-caches` - -Allows you to clear various Craft caches. - -

- # - clear-caches/all -

- - -Clear all caches. - -

- # - clear-caches/asset -

- - -Clears Asset caches. - -

- # - clear-caches/asset-indexing-data -

- - -Clears Asset indexing data. - -

- # - clear-caches/compiled-classes -

- - -Clears compiled classes. - -

- # - clear-caches/compiled-templates -

- - -Clears compiled templates. - -

- # - clear-caches/cp-resources -

- - -Clears control panel resources. - -

- # - clear-caches/data -

- - -Clears data caches. - -

- # - clear-caches -

- - -Lists the caches that can be cleared. - -

- # - clear-caches/temp-files -

- - -Clears temporary files. - -

- # - clear-caches/transform-indexes -

- - -Clears the Asset transform index. - -## `clear-deprecations` - - -

- # - clear-deprecations -

- - -Clears all deprecation warnings. - -## `db` - -Performs database operations. - -

- # - db/backup -

- - -Creates a new database backup. - -Example: -``` -php craft db/backup ./my-backups/ -``` - -

Parameters

- -path -: The path the database backup should be created at. -Can be any of the following: - - - A full file path - - A folder path (backup will be saved in there with a dynamically-generated name) - - A filename (backup will be saved in the working directory with the given name) - - Blank (backup will be saved to the `storage/backups/` folder with a dynamically-generated name) - - - -

Options

- - ---zip -: Whether the backup should be saved as a zip file. - - ---overwrite -: Whether to overwrite an existing backup file, if a specific file path is given. - - - -

- # - db/convert-charset -

- - -Converts tables’ character sets and collations. (MySQL only) - -Example: -``` -php craft db/convert-charset utf8 utf8_unicode_ci -``` - -

Parameters

- -charset -: The target character set, which honors `DbConfig::$charset` - or defaults to `utf8`. - -collation -: The target collation, which honors `DbConfig::$collation` - or defaults to `utf8_unicode_ci`. - - - -

- # - db/drop-all-tables -

- - -Drops all tables in the database. - -Example: -``` -php craft db/drop-all-tables -``` - -

- # - db/restore -

- - -Restores a database backup. - -Example: -``` -php craft db/restore ./my-backup.sql -``` - -

Parameters

- -path -: The path to the database backup file. - - - -

Options

- - ---drop-all-tables -: Whether to drop all preexisting tables in the database prior to restoring the backup. - - - -## `elements` - -Manages elements. - -

- # - elements/delete -

- - -Deletes an element by its ID. - -

Parameters

- -id -: The element ID to delete. - - - -

Options

- - ---hard -: Whether the element should be hard-deleted. - - - -

- # - elements/restore -

- - -Restores an element by its ID. - -

Parameters

- -id -: The element ID to restore. - - - -## `entrify` - -Converts categories, tags, and global sets to entries. - -

- # - entrify/categories -

- - -Converts categories to entries. - -

Parameters

- -categoryGroup -: The category group handle - - - -

Options

- - ---section -: The section handle that entries should be saved in - - ---entry-type -: The entry type handle that entries should have - - ---author -: The author username or email that entries should have - - - -

- # - entrify/global-set -

- - -Converts a global set to a Single section. - -

Parameters

- -globalSet -: The global set handle - - - -

Options

- - ---section -: The section handle that entries should be saved in - - - -

- # - entrify/tags -

- - -Converts tags to entries. - -

Parameters

- -tagGroup -: The tag group handle - - - -

Options

- - ---section -: The section handle that entries should be saved in - - ---entry-type -: The entry type handle that entries should have - - ---author -: The author username or email that entries should have - - - -## `exec` - - -

- # - exec/exec -

- - -Executes a PHP statement and outputs the result. - -

Parameters

- -command -: - - - -## `fixture` - -Allows you to manage test fixtures. - -

- # - fixture/load -

- - -Loads the specified fixture data. - -Example: - -```sh -# load User fixture data (any existing fixture data will be removed first) -php craft fixture/load "User" - -# load all available fixtures found under 'tests\unit\fixtures' -php craft fixture/load "*" - -# load all fixtures except User -php craft fixture/load "*, -User" -``` - -

Parameters

- -fixturesInput -: Array of fixtures to load. - - - -

Options

- - ---global-fixtures, -g -: Array of global fixtures that should be applied when loading and unloading. Set to `InitDbFixture` by default, which disables and enables integrity check so your data can be safely loaded. - - ---namespace, -n -: Namespace to search for fixtures. Defaults to `tests\unit\fixtures`. - - - -

- # - fixture/unload -

- - -Unloads the specified fixtures. - -Example: - -```sh -# unload User fixture data -php craft fixture/load "User" - -# unload all fixtures found under 'tests\unit\fixtures' -php craft fixture/load "*" - -# unload all fixtures except User -php craft fixture/load "*, -User" -``` - -

Parameters

- -fixturesInput -: Array of fixtures to unload. - - - -

Options

- - ---global-fixtures, -g -: Array of global fixtures that should be applied when loading and unloading. Set to `InitDbFixture` by default, which disables and enables integrity check so your data can be safely loaded. - - ---namespace, -n -: Namespace to search for fixtures. Defaults to `tests\unit\fixtures`. - - - -## `gc` - - -

- # - gc/run -

- - -Runs garbage collection. - -

Options

- - ---delete-all-trashed -: Whether all soft-deleted items should be deleted, rather than just -the ones that were deleted long enough ago to be ready for hard-deletion -per the `softDeleteDuration` config setting. - - - -## `graphql` - -Allows you to manage GraphQL schemas. - -

- # - graphql/create-token -

- - -Creates a new authorization token for a schema. - -

Parameters

- -schemaUid -: The schema UUID - - - -

Options

- - ---name -: The schema name - - ---expiry -: Expiry date - - - -

- # - graphql/dump-schema -

- - -Dumps a given GraphQL schema to a file. - -

Options

- - ---schema -: The GraphQL schema UUID. - - ---token -: The token to look up to determine the appropriate GraphQL schema. - - ---full-schema -: Whether full schema should be printed or dumped. - - - -

- # - graphql/list-schemas -

- - -Lists all GraphQL schemas. - -

- # - graphql/print-schema -

- - -Prints a given GraphQL schema. - -

Options

- - ---schema -: The GraphQL schema UUID. - - ---token -: The token to look up to determine the appropriate GraphQL schema. - - ---full-schema -: Whether full schema should be printed or dumped. - - - -## `help` - -Provides help information about console commands. - -

- # - help -

- - -Displays available commands or the detailed information -about a particular command. - -Example: - -``` -$ php craft help db/backup - -DESCRIPTION - -Creates a new database backup. - -Example: -php craft db/backup ./my-backups/ - - -USAGE - -craft db/backup [path] [...options...] - -- path: string - The path the database backup should be created at. - Can be any of the following: - - - A full file path - - A folder path (backup will be saved in there with a dynamically-generated name) - - A filename (backup will be saved in the working directory with the given name) - - Blank (backup will be saved to the `storage/backups/` folder with a dynamically-generated name) - - -OPTIONS - ---appconfig: string - custom application configuration file path. - If not set, default application configuration is used. - ---color: boolean, 0 or 1 - whether to enable ANSI color in the output. - If not set, ANSI color will only be enabled for terminals that support it. - ---help, -h: boolean, 0 or 1 (defaults to 0) - whether to display help information about current command. - ---interactive: boolean, 0 or 1 (defaults to 1) - whether to run the command interactively. - ---overwrite: boolean, 0 or 1 (defaults to 0) - Whether to overwrite an existing backup file, if a specific file path is given. - ---silent-exit-on-exception: boolean, 0 or 1 - if true - script finish with `ExitCode::OK` in case of exception. - false - `ExitCode::UNSPECIFIED_ERROR`. - Default: `YII_ENV_TEST` - ---zip: boolean, 0 or 1 (defaults to 0) - Whether the backup should be saved as a zip file. - -$ -``` - - -

Parameters

- -command -: The name of the command to show help about. -If not provided, all available commands will be displayed. - - - -

Options

- - ---as-json, -j -: Should the commands help be returned in JSON format? - - - -

- # - help/list -

- - -Lists all available controllers and actions in machine-readable format. - -

- # - help/list-action-options -

- - -List all available options for `action` in machine-readable format. - -

Parameters

- -action -: Route to action. - - - -

- # - help/usage -

- - -Displays usage information for `action`. - -

Parameters

- -action -: Route to action. - - - -## `index-assets` - -Allows you to re-index assets in volumes. - -

- # - index-assets/all -

- - -Re-indexes assets across all volumes. - -

Options

- - ---cache-remote-images -: Whether remote-stored images should be locally cached in the process. - - ---create-missing-assets -: Whether to auto-create new asset records when missing. - - ---delete-missing-assets -: Whether to delete all the asset records that have their files missing. - - - -

- # - index-assets/cleanup -

- - -Removes all CLI indexing sessions. - -

Options

- - ---cache-remote-images -: Whether remote-stored images should be locally cached in the process. - - ---create-missing-assets -: Whether to auto-create new asset records when missing. - - ---delete-missing-assets -: Whether to delete all the asset records that have their files missing. - - - -

- # - index-assets/one -

- - -Re-indexes assets from the given volume handle. - -

Parameters

- -handle -: The handle of the volume to index. -You can optionally provide a volume sub-path, e.g. `php craft index-assets/one volume-handle/path/to/folder`. - -startAt -: Index of the asset to start with, which defaults to `0`. - - - -

Options

- - ---cache-remote-images -: Whether remote-stored images should be locally cached in the process. - - ---create-missing-assets -: Whether to auto-create new asset records when missing. - - ---delete-missing-assets -: Whether to delete all the asset records that have their files missing. - - - -## `install` - -Craft CMS CLI installer. - -

- # - install/check -

- - -Checks whether Craft is already installed. - -

- # - install/craft -

- - -Runs the install migration. - -

Options

- - ---email -: The default email address for the first user to create during install. - - ---username -: The default username for the first user to create during install. - - ---password -: The default password for the first user to create during install. - - ---site-name -: The default site name for the first site to create during install. - - ---site-url -: The default site URL for the first site to create during install. - - ---language -: The default language for the first site to create during install. - - - -## `invalidate-tags` - -Allows you to invalidate cache tags. - -

- # - invalidate-tags/all -

- - -Invalidates all cache tags. - -

- # - invalidate-tags/graphql -

- - -Invalidates all GraphQL query cache tags. - -

- # - invalidate-tags -

- - -Lists the cache tags that can be invalidated. - -

- # - invalidate-tags/template -

- - -Invalidates all template cache tags. - -## `mailer` - - -

- # - mailer/test -

- - -Tests sending an email with the current mailer settings. - -

Options

- - ---to -: Email address that should receive the test message. - - - -## `migrate` - -Manages Craft and plugin migrations. - -

- # - migrate/all -

- - -Runs all pending Craft, plugin, and content migrations. - -

Options

- - ---no-content -: Exclude pending content migrations. - - ---no-backup -: Skip backing up the database. - - - -

- # - migrate/create -

- - -Creates a new migration. - -This command creates a new migration using the available migration template. -After using this command, developers should modify the created migration -skeleton by filling up the actual migration logic. - -``` -craft migrate/create create_news_section -``` - -By default, the migration is created in the project’s `migrations/` -folder (as a “content migration”).\ -Use `--plugin=` to create a new plugin migration.\ -Use `--type=app` to create a new Craft CMS app migration. - -

Parameters

- -name -: the name of the new migration. This should only contain -letters, digits, and underscores. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - ---template-file -: The template file for generating new migrations. This can be either a path alias (e.g. `@app/migrations/template.php`) or a file path. Defaults to `vendor/craftcms/cms/src/updates/migration.php.template`. - - - -

- # - migrate/down -

- - -Downgrades Craft by reverting old migrations. - -Example: - -```sh -php craft migrate/down # revert last migration -php craft migrate/down 3 # revert last three migrations -php craft migrate/down all # revert all migrations -``` - -

Parameters

- -limit -: The number of migrations to be reverted. Defaults to `1`, meaning the last applied migration will be reverted. When value is `all`, all migrations will be reverted. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/history -

- - -Shows the list of migrations that have been applied so far. - -Example: - -```sh -php craft migrate/history # displays the last ten migrations -php craft migrate/history 5 # displays the last five migrations -php craft migrate/history all # displays the entire migration history -``` - -

Parameters

- -limit -: The maximum number of migrations to be displayed. (Defaults to `10`.) -If `all`, the whole migration history will be displayed. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/mark -

- - -Modifies the migration history to the specified version. - -No actual migration will be performed. - -```sh -php craft migrate/mark 101129_185401 # using timestamp -php craft migrate/mark m101129_185401_create_user_table # using name -php craft migrate/mark app\migrations\M101129185401CreateUser # using namespace name -php craft migrate/mark m000000_000000_base # reset entire history -``` - -

Parameters

- -version -: The version at which the migration history should be marked, which can be either the timestamp or the full name of the migration. - - Specify `m000000_000000_base` to set the migration history to a state where no migration has been applied. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/new -

- - -Shows any new migrations that have not been applied. - -Example: - -```sh -php craft migrate/new # displays the first 10 new migrations -php craft migrate/new 5 # displays the first 5 new migrations -php craft migrate/new all # displays all new migrations -``` - -

Parameters

- -limit -: The maximum number of new migrations to be displayed. (Defaults to `10`.) -If `all`, then every available new migration will be displayed. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/redo -

- - -Reapplies previous migrations by first reverting them and then applying them again. - -Example: - -```sh -php craft migrate/redo # redo the last applied migration -php craft migrate/redo 3 # redo the last three applied migrations -php craft migrate/redo all # redo all migrations -``` - -

Parameters

- -limit -: The number of migrations to be redone. Defaults to `1`, meaning the last applied migration will be redone. When `all`, every migration will be redone. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/to -

- - -Upgrades or downgrades until the specified version. - -You can downgrade versions to a past apply time by providing a UNIX timestamp or a [strtotime()](https://www.php.net/manual/en/function.strtotime.php)-parseable value. All versions applied after that specified time will then be reverted. - -Example: - -```sh -php craft migrate/to 101129_185401 # migration timestamp -php craft migrate/to m101129_185401_create_user_table # full name -php craft migrate/to 1392853618 # UNIX timestamp -php craft migrate/to "2022-02-02 02:02:02" # strtotime()-parseable -php craft migrate/to app\migrations\M101129185401CreateUser # full namespace name -``` - -

Parameters

- -version -: Either the version name or a past time value to be migrated to. This can be a timestamp, the full name of the migration, a UNIX timestamp, or a string value that can be parsed by [strotime()](https://www.php.net/manual/en/function.strtotime.php). - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -

- # - migrate/up -

- - -Upgrades Craft by applying new migrations. - -Example: -``` -php craft migrate # apply all new migrations -php craft migrate 3 # apply the first 3 new migrations -``` - -

Parameters

- -limit -: The number of new migrations to be applied. If `0`, every new migration -will be applied. - - - -

Options

- - ---track -: The migration track to work with (e.g. `craft`, `content`, `plugin:commerce`, etc.) - - Defaults to `content`, or automatically set to the plugin’s track when `--plugin` is passed. - - ---plugin, -p -: The handle of the plugin to use during migration operations, or the plugin itself. - - - -## `off` - - -

- # - off -

- - -Disables `system.live` project config value—bypassing any `allowAdminChanges` config setting -restrictions—meant for temporary use during the deployment process. - -

Options

- - ---retry -: Number of seconds the `Retry-After` HTTP header should be set to for 503 responses. - - The `retryDuration` config setting can be used to configure a *system-wide* `Retry-After` header. - - ::: warning - The `isSystemLive` config setting takes precedence over the `system.live` project config value, - so if `config/general.php` sets `isSystemLive` to `true` or `false` these `on`/`off` commands error out. - ::: - - **Example** - - Running the following takes the system offline and returns 503 responses until it’s switched on again: - - ``` - $ php craft off --retry=60 - The system is now offline. - The retry duration is now set to 60. - ``` - - - -## `on` - - -

- # - on -

- - -Turns the system on. - -Example: -``` -$ php craft on -The system is now online. -``` - -## `plugin` - -Manages plugins. - -

- # - plugin/disable -

- - -Disables a plugin. - -``` -$ php craft plugin/disable - -The following plugins are enabled: - - Handle Name Version - ------------- -------------- ------- - apple-news Apple News 3.0.0 - ckeditor CKEditor 2.0.0 - commerce Craft Commerce 4.0.0 - gatsby-helper Gatsby Helper 2.0.0 - -Choose a plugin handle to disable: ckeditor -*** disabling ckeditor -*** disabled ckeditor successfully (time: 0.003s) -``` - - -

Parameters

- -handle -: The plugin handle (omitted if --all provided). - - - -

Options

- - ---all -: Whether the action should be run for all Composer-installed plugins. - - - -

- # - plugin/enable -

- - -Enables a plugin. - -``` -$ php craft plugin/enable - -The following plugins are disabled: - - Handle Name Version - ---------- ---------- ------- - apple-news Apple News 3.0.0 - ckeditor CKEditor 2.0.0 - -Choose a plugin handle to enable: ckeditor -*** enabling ckeditor -*** enabled ckeditor successfully (time: 0.004s) -``` - - -

Parameters

- -handle -: The plugin handle (omitted if --all provided). - - - -

Options

- - ---all -: Whether the action should be run for all Composer-installed plugins. - - - -

- # - plugin/install -

- - -Installs a plugin. - -``` -$ php craft plugin/install - -The following uninstalled plugins are present: - - Handle Name Version - ------------- -------------- ------- - anchors Anchors 3.0.0 - apple-news Apple News 3.0.0 - ckeditor CKEditor 2.0.0 - commerce Craft Commerce 4.0.0 - gatsby-helper Gatsby Helper 2.0.0 - -Choose a plugin handle to install: ckeditor -*** installing ckeditor -*** installed ckeditor successfully (time: 0.496s) -``` - - -

Parameters

- -handle -: The plugin handle (omitted if --all provided). - - - -

Options

- - ---all -: Whether the action should be run for all Composer-installed plugins. - - - -

- # - plugin/list -

- - -Lists all plugins. - -``` -$ php craft plugin/list - - Name Handle Package Name Version Installed Enabled - -------------- ------------- ---------------------- ------- --------- ------- - Anchors anchors craftcms/anchors 3.0.0 Yes Yes - Apple News apple-news craftcms/apple-news 3.0.0 Yes Yes - CKEditor ckeditor craftcms/ckeditor 2.0.0 Yes Yes - Craft Commerce commerce craftcms/commerce 4.0.0 Yes Yes - Gatsby Helper gatsby-helper craftcms/gatsby-helper 2.0.0 Yes Yes -``` - - -

- # - plugin/uninstall -

- - -Uninstalls a plugin. - -``` -$ php craft plugin/uninstall - -The following plugins plugins are installed and enabled: - - Handle Name Version - ------------- -------------- ------- - anchors Anchors 3.0.0 - apple-news Apple News 3.0.0 - ckeditor CKEditor 2.0.0 - commerce Craft Commerce 4.0.0 - gatsby-helper Gatsby Helper 2.0.0 - -Choose a plugin handle to uninstall: ckeditor -*** uninstalling ckeditor -*** uninstalled ckeditor successfully (time: 0.496s) -``` - - -

Parameters

- -handle -: The plugin handle (omitted if --all provided). - - - -

Options

- - ---force -: Whether the plugin uninstallation should be forced. - - ---all -: Whether the action should be run for all Composer-installed plugins. - - - -## `project-config` - -Manages the Project Config. - -

- # - project-config/apply -

- - -Applies project config file changes. - -

Options

- - ---force -: Whether every entry change should be force-applied. - - ---quiet -: Whether to reduce the command output. - - - -

- # - project-config/diff -

- - -Outputs a diff of the pending project config YAML changes. - -

Options

- - ---invert -: Whether to treat the loaded project config as the source of truth, instead of the YAML files. - - - -

- # - project-config/export -

- - -Exports the entire project config to a single file. - -

Parameters

- -path -: The path the project config should be exported to. -Can be any of the following: - - - A full file path - - A folder path (export will be saved in there with a dynamically-generated name) - - A filename (export will be saved in the working directory with the given name) - - Blank (export will be saved in the working directly with a dynamically-generated name) - - - -

Options

- - ---external -: Whether to pull values from the project config YAML files instead of the loaded config. - - ---overwrite -: Whether to overwrite an existing export file, if a specific file path is given. - - - -

- # - project-config/get -

- - -Outputs a project config value. - -Example: -``` -php craft project-config/get system.edition -``` - -The “path” syntax used here may be composed of directory and filenames (within your `config/project` folder), YAML object keys (including UUIDs for many Craft resources), and integers (referencing numerically-indexed arrays), joined by a dot (`.`): `path.to.nested.array.0.property`. - -

Parameters

- -path -: The config item path - - - -

Options

- - ---external -: Whether to pull values from the project config YAML files instead of the loaded config. - - - -

- # - project-config/rebuild -

- - -Rebuilds the project config. - -

- # - project-config/remove -

- - -Removes a project config value. - -Example: -``` -php craft project-config/remove some.nested.key -``` - -::: danger -This should only be used when the equivalent change is not possible through the control panel or other Craft APIs. By directly modifying project config values, you are bypassing all validation and can easily destabilize configuration. -::: - -As with [set](#project-config-set), removing values only updates the root `dateModified` key when using the [`--update-timestamp` flag](#project-config-set-options). If you do not include this flag, you must run `project-config/touch` before changes will be detected or applied in other environments! - -

Parameters

- -path -: The config item path - - - -

- # - project-config/set -

- - -Sets a project config value. - -Example: -``` -php craft project-config/set some.nested.key -``` - -See [get](#project-config-get) for the accepted key formats. - -::: danger -This should only be used when the equivalent change is not possible through the control panel or other Craft APIs. By directly modifying project config values, you are bypassing all validation and can easily destabilize configuration. -::: - -Values are updated in the database *and* in your local YAML files, but the root `dateModified` project config property is only touched when using the [`--update-timestamp` flag](#project-config-set-options). If you do not update the timestamp along with the value, the change may not be detected or applied in other environments! - -

Parameters

- -path -: The config item path - -value -: The config item value as a valid YAML string - - - -

Options

- - ---force -: Whether every entry change should be force-applied. - - ---message -: A message describing the changes. - - ---update-timestamp -: Whether the `dateModified` value should be updated - - - -

- # - project-config/touch -

- - -Updates the `dateModified` value in `config/project/project.yaml`, attempting to resolve a Git conflict for it. - -

- # - project-config/write -

- - -Writes out the currently-loaded project config as YAML files to the `config/project/` folder, discarding any pending YAML changes. - -## `queue` - -Manages the queue. - -

- # - queue/exec -

- - -Executes a job. -The command is internal, and used to isolate a job execution. Manual usage is not provided. - -

Parameters

- -id -: of a message - -ttr -: time to reserve - -attempt -: number - -pid -: of a worker - - - -

Options

- - ---verbose, -v -: verbose mode of a job execute. If enabled, execute result of each job -will be printed. - - - -

- # - queue/info -

- - -Info about queue status. - -

- # - queue/listen -

- - -Listens for new jobs added to the queue and runs them. - -

Parameters

- -timeout -: The number of seconds to wait between cycles. - - - -

Options

- - ---verbose, -v -: verbose mode of a job execute. If enabled, execute result of each job -will be printed. - - ---isolate -: isolate mode. It executes a job in a child process. - - ---php-binary -: path to php interpreter that uses to run child processes. -If it is undefined, PHP_BINARY will be used. - - - -

- # - queue/release -

- - -Releases job(s) from the queue. - -Example: - -``` -php craft queue/release all -``` - -

Parameters

- -job -: The job ID to release. Pass `all` to release all jobs. - - - -

- # - queue/retry -

- - -Re-adds failed job(s) to the queue. - -

Parameters

- -job -: The job ID that should be retried, or `all` to retry all failed jobs. - - - -

- # - queue/run -

- - -Runs all jobs in the queue. - -

Options

- - ---verbose, -v -: verbose mode of a job execute. If enabled, execute result of each job -will be printed. - - ---isolate -: isolate mode. It executes a job in a child process. - - ---php-binary -: path to php interpreter that uses to run child processes. -If it is undefined, PHP_BINARY will be used. - - - -## `resave` - -Allows you to bulk-save elements. - -

- # - resave/assets -

- - -Re-saves assets. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to fetch elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---volume -: The volume handle(s) to save assets from. Can be set to multiple comma-separated volumes. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/categories -

- - -Re-saves categories. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to fetch elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---group -: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/entries -

- - -Re-saves entries. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---drafts -: Whether to resave element drafts. - - ---provisional-drafts -: Whether to resave provisional element drafts. - - ---revisions -: Whether to resave element revisions. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to fetch elements from. - - ---propagate-to -: Comma-separated site handles to propagate entries to. - - When this is set, the entry will *only* be saved for this site. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---section -: The section handle(s) to save entries from. Can be set to multiple comma-separated sections. - - ---type -: The type handle(s) of the elements to resave. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---set-enabled-for-site -: The site-enabled status that should be set on the entry, for the site it’s initially being saved/propagated to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/matrix-blocks -

- - -Re-saves Matrix blocks. - -You must supply the `--field` or `--element-id` argument for this to work properly. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to fetch elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---type -: The type handle(s) of the elements to resave. - - ---field -: The field handle to save Matrix blocks for. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/tags -

- - -Re-saves tags. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to fetch elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---group -: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -

- # - resave/users -

- - -Re-saves users. - -

Options

- - ---queue -: Whether the elements should be resaved via a queue job. - - ---element-id -: The ID(s) of the elements to resave. - - ---uid -: The UUID(s) of the elements to resave. - - ---site -: The site handle to fetch elements from. - - ---status -: The status(es) of elements to resave. Can be set to multiple comma-separated statuses. - - ---offset -: The number of elements to skip. - - ---limit -: The number of elements to resave. - - ---update-search-index -: Whether to update the search indexes for the resaved elements. - - ---touch -: Whether to update the `dateUpdated` timestamp for the elements. - - ---group -: The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups. - - ---set -: An attribute name that should be set for each of the elements. The value will be determined by --to. - - ---to -: The value that should be set on the --set attribute. - - The following value types are supported: - - An attribute name: `--to myCustomField` - - An object template: `--to "={myCustomField|lower}"` - - A raw value: `--to "=foo bar"` - - A PHP arrow function: `--to "fn(\$element) => \$element->callSomething()"` - - An empty value: `--to :empty:` - - ---if-empty -: Whether the `--set` attribute should only be set if it doesn’t have a value. - - - -## `sections` - -Manages sections. - -

- # - sections/create -

- - -Creates a section. - -

Options

- - ---from-category-group -: The category group handle to model the section from. - - ---from-tag-group -: The tag group handle to model the section from. - - ---from-global-set -: The global set handle to model the section from. - - - -

- # - sections/delete -

- - -Deletes a section. - -

Parameters

- -handle -: The section handle - - - -## `serve` - - -

- # - serve -

- - -Runs PHP built-in web server. - -

Parameters

- -address -: address to serve on. Either "host" or "host:port". - - - -

Options

- - ---docroot, -t -: path or [path alias](https://craftcms.com/docs/4.x/config/#aliases) of the directory to serve. - - ---router, -r -: - - ---port, -p -: port to serve on. - - - -## `setup` - -Craft CMS setup installer. - -

- # - setup/app-id -

- - -Generates a new application ID and saves it in the `.env` file. - -

- # - setup/cloud -

- - -Prepares the Craft install to be deployed to Craft Cloud. - -

- # - setup/db -

- - -Alias for [setup/db-creds](#setup-db-creds). - -

Options

- - ---driver -: The database driver to use. Either `'mysql'` for MySQL or `'pgsql'` for PostgreSQL. - - ---server -: The database server name or IP address. Usually `'localhost'` or `'127.0.0.1'`. - - ---port -: The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. - - ---user -: The database username to connect with. - - ---password -: The database password to connect with. - - ---database -: The name of the database to select. - - ---schema -: The schema that Postgres is configured to use by default (PostgreSQL only). - - ---table-prefix -: The table prefix to add to all database tables. This can -be no more than 5 characters, and must be all lowercase. - - - -

- # - setup/db-cache-table -

- - -Creates a database table for storing DB caches. - -

- # - setup/db-creds -

- - -Stores new DB connection settings to the `.env` file. - -

Options

- - ---driver -: The database driver to use. Either `'mysql'` for MySQL or `'pgsql'` for PostgreSQL. - - ---server -: The database server name or IP address. Usually `'localhost'` or `'127.0.0.1'`. - - ---port -: The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. - - ---user -: The database username to connect with. - - ---password -: The database password to connect with. - - ---database -: The name of the database to select. - - ---schema -: The schema that Postgres is configured to use by default (PostgreSQL only). - - ---table-prefix -: The table prefix to add to all database tables. This can -be no more than 5 characters, and must be all lowercase. - - - -

- # - setup -

- - -Sets up all the things. - -This is an interactive wrapper for the `setup/app-id`, `setup/security-key`, `setup/db-creds`, -and `install` commands, each of which support being run non-interactively. - -

- # - setup/keys -

- - -Generates an application ID and security key (if they don’t exist), and saves them in the `.env` file. - -

- # - setup/message-tables -

- - -Creates database tables for storing message translations. (EXPERIMENTAL!) - -

- # - setup/php-session-table -

- - -Creates a database table for storing PHP session information. - -

- # - setup/security-key -

- - -Generates a new security key and saves it in the `.env` file. - -

- # - setup/welcome -

- - -Called from the `post-create-project-cmd` Composer hook. - -## `shell` - - -

- # - shell -

- - -Runs an interactive shell. - -::: tip -This command requires the [`yiisoft/yii2-shell`](https://github.com/yiisoft/yii2-shell) package, which you may need to add to your project: - -``` -composer require --dev yiisoft/yii2-shell -``` -::: - -``` -$ php craft shell - -Psy Shell v0.10.12 (PHP 8.0.3 — cli) by Justin Hileman ->>> help - help Show a list of commands. Type `help [foo]` for information about [foo]. Aliases: ? - ls List local, instance or class variables, methods and constants. Aliases: dir - dump Dump an object or primitive. - doc Read the documentation for an object, class, constant, method or property. Aliases: rtfm, m - show Show the code for an object, class, constant, method or property. - wtf Show the backtrace of the most recent exception. Aliases: last-ex - whereami Show where you are in the code. - throw-up Throw an exception or error out of the Psy Shell. - timeit Profiles with a timer. - trace Show the current call stack. - buffer Show (or clear) the contents of the code input buffer. Aliases: buf - clear Clear the Psy Shell screen. - edit Open an external editor. Afterwards, get produced code in input buffer. - sudo Evaluate PHP code, bypassing visibility restrictions. - history Show the Psy Shell history. Aliases: hist - exit End the current session and return to caller. Aliases: quit, q -``` - - -

Options

- - ---include -: Include file(s) before starting tinker shell. - - - -## `tests` - - -

- # - tests/setup -

- - -Sets up a test suite for the current project. - -

Parameters

- -dst -: The folder that the test suite should be generated in. - Defaults to the current working directory. - - - -## `up` - - -

- # - up -

- - -Runs pending migrations and applies pending project config changes. - -

Options

- - ---force -: Whether to perform the action even if a mutex lock could not be acquired. - - - -## `update` - -Updates Craft and plugins. - -

- # - update/composer-install -

- - -Installs dependencies based on the current `composer.json` & `composer.lock`. - -

- # - update/info -

- - -Displays info about available updates. - -

- # - update/update -

- - -Updates Craft and/or plugins. - -

Parameters

- -handle -: The update handle (`all`, `craft`, or a plugin handle). -You can pass multiple handles separated by spaces, and you can update to a specific -version using the syntax `:`. - - - -

Options

- - ---force, -f -: Force the update if allowUpdates is disabled - - ---backup -: Backup the database before updating - - ---migrate -: Run new database migrations after completing the update - - - -## `users` - -Manages user accounts. - -

- # - users/activation-url -

- - -Generates an activation URL for a pending user. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

- # - users/create -

- - -Creates a user. - -

Options

- - ---email -: The user’s email address. - - ---username -: The user’s username. - - ---password -: The user’s new password. - - ---admin -: Whether the user should be an admin. - - ---groups -: The group handles to assign the created user to. - - ---group-ids -: The group IDs to assign the user to the created user to. - - - -

- # - users/delete -

- - -Deletes a user. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

Options

- - ---inheritor -: The email or username of the user to inherit content when deleting a user. - - ---delete-content -: Whether to delete the user’s content if no inheritor is specified. - - ---hard -: Whether the user should be hard-deleted immediately, instead of soft-deleted. - - - -

- # - users/impersonate -

- - -Generates a URL to impersonate a user. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

- # - users/list-admins -

- - -Lists admin users. - -

- # - users/logout-all -

- - -Logs all users out of the system. - -

- # - users/password-reset-url -

- - -Generates a password reset URL for a user. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

- # - users/set-password -

- - -Changes a user’s password. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -

Options

- - ---password -: The user’s new password. - - - -

- # - users/unlock -

- - -Unlocks a user's account. - -

Parameters

- -user -: The ID, username, or email address of the user account. - - - -## `utils/ascii-filenames` - - -

- # - utils/ascii-filenames -

- - -Converts all non-ASCII asset filenames to ASCII. - -## `utils/fix-element-uids` - - -

- # - utils/fix-element-uids -

- - -Ensures all elements UIDs are unique. - -## `utils/fix-field-layout-uids` - - -

- # - utils/fix-field-layout-uids -

- - -Fixes any duplicate UUIDs found within field layout components in the project config. - -## `utils/prune-provisional-drafts` - - -

- # - utils/prune-provisional-drafts -

- - -Prunes provisional drafts for elements that have more than one per user. - -

Options

- - ---dry-run -: Whether this is a dry run. - - - -## `utils/prune-revisions` - - -

- # - utils/prune-revisions -

- - -Prunes excess element revisions. - -

Options

- - ---section -: The section handle(s) to prune revisions from. Can be set to multiple comma-separated sections. - - ---max-revisions -: The maximum number of revisions an element can have. - - ---dry-run -: Whether this is a dry run. - - - -## `utils/repair` - -Repairs data. - -

- # - utils/repair/category-group-structure -

- - -Repairs structure data for a category group. - -

Parameters

- -handle -: The category group handle. - - - -

Options

- - ---dry-run -: Whether to only do a dry run of the repair process. - - - -

- # - utils/repair/project-config -

- - -Repairs double-packed associative arrays in the project config. - -

Options

- - ---dry-run -: Whether to only do a dry run of the repair process. - - - -

- # - utils/repair/section-structure -

- - -Repairs structure data for a section. - -

Parameters

- -handle -: The section handle. - - - -

Options

- - ---dry-run -: Whether to only do a dry run of the repair process. - - - -## `utils/update-usernames` - - -

- # - utils/update-usernames -

- - -Updates all users’ usernames to ensure they match their email address. - - - - + +!!!include(docs/.artifacts/cms/4.x/console-commands.md)!!! diff --git a/docs/4.x/control-panel.md b/docs/4.x/control-panel.md index e1f51a802..9914399ef 100644 --- a/docs/4.x/control-panel.md +++ b/docs/4.x/control-panel.md @@ -118,6 +118,10 @@ Access to utilities should be granted only to trusted users, especially the inno Keep in mind that any user marked as an “Admin” implicitly has access to _all_ utilities. ::: +#### Disabling Utilities + +You can disable a utility for all users with the [`disabledUtilities` config setting](config4:disabledUtilities). Refer to each [utility class](repo:craftcms/cms/tree/main/src/utilities)’s `id()` method for their handles—including those provided by plugins. + ### Settings The **Settings** screen is where you’ll configure the system and design your content model. Settings complement [configuration](./config/README.md) are typically stored in [Project Config](./project-config.md) so that you can easily deploy them to other environments. diff --git a/docs/4.x/country-fields.md b/docs/4.x/country-fields.md new file mode 100644 index 000000000..8c15625a3 --- /dev/null +++ b/docs/4.x/country-fields.md @@ -0,0 +1,84 @@ +--- +description: Select a country from the same database that powers address elements. +--- + +# Country Fields + +The **Country** field allows authors to select from a the same list of countries made available via [address](addresses.md) elements. When viewed as part of a form in the [control panel](control-panel.md), countries’ names will be localized into the user’s preferred language. + +## Settings + +This field has no configurable options. + +::: tip +You can switch other text-based fields to use the Country field type. As long as your existing field’s values are valid two-letter country codes (or empty) and the existing field +::: + +## Development + +Craft stores the field’s value as a capitalized, two-letter country code. + +```twig +{% if entry.country is not empty %} + Country code: {{ entry.country }} +{% endif %} +``` + +To get more information about the country, use the [address repository](addresses.md#address-repository) available via the address service: + +```twig +{# Load all country data: #} +{% set repo = craft.app.addresses.getCountryRepository() %} + +{# Get just the selected country: #} +{% set country = repo.get(entry.country) %} + +{# Use properties of the country model: #} +{{ country.name }} ({{ country.threeLetterCode }}) +``` + +The `country` variable in this example is an instance of [`CommerceGuys\Addressing\Country\Country`](repo:commerceguys/addressing/blob/master/src/Country/Country.php). + +### Querying by Country + +You can query for elements based on a country field’s value in a familiar way: + +```twig + +{% set letters = craft.entries + .section('letters') + .fromCountry('FR') + .toCountry('GB') + .dateSent() + .all() %} +``` + +### Front-end Forms + +Update the value of a country field on an element by submitting a two-letter country code to the [`entries/save-entry` action](dev/controller-actions.md#post-entries-save-entry). Supposing we are in a template used by the “Letters” section from the previous example, our form might look something like this: + +```twig +{% set countries = craft.app.addresses.getCountryRepository().getAll() %} + +
+ {{ csrfInput() }} + {{ actionInput('entries/save-entry') }} + {{ hiddenInput('canonicalId', entry.id) }} + + {{ input('text', 'title', entry.title) }} + + + + +
+``` + + diff --git a/docs/4.x/deployment.md b/docs/4.x/deployment.md index b7193f96c..38dd09018 100644 --- a/docs/4.x/deployment.md +++ b/docs/4.x/deployment.md @@ -101,7 +101,7 @@ Proprietary and open source cloud computing solutions are both options for hosti ## Deployment -Broadly, we’re defining _deployment_ as the process of publishing code changes to a live website. +Broadly, we’re defining _deployment_ as the process of publishing code changes to a live website. For the following examples, we’ll assume your project uses the standard [directory structure](directory-structure.md). ::: tip Be sure and read our [Deployment Best Practices](kb:deployment-best-practices) article for some high-level recommendations. What follows is intended for technical users who are tasked with extending their workflow to a web server. @@ -161,7 +161,7 @@ With a generic deployment framework in place, we’re ready to get into a few co Let’s assume you’ve cloned your project onto a host, and configured it to serve requests directly out of the `web/` directory. -Within the project directory, a simple Git-based deployment might look like this: +Within the project’s root directory, a simple Git-based deployment might look like this: ```bash # Fetch new code: diff --git a/docs/4.x/dev/controller-actions.md b/docs/4.x/dev/controller-actions.md index 957ab71d3..c39b26234 100644 --- a/docs/4.x/dev/controller-actions.md +++ b/docs/4.x/dev/controller-actions.md @@ -1,4 +1,5 @@ --- +description: Craft has a powerful and secure HTTP API for interacting with accounts, content, and other features from your front-end. sidebarDepth: 2 related: - uri: https://craftcms.com/knowledge-base/front-end-user-accounts @@ -494,11 +495,11 @@ Similarly, if you are outputting user-submitted content anywhere on site, take s Param | Description ----- | ----------- -`authorId` | The ID of the user account that should be set as the entry author. (Defaults to the entry’s current author, or the logged-in user.) -`canonicalId` | Canonical (non-draft, non-revision) entry ID to update. +`author` | The ID of the user account that should be set as the entry author. (Defaults to the entry’s current author, or the logged-in user.) +`canonicalId` | The ID of the entry to save, if updating an existing entry. `enabledForSite` | Whether the entry should be enabled for the entry’s `siteId` (`1`/`0`), or an array of site IDs that the entry should be enabled for. (Defaults to the `enabled` param.) `enabled` | Whether the entry should be enabled (`1`/`0`). (Defaults to enabled.) -`entryId` | Fallback if `sourceId` isn’t passed, for backwards compatibility. +`entryId` | Fallback if `canonicalId` isn’t passed, for backwards compatibility. `entryVariable` | The [hashed](./filters.md#hash) name of the variable that should reference the entry, if a validation error occurs. (Defaults to `entry`.) `expiryDate` | The expiry date for the entry. (Defaults to the current expiry date, or `null`.) `fieldsLocation` | Parameter name under which Craft will look for custom field data. (Defaults to `fields`.) @@ -510,7 +511,7 @@ Param | Description `sectionId` | The ID of the section the entry will be created in. (Only for new entries. User must have appropriate permissions.) `siteId` | The ID of the site to save the entry in. `slug` | The entry slug. (Defaults to the current slug, or an auto-generated slug.) -`sourceId` | The ID of the entry to save, if updating an existing entry (including drafts and revisions). +`sourceId` | Fallback if `canonicalId` isn’t passed, for backwards compatibility. `title` | The entry title. (Defaults to the current entry title.) `typeId` | The entry type ID to save the entry as. (Defaults to the current entry type for existing entries, or the first configured type for new ones.) diff --git a/docs/4.x/dev/filters.md b/docs/4.x/dev/filters.md index 30ca39fc9..7b185b25a 100644 --- a/docs/4.x/dev/filters.md +++ b/docs/4.x/dev/filters.md @@ -568,7 +568,7 @@ Coerces the passed value to a float using PHP’s [`floatval()`](https://www.php ## `group` -Groups items in an array by a the results of an arrow function. +Groups items in an array by the results of an arrow function. ```twig {% set allEntries = craft.entries().section('blog').all() %} @@ -778,12 +778,24 @@ the [Apple Extended Keyboard II] [1]. ``` This filter supports two arguments: -- `flavor` can be `'original'` (default value), `'gfm'`(GitHub-Flavored Markdown), `'gfm-comment'` (GFM with newlines converted to `
`s), or `'extra'` (Markdown Extra) -- `inlineOnly` determines whether to only parse inline elements, omitting any `

` tags (defaults to `false`) +- `flavor` — Choose the “flavor” of Markdown the parser will use. Must be one of: + - `'original'` (Default) + - `'gfm'`([GitHub-Flavored Markdown](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)) + - `'gfm-comment'` (GitHub-Flavored Markdown with newlines converted to `
`s) + - `'extra'` ([Markdown Extra](https://michelf.ca/projects/php-markdown/extra/)) + - `'pre-escape'` (Same as `'original'` but forces the `encode` argument to `true`) +- `inlineOnly` — Determines whether to only parse inline elements, omitting any `

` tags (defaults to `false`) +- `encode` — Equivalent to pre-processing the input string with Twig’s [`escape` or `e` filter](https://twig.symfony.com/doc/3.x/filters/escape.html), i.e: `{{ content|e|md }}`. _Only the `original` and `pre-escape` flavors are allowed when encoding is enabled._ + +::: danger +**Do not output user-submitted content with this filter.** The resulting markup is “trusted” by the Twig environment (as though it were output with the `|raw` filter), and can result in [XSS vulnerabilities](https://owasp.org/www-community/attacks/xss/). + +To protect your site or app, first pass the text through the [`escape` or `e` filter](https://twig.symfony.com/doc/3.x/filters/escape.html), or set the `escape` argument to `true`. +::: ## `merge` -Merges an array with another one. +Merges the passed array with another one. This has the same behavior as [Twig’s merge filter](https://twig.symfony.com/doc/3.x/filters/merge.html) which uses PHP’s [array_merge()](https://www.php.net/manual/en/function.array-merge.php) under the hood: @@ -1224,7 +1236,7 @@ When a mapping array is passed, this works identically to Twig’s core [`replac }) }} ``` -Or you can replace one thing at a time: +To replace one string at a time, pass the string you want to replace as the first argument, and the replacement as the second argument: ```twig {% set str = 'Hello, NAME' %} @@ -1238,7 +1250,7 @@ You can also use a regular expression to search for matches by starting and endi {{ tag.title|lower|replace('/[^\\w]+/', '-') }} ``` -Regular expressions can also be used as keys when passing an array: +When passing an array, its keys can be regular expressions : ```twig {{ tag.title|lower|replace({ @@ -1247,6 +1259,15 @@ Regular expressions can also be used as keys : + +```twig{4} +{{ tag.title|lower|replace({ + '/you/i': 'y’all', + '/-_-/': '(^_^)', +}, regex=false) }} +``` + ## `rss` Outputs a date in the format required for RSS feeds (`D, d M Y H:i:s O`). diff --git a/docs/4.x/directory-structure.md b/docs/4.x/directory-structure.md index 5886037fb..90c7fd5f0 100644 --- a/docs/4.x/directory-structure.md +++ b/docs/4.x/directory-structure.md @@ -1,95 +1,156 @@ # Directory Structure -A fresh Craft 4 [installation](./installation.md) will have the following folders and files in it. +A fresh Craft 4 [installation](./installation.md) will have the following folders and files in it. Existing projects may have [additional files](#other-common-files) in the root. -### `config/` +## Customizing Paths -Holds all of your Craft and plugin [configuration files](config/README.md), as well as your `license.key` file. +Craft’s default directory structure is intended to work for most projects and [hosting](./deployment.md) environments, but it is deeply customizable. Paths to many of the core files and folders can be changed by setting special [environment overrides](./config/README.md#environment-overrides). -::: tip -You can customize the name and location of this folder by setting the [CRAFT_CONFIG_PATH](config/README.md#craft-config-path) PHP constant in your [entry script](./config/README.md#entry-script). +::: warning +Many of these directories’ locations are defined relative to Craft’s _base path_. Manually setting the [`CRAFT_BASE_PATH`](./config/README.md#craft_base_path) environment override without making the corresponding adjustments to the rest of your project’s structure (or explicitly setting other paths) can lead to a non-functional installation. ::: -### `modules/` +## Folders + +### `config/` + +Purpose +: Holds all of your project’s static [configuration](config/README.md#where-configuration-happens) files, as well as its `license.key` file. Your [`.env` file](#env), however, is typically located in the project root! -Holds any [Yii modules](https://www.yiiframework.com/doc/guide/2.0/en/structure-modules) your site might be using. +Configuration +: [`CRAFT_CONFIG_PATH`](./config/README.md#craft-config-path) ### `storage/` -This is where Craft stores a bunch of files that get dynamically generated at runtime. +Purpose +: This is where Craft stores a variety of files that are dynamically generated at runtime. -Some of the folders you might find in there include: + Some of the folders you might find in the storage directory include: -- `backups/` – Stores database backups that get created when you update Craft or run the DB Backup utility. -- `logs/` – Stores Craft’s logs and PHP error logs. -- `rebrand/` – Stores the custom Login Page Logo and Site Icon files, if you’ve uploaded them. -- `runtime/` – Pretty much everything in here is there for caching and logging purposes. Nothing that Craft couldn’t live without, if the folder happened to get deleted. + - `backups/` — Stores database backups that get created when you update Craft, or capture a backup via the control panel utility or [CLI](./console-commands.md#db-backup). + - `logs/` — Stores Craft’s [logs](./logging.md) and PHP error logs. + - `rebrand/` — Stores the custom Login Page Logo and Site Icon files, if you’ve uploaded them. + - `runtime/` — Pretty much everything in here is there for caching and logging purposes. Nothing that Craft couldn’t live without, if the folder happened to get deleted. -For the curious, here are the types of things you will find in `storage/runtime/` (though this is not a comprehensive list): + For the curious, here are the types of things you will find in `storage/runtime/` (though this is not a comprehensive list): - - `assets/` – Stores image thumbnails, resized file icons, and copies of images stored on remote asset volumes, to save Craft an HTTP request when it needs the images to generate new thumbnails or transforms. - - `cache/` – Stores data caches. - - `compiled_classes/` – Stores some dynamically-defined PHP classes. - - `compiled_templates/` – Stores compiled Twig templates. - - `temp/` – Stores temp files. - - `validation.key` – A randomly-generated, cryptographically secure key that is used for hashing and validating data between requests. + - `assets/` — Stores temporary uploads, image thumbnails, resized file icons, image editor scratch files, and copies of images stored on remote asset volumes (to save Craft an HTTP request when it needs the images to generate new thumbnails or transforms). + - `cache/` — Stores arbitrary data caches, when using the [`FileCache` driver](./config/app.md#cache). + - `compiled_classes/` — Stores some dynamically-defined PHP classes. + - `compiled_templates/` — Stores compiled Twig templates. This is _not_ your main [templates](#templates) folder! + - `temp/` — Other temporary files. The names and contents of files in here do not obey any convention—the assumption should be that they will be deleted or overwritten between requests. -::: tip -You can customize the name and location of this folder by setting the [CRAFT_STORAGE_PATH](config/README.md#craft-storage-path) PHP constant in your [entry script](./config/README.md#entry-script). -::: +Configuration +: [`CRAFT_STORAGE_PATH`](./config/README.md#craft-storage-path) — This is useful when running on systems with an [ephemeral](./config/README.md#craft-ephemeral) or “read-only” filesystem (wherein the only place to write temporary files is a central `/tmp` directory). ### `templates/` -Your front-end Twig templates go in here. Any local site assets, such as images, CSS, and JS that should be statically served, should live in the [web](directory-structure.md#web) folder. +Purpose +: Your front-end Twig templates go in here. Any local site assets, such as images, CSS, and JS that should be statically served, should live in the [web/](directory-structure.md#web) folder. The [Routing](./routing.md) page has an overview of how files in this folder are handled. -::: tip -You can customize the name and location of this folder by setting the [CRAFT_TEMPLATES_PATH](config/README.md#craft-templates-path) PHP constant in your [entry script](./config/README.md#entry-script). -::: +Configuration +: [`CRAFT_TEMPLATES_PATH`](./config/README.md#craft-templates-path) — Plugins may register additional _template roots_ that behave similarly, but are not affected by this setting and generally do not contain user-editable templates. ### `vendor/` -This is where all of your Composer dependencies go—including Craft and any plugins you’ve installed. This directory should _not_ be tracked in version control. Instead, commit [`composer.lock`](#composerlock), and use [`composer install`](https://getcomposer.org/doc/03-cli.md#install-i) to rebuild it. +Purpose +: This is where all of your Composer dependencies go—including Craft and any plugins you’ve installed. This directory should _not_ be tracked in version control. Instead, commit [`composer.lock`](#composerlock), and use [`composer install`](https://getcomposer.org/doc/03-cli.md#install-i) to rebuild it. -::: tip -You can customize the name and location of this folder by changing the [CRAFT_VENDOR_PATH](config/README.md#craft-vendor-path) PHP constant in your [entry script](./config/README.md#entry-script). If you choose to relocate it, make sure you update your `.gitignore` file to continue excluding it from version control. -::: +Configuration +: [`CRAFT_VENDOR_PATH`](config/README.md#craft-vendor-path) — If you choose to relocate your `vendor/` directory, make sure you update your `.gitignore` file to continue excluding it from version control. ### `web/` -This directory represents your server’s web root. The public `index.php` file lives here and this is where any of the local site images, CSS, and JS that is statically served should live. +Purpose +: This directory represents your server’s web root. The public `index.php` file lives here, alongside your static images, stylesheets, and JavaScript files. -::: tip -You can customize the name and location of this folder. If you move it so it’s no longer living alongside the other Craft folders, make sure to update the [CRAFT_BASE_PATH](config/README.md#craft-vendor-path) PHP constant in your [entry script](./config/README.md#entry-script). -::: + You can generate a URL to a file in this folder with Twig’s [`siteUrl()` function](./dev/functions.md#siteurl). + +Customization +: [`CRAFT_WEB_ROOT`](./config/README.md#craft-web-root) — This is primarily used to set the [`@webroot` alias](./config/README.md#aliases). + +## Files ### `.env` -This is your [PHP dotenv](https://github.com/vlucas/phpdotenv) `.env` configuration file. It defines sensitive or [environment-specific config](./config/README.md#env) values that don’t make sense to commit to version control. +Purpose +: This is your [PHP dotenv](https://github.com/vlucas/phpdotenv) `.env` configuration file. It defines sensitive or [environment-specific config](./config/README.md#env) values that don’t make sense to commit to version control. + + The [starter project](https://github.com/craftcms/craft) provides a few examples of configuration that is apt to change between environments—you’ll see a group of similarly-named files, like `.env.example.staging`. -### `.env.example` + These are `.env` file templates. Maintain one of them (with sensitive data removed) as a starting point for your actual `.env` file, so collaborators know what variables the project requires. When they set up the project, they can run `cp .env.example .env` to duplicate the file and fill out missing keys! -This is your [PHP dotenv](https://github.com/vlucas/phpdotenv) `.env` file template. It should be used as a starting point for any actual `.env` files, stored alongside it but out of version control on each of the environments your Craft project is running in. +Configuration +: [`CRAFT_DOTENV_PATH`](./config/README.md#craft-dotenv-path) — This setting _was_ technically available in prior versions, but unreliable. ### `.gitignore` -Tells Git which files it should exclude when committing changes. At minimum, this should ignore `.env` and Composer’s `vendor/` directory. +This file tells Git which files it should exclude when committing changes. At minimum, it should contain entries for `.env` and Composer’s `vendor/` directory. + +Check out our [Hosting & Deployment](./deployment.md#be-aware-of-artifacts) article for a list of other things you’ll want to exclude. ### `bootstrap.php` -The [starter project](depo:craftcms/craft) consolidates important bootstrapping logic (like defining path [constants](./config/README.md#php-constants) and loading environment variables from the [`.env`](#env) file) into this file. Both the HTTP and console entry scripts (`web/index.php` and [`craft`](#craft), respectively) include this file—but each goes on to instantiate a different [type of application](guide:structure-entry-scripts) suited for that request context. +The [starter project](depo:craftcms/craft) consolidates important bootstrapping logic (like defining path [constants](./config/README.md#php-constants) that determine the above directories’ locations, and loading environment variables from a [`.env`](#env) file) into this file. Both the HTTP and console entry scripts (`web/index.php` and [`craft`](#craft), respectively) include this file—but each goes on to instantiate a different [type of application](guide:structure-entry-scripts) suited for that request context. + +This file’s location only matters to your entry scripts, so it is not “configurable” like other paths are. If you make changes to the layout of your project directory, be sure and update the references to `bootstrap.php` in `index.php` and the CLI entry point. ### `composer.json` -The starting point `composer.json` file that should be used for all Craft projects. See the [Composer documentation](https://getcomposer.org/doc/04-schema.md) for details on what can go in here. +Your project’s PHP dependencies are declared in this file. If you just started your project, the only two packages it will explicitly require are `craftcms/cms` (Craft’s core) and `vlucas/phpdotenv` (used in the entry scripts). Existing projects may contain more packages—say, if the it relies on Craft [plugins](./plugins.md) or includes other [custom functionality](./extend/README.md). + +Craft uses Composer to update itself and install plugins. See the [Composer documentation](https://getcomposer.org/doc/04-schema.md) for details on how this file works. ### `composer.lock` -This is a Composer file that tells Composer exactly which dependencies and versions should be currently installed in `vendor/`. +This is a Composer-managed file that contains the _exact_ list of packages (and their versions) that should be installed in the `vendor/` directory. It should be committed to version control so that anyone working on the project can run `composer install` to download all its dependencies. ### `craft` -This is a command line executable used to execute Craft’s [console commands](console-commands.md). Its structure is similar to `web/index.php`, insofar as it is responsible for bootstrapping the appropriate Craft application—but instead of a , it creates a . +This is a command line executable used to run Craft’s [console commands](console-commands.md). Its structure is similar to `web/index.php` (insofar as it is responsible for bootstrapping the appropriate Craft application), but instead of a , it creates a and handles the “request” with a different set of controllers. + +## Other Common Files + +Depending on the age and structure of your Craft project (as well as the tools used to build it), your project directory may look a little bit different! Here are some examples of common things you might find when inheriting a project: ### `.ddev/` -If you followed the [installation](./installation.md) guide, DDEV will have left a `.ddev/` directory in the root of your project. This is safe to keep in version control—DDEV may make changes to it from time to time, but a separate `.gitignore` file exists within it to ensure only necessary files are tracked. +If you (or another maintainer) followed the [installation](./installation.md) instructions or [Getting Started Tutorial](/getting-started-tutorial/README.md), DDEV will have left a `.ddev/` directory in the root of your project. This is safe to keep in version control—DDEV may make changes to it from time to time, but a separate `.gitignore` file exists within it to ensure only necessary files are tracked. + +### `migrations/` + +Projects that use [content migrations](./extend/migrations.md) will typically use this directory, but it is customizable with the [`CRAFT_CONTENT_MIGRATIONS_PATH`](./config/README.md#craft-content-migrations-path) variable. + +### `modules/` + +For a time, the starter project came with a pre-initialized [custom module](./extend/module-guide.md) in the `modules/` directory. This is typically harmless, but it cannot be removed without also modifying your project’s `config/app.php` file. + +### `public/` + +Older projects may have carried over a Craft 2 convention of naming their public web directory `public/`. There is no functional difference between these folder names, but most Craft resources will refer to it as `web/`. + +### `tests/` + +When using [tests](./testing/README.md) to validate application changes, you are apt to have a dedicated `tests/` directory. + +### `translations/` + +Multi-site projects often make use of [static translations](./sites.md#static-message-translations), which are stored in this directory, indexed by their language code. Customize this location with the [`CRAFT_TRANSLATIONS_PATH`](./config/README.md#craft-translations-path) variable. + +### `package.json` + +Projects that use Node.js will typically contain `package.json` and `package-lock.json` files, as well as a `node_modules/` directory. Craft does not interact with these files, but they often contain information about how the front-end of your site works. + +Oftentimes, a Node.js “build step” will output files that are then loaded by a user’s browser—those should be written to the web root so they can be directly requested via HTTP. + +### `craft.bat` + +A Windows-specific command line entry point or “batch file.” + +### Docker Files + +A `Dockerfile` or `docker-compose.yml` in your project root suggests that it is intended to be run in [Docker](https://www.docker.com/), a containerized development environment. DDEV users will typically _not_ see these files, as they’re abstracted by configuration stored in the [`.ddev/` directory](#ddev). + +### IDE Configuration + +Some editors write configuration to a file or folder within your project—for example, PhpStorm will create a `.idea/` directory; Visual Studio Code uses `.vscode/`. Coordinate with your team about which tools are valuable to your process, and commit anything that supports it. diff --git a/docs/4.x/entries.md b/docs/4.x/entries.md index e68039a9c..281a8e095 100644 --- a/docs/4.x/entries.md +++ b/docs/4.x/entries.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Entries Entries are the primary container for content you want to display on your web pages. Each entry has _Title_, _Author_, a _Post Date_, an _Expiration Date_ (if desired), a _Status_ (enabled or disabled), and—like other [element types](elements.md)—flexible content defined via [custom fields](fields.md). Also like other elements, entries can have their own [URLs](#entry-uri-formats), or be fetched from anywhere via [element queries](#querying-entries). @@ -444,1981 +448,5 @@ We can display the 10 most recent entries in a “Blog” section by doing the f Entry queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [after](#after) | Narrows the query results to only entries that were posted on or after a certain date. -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [ancestorDist](#ancestordist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). -| [ancestorOf](#ancestorof) | Narrows the query results to only entries that are ancestors of another entry in its structure. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only entries that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching entries as arrays of data, rather than [Entry](craft4:craft\elements\Entry) objects. -| [authorGroup](#authorgroup) | Narrows the query results based on the user group the entries’ authors belong to. -| [authorGroupId](#authorgroupid) | Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. -| [authorId](#authorid) | Narrows the query results based on the entries’ authors. -| [before](#before) | Narrows the query results to only entries that were posted before a certain date. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [collect](#collect) | -| [dateCreated](#datecreated) | Narrows the query results based on the entries’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the entries’ last-updated dates. -| [descendantDist](#descendantdist) | Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). -| [descendantOf](#descendantof) | Narrows the query results to only entries that are descendants of another entry in its structure. -| [draftCreator](#draftcreator) | Narrows the query results to only drafts created by a given user. -| [draftId](#draftid) | Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). -| [draftOf](#draftof) | Narrows the query results to only drafts of a given entry. -| [drafts](#drafts) | Narrows the query results to only drafts entries. -| [expiryDate](#expirydate) | Narrows the query results based on the entries’ expiry dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [hasDescendants](#hasdescendants) | Narrows the query results based on whether the entries have any descendants in their structure. -| [id](#id) | Narrows the query results based on the entries’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [leaves](#leaves) | Narrows the query results based on whether the entries are “leaves” (entries with no descendants). -| [level](#level) | Narrows the query results based on the entries’ level within the structure. -| [limit](#limit) | Determines the number of entries that should be returned. -| [nextSiblingOf](#nextsiblingof) | Narrows the query results to only the entry that comes immediately after another entry in its structure. -| [offset](#offset) | Determines how many entries should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`, or the order defined by the section if the [section](#section) or [sectionId](#sectionid) params are set to a single Structure section.) -| [positionedAfter](#positionedafter) | Narrows the query results to only entries that are positioned after another entry in its structure. -| [positionedBefore](#positionedbefore) | Narrows the query results to only entries that are positioned before another entry in its structure. -| [postDate](#postdate) | Narrows the query results based on the entries’ post dates. -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [prevSiblingOf](#prevsiblingof) | Narrows the query results to only the entry that comes immediately before another entry in its structure. -| [provisionalDrafts](#provisionaldrafts) | Narrows the query results to only provisional drafts. -| [relatedTo](#relatedto) | Narrows the query results to only entries that are related to certain other elements. -| [revisionCreator](#revisioncreator) | Narrows the query results to only revisions created by a given user. -| [revisionId](#revisionid) | Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). -| [revisionOf](#revisionof) | Narrows the query results to only revisions of a given entry. -| [revisions](#revisions) | Narrows the query results to only revision entries. -| [savable](#savable) | Sets the [savable](https://docs.craftcms.com/api/v3/craft-elements-db-entryquery.html#savable) property. -| [savedDraftsOnly](#saveddraftsonly) | Narrows the query results to only unpublished drafts which have been saved after initial creation. -| [search](#search) | Narrows the query results to only entries that match a search query. -| [section](#section) | Narrows the query results based on the sections the entries belong to. -| [sectionId](#sectionid) | Narrows the query results based on the sections the entries belong to, per the sections’ IDs. -| [siblingOf](#siblingof) | Narrows the query results to only entries that are siblings of another entry in its structure. -| [site](#site) | Determines which site(s) the entries should be queried in. -| [siteId](#siteid) | Determines which site(s) the entries should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the entries’ IDs in the `elements_sites` table. -| [slug](#slug) | Narrows the query results based on the entries’ slugs. -| [status](#status) | Narrows the query results based on the entries’ statuses. -| [title](#title) | Narrows the query results based on the entries’ titles. -| [trashed](#trashed) | Narrows the query results to only entries that have been soft-deleted. -| [type](#type) | Narrows the query results based on the entries’ entry types. -| [typeId](#typeid) | Narrows the query results based on the entries’ entry types, per the types’ IDs. -| [uid](#uid) | Narrows the query results based on the entries’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uri](#uri) | Narrows the query results based on the entries’ URIs. -| [with](#with) | Causes the query to return matching entries eager-loaded with related elements. - - - - - -#### `after` - -Narrows the query results to only entries that were posted on or after a certain date. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'2018-04-01'` | that were posted after 2018-04-01. -| a [DateTime](https://php.net/class.datetime) object | that were posted after the date represented by the object. -| `now`/`today`/`tomorrow`/`yesterday` | that were posted after midnight of the specified relative date. - - - -::: code -```twig -{# Fetch entries posted this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set entries = craft.entries() - .after(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch entries posted this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$entries = \craft\elements\Entry::find() - ->after($firstDayOfMonth) - ->all(); -``` -::: - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `ancestorDist` - -Narrows the query results to only entries that are up to a certain distance away from the entry specified by [ancestorOf](#ancestorof). - - - - - -::: code -```twig -{# Fetch entries above this one #} -{% set entries = craft.entries() - .ancestorOf(myEntry) - .ancestorDist(3) - .all() %} -``` - -```php -// Fetch entries above this one -$entries = \craft\elements\Entry::find() - ->ancestorOf($myEntry) - ->ancestorDist(3) - ->all(); -``` -::: - - -#### `ancestorOf` - -Narrows the query results to only entries that are ancestors of another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | above the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | above the entry represented by the object. - - - -::: code -```twig -{# Fetch entries above this one #} -{% set entries = craft.entries() - .ancestorOf(myEntry) - .all() %} -``` - -```php -// Fetch entries above this one -$entries = \craft\elements\Entry::find() - ->ancestorOf($myEntry) - ->all(); -``` -::: - - - -::: tip -This can be combined with [ancestorDist](#ancestordist) if you want to limit how far away the ancestor entries can be. -::: - - -#### `andRelatedTo` - -Narrows the query results to only entries that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all entries that are related to myCategoryA and myCategoryB #} -{% set entries = craft.entries() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all entries that are related to $myCategoryA and $myCategoryB -$entries = \craft\elements\Entry::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching entries as arrays of data, rather than [Entry](craft4:craft\elements\Entry) objects. - - - - - -::: code -```twig -{# Fetch entries as arrays #} -{% set entries = craft.entries() - .asArray() - .all() %} -``` - -```php -// Fetch entries as arrays -$entries = \craft\elements\Entry::find() - ->asArray() - ->all(); -``` -::: - - -#### `authorGroup` - -Narrows the query results based on the user group the entries’ authors belong to. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | with an author in a group with a handle of `foo`. -| `'not foo'` | not with an author in a group with a handle of `foo`. -| `['foo', 'bar']` | with an author in a group with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not with an author in a group with a handle of `foo` or `bar`. -| a [UserGroup](craft4:craft\models\UserGroup) object | with an author in a group represented by the object. -| an array of [UserGroup](craft4:craft\models\UserGroup) objects | with an author in a group represented by the objects. - - - -::: code -```twig -{# Fetch entries with an author in the Foo user group #} -{% set entries = craft.entries() - .authorGroup('foo') - .all() %} -``` - -```php -// Fetch entries with an author in the Foo user group -$entries = \craft\elements\Entry::find() - ->authorGroup('foo') - ->all(); -``` -::: - - -#### `authorGroupId` - -Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with an author in a group with an ID of 1. -| `'not 1'` | not with an author in a group with an ID of 1. -| `[1, 2]` | with an author in a group with an ID of 1 or 2. -| `['not', 1, 2]` | not with an author in a group with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch entries with an author in a group with an ID of 1 #} -{% set entries = craft.entries() - .authorGroupId(1) - .all() %} -``` - -```php -// Fetch entries with an author in a group with an ID of 1 -$entries = \craft\elements\Entry::find() - ->authorGroupId(1) - ->all(); -``` -::: - - -#### `authorId` - -Narrows the query results based on the entries’ authors. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with an author with an ID of 1. -| `'not 1'` | not with an author with an ID of 1. -| `[1, 2]` | with an author with an ID of 1 or 2. -| `['not', 1, 2]` | not with an author with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch entries with an author with an ID of 1 #} -{% set entries = craft.entries() - .authorId(1) - .all() %} -``` - -```php -// Fetch entries with an author with an ID of 1 -$entries = \craft\elements\Entry::find() - ->authorId(1) - ->all(); -``` -::: - - -#### `before` - -Narrows the query results to only entries that were posted before a certain date. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'2018-04-01'` | that were posted before 2018-04-01. -| a [DateTime](https://php.net/class.datetime) object | that were posted before the date represented by the object. -| `now`/`today`/`tomorrow`/`yesterday` | that were posted before midnight of specified relative date. - - - -::: code -```twig -{# Fetch entries posted before this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set entries = craft.entries() - .before(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch entries posted before this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$entries = \craft\elements\Entry::find() - ->before($firstDayOfMonth) - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `collect` - - - - - - - - -#### `dateCreated` - -Narrows the query results based on the entries’ creation dates. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch entries created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set entries = craft.entries() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch entries created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$entries = \craft\elements\Entry::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the entries’ last-updated dates. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch entries updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set entries = craft.entries() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch entries updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$entries = \craft\elements\Entry::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `descendantDist` - -Narrows the query results to only entries that are up to a certain distance away from the entry specified by [descendantOf](#descendantof). - - - - - -::: code -```twig -{# Fetch entries below this one #} -{% set entries = craft.entries() - .descendantOf(myEntry) - .descendantDist(3) - .all() %} -``` - -```php -// Fetch entries below this one -$entries = \craft\elements\Entry::find() - ->descendantOf($myEntry) - ->descendantDist(3) - ->all(); -``` -::: - - -#### `descendantOf` - -Narrows the query results to only entries that are descendants of another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | below the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | below the entry represented by the object. - - - -::: code -```twig -{# Fetch entries below this one #} -{% set entries = craft.entries() - .descendantOf(myEntry) - .all() %} -``` - -```php -// Fetch entries below this one -$entries = \craft\elements\Entry::find() - ->descendantOf($myEntry) - ->all(); -``` -::: - - - -::: tip -This can be combined with [descendantDist](#descendantdist) if you want to limit how far away the descendant entries can be. -::: - - -#### `draftCreator` - -Narrows the query results to only drafts created by a given user. - - - -Possible values include: - -| Value | Fetches drafts… -| - | - -| `1` | created by the user with an ID of 1. -| a [craft\elements\User](craft4:craft\elements\User) object | created by the user represented by the object. - - - -::: code -```twig -{# Fetch drafts by the current user #} -{% set entries = craft.entries() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch drafts by the current user -$entries = \craft\elements\Entry::find() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -#### `draftId` - -Narrows the query results based on the entries’ draft’s ID (from the `drafts` table). - - - -Possible values include: - -| Value | Fetches drafts… -| - | - -| `1` | for the draft with an ID of 1. - - - -::: code -```twig -{# Fetch a draft #} -{% set entries = craft.entries() - .draftId(10) - .all() %} -``` - -```php -// Fetch a draft -$entries = \craft\elements\Entry::find() - ->draftId(10) - ->all(); -``` -::: - - -#### `draftOf` - -Narrows the query results to only drafts of a given entry. - - - -Possible values include: - -| Value | Fetches drafts… -| - | - -| `1` | for the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | for the entry represented by the object. -| `'*'` | for any entry -| `false` | that aren’t associated with a published entry - - - -::: code -```twig -{# Fetch drafts of the entry #} -{% set entries = craft.entries() - .draftOf(myEntry) - .all() %} -``` - -```php -// Fetch drafts of the entry -$entries = \craft\elements\Entry::find() - ->draftOf($myEntry) - ->all(); -``` -::: - - -#### `drafts` - -Narrows the query results to only drafts entries. - - - - - -::: code -```twig -{# Fetch a draft entry #} -{% set entries = craft.entries() - .drafts() - .id(123) - .one() %} -``` - -```php -// Fetch a draft entry -$entries = \craft\elements\Entry::find() - ->drafts() - ->id(123) - ->one(); -``` -::: - - -#### `expiryDate` - -Narrows the query results based on the entries’ expiry dates. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `':empty:'` | that don’t have an expiry date. -| `':notempty:'` | that have an expiry date. -| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. -| `'< 2020-05-01'` | that will expire before 2020-05-01 -| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that expire at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch entries expiring this month #} -{% set nextMonth = date('first day of next month')|atom %} - -{% set entries = craft.entries() - .expiryDate("< #{nextMonth}") - .all() %} -``` - -```php -// Fetch entries expiring this month -$nextMonth = (new \DateTime('first day of next month'))->format(\DateTime::ATOM); - -$entries = \craft\elements\Entry::find() - ->expiryDate("< {$nextMonth}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch entries in a specific order #} -{% set entries = craft.entries() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch entries in a specific order -$entries = \craft\elements\Entry::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `hasDescendants` - -Narrows the query results based on whether the entries have any descendants in their structure. - - - -(This has the opposite effect of calling [leaves](#leaves).) - - - -::: code -```twig -{# Fetch entries that have descendants #} -{% set entries = craft.entries() - .hasDescendants() - .all() %} -``` - -```php -// Fetch entries that have descendants -$entries = \craft\elements\Entry::find() - ->hasDescendants() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the entries’ IDs. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the entry by its ID #} -{% set entry = craft.entries() - .id(1) - .one() %} -``` - -```php -// Fetch the entry by its ID -$entry = \craft\elements\Entry::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch entries in reverse #} -{% set entries = craft.entries() - .inReverse() - .all() %} -``` - -```php -// Fetch entries in reverse -$entries = \craft\elements\Entry::find() - ->inReverse() - ->all(); -``` -::: - - -#### `leaves` - -Narrows the query results based on whether the entries are “leaves” (entries with no descendants). - - - -(This has the opposite effect of calling [hasDescendants](#hasdescendants).) - - - -::: code -```twig -{# Fetch entries that have no descendants #} -{% set entries = craft.entries() - .leaves() - .all() %} -``` - -```php -// Fetch entries that have no descendants -$entries = \craft\elements\Entry::find() - ->leaves() - ->all(); -``` -::: - - -#### `level` - -Narrows the query results based on the entries’ level within the structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with a level of 1. -| `'not 1'` | not with a level of 1. -| `'>= 3'` | with a level greater than or equal to 3. -| `[1, 2]` | with a level of 1 or 2 -| `['not', 1, 2]` | not with level of 1 or 2. - - - -::: code -```twig -{# Fetch entries positioned at level 3 or above #} -{% set entries = craft.entries() - .level('>= 3') - .all() %} -``` - -```php -// Fetch entries positioned at level 3 or above -$entries = \craft\elements\Entry::find() - ->level('>= 3') - ->all(); -``` -::: - - -#### `limit` - -Determines the number of entries that should be returned. - - - -::: code -```twig -{# Fetch up to 10 entries #} -{% set entries = craft.entries() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 entries -$entries = \craft\elements\Entry::find() - ->limit(10) - ->all(); -``` -::: - - -#### `nextSiblingOf` - -Narrows the query results to only the entry that comes immediately after another entry in its structure. - - - -Possible values include: - -| Value | Fetches the entry… -| - | - -| `1` | after the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | after the entry represented by the object. - - - -::: code -```twig -{# Fetch the next entry #} -{% set entry = craft.entries() - .nextSiblingOf(myEntry) - .one() %} -``` - -```php -// Fetch the next entry -$entry = \craft\elements\Entry::find() - ->nextSiblingOf($myEntry) - ->one(); -``` -::: - - -#### `offset` - -Determines how many entries should be skipped in the results. - - - -::: code -```twig -{# Fetch all entries except for the first 3 #} -{% set entries = craft.entries() - .offset(3) - .all() %} -``` - -```php -// Fetch all entries except for the first 3 -$entries = \craft\elements\Entry::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the entries should be returned in. (If empty, defaults to `postDate DESC`, or the order defined by the section if the [section](#section) or [sectionId](#sectionid) params are set to a single Structure section.) - - - -::: code -```twig -{# Fetch all entries in order of date created #} -{% set entries = craft.entries() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all entries in order of date created -$entries = \craft\elements\Entry::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `positionedAfter` - -Narrows the query results to only entries that are positioned after another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | after the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | after the entry represented by the object. - - - -::: code -```twig -{# Fetch entries after this one #} -{% set entries = craft.entries() - .positionedAfter(myEntry) - .all() %} -``` - -```php -// Fetch entries after this one -$entries = \craft\elements\Entry::find() - ->positionedAfter($myEntry) - ->all(); -``` -::: - - -#### `positionedBefore` - -Narrows the query results to only entries that are positioned before another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | before the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | before the entry represented by the object. - - - -::: code -```twig -{# Fetch entries before this one #} -{% set entries = craft.entries() - .positionedBefore(myEntry) - .all() %} -``` - -```php -// Fetch entries before this one -$entries = \craft\elements\Entry::find() - ->positionedBefore($myEntry) - ->all(); -``` -::: - - -#### `postDate` - -Narrows the query results based on the entries’ post dates. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. -| `'< 2018-05-01'` | that were posted before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were posted at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch entries posted last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set entries = craft.entries() - .postDate(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch entries posted last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$entries = \craft\elements\Entry::find() - ->postDate(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique entries from Site A, or Site B if they don’t exist in Site A #} -{% set entries = craft.entries() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique entries from Site A, or Site B if they don’t exist in Site A -$entries = \craft\elements\Entry::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `prevSiblingOf` - -Narrows the query results to only the entry that comes immediately before another entry in its structure. - - - -Possible values include: - -| Value | Fetches the entry… -| - | - -| `1` | before the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | before the entry represented by the object. - - - -::: code -```twig -{# Fetch the previous entry #} -{% set entry = craft.entries() - .prevSiblingOf(myEntry) - .one() %} -``` - -```php -// Fetch the previous entry -$entry = \craft\elements\Entry::find() - ->prevSiblingOf($myEntry) - ->one(); -``` -::: - - -#### `provisionalDrafts` - -Narrows the query results to only provisional drafts. - - - - - -::: code -```twig -{# Fetch provisional drafts created by the current user #} -{% set entries = craft.entries() - .provisionalDrafts() - .draftCreator(currentUser) - .all() %} -``` - -```php -// Fetch provisional drafts created by the current user -$entries = \craft\elements\Entry::find() - ->provisionalDrafts() - ->draftCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only entries that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all entries that are related to myCategory #} -{% set entries = craft.entries() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all entries that are related to $myCategory -$entries = \craft\elements\Entry::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `revisionCreator` - -Narrows the query results to only revisions created by a given user. - - - -Possible values include: - -| Value | Fetches revisions… -| - | - -| `1` | created by the user with an ID of 1. -| a [craft\elements\User](craft4:craft\elements\User) object | created by the user represented by the object. - - - -::: code -```twig -{# Fetch revisions by the current user #} -{% set entries = craft.entries() - .revisionCreator(currentUser) - .all() %} -``` - -```php -// Fetch revisions by the current user -$entries = \craft\elements\Entry::find() - ->revisionCreator(Craft::$app->user->identity) - ->all(); -``` -::: - - -#### `revisionId` - -Narrows the query results based on the entries’ revision’s ID (from the `revisions` table). - - - -Possible values include: - -| Value | Fetches revisions… -| - | - -| `1` | for the revision with an ID of 1. - - - -::: code -```twig -{# Fetch a revision #} -{% set entries = craft.entries() - .revisionId(10) - .all() %} -``` - -```php -// Fetch a revision -$entries = \craft\elements\Entry::find() - ->revisionIf(10) - ->all(); -``` -::: - - -#### `revisionOf` - -Narrows the query results to only revisions of a given entry. - - - -Possible values include: - -| Value | Fetches revisions… -| - | - -| `1` | for the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | for the entry represented by the object. - - - -::: code -```twig -{# Fetch revisions of the entry #} -{% set entries = craft.entries() - .revisionOf(myEntry) - .all() %} -``` - -```php -// Fetch revisions of the entry -$entries = \craft\elements\Entry::find() - ->revisionOf($myEntry) - ->all(); -``` -::: - - -#### `revisions` - -Narrows the query results to only revision entries. - - - - - -::: code -```twig -{# Fetch a revision entry #} -{% set entries = craft.entries() - .revisions() - .id(123) - .one() %} -``` - -```php -// Fetch a revision entry -$entries = \craft\elements\Entry::find() - ->revisions() - ->id(123) - ->one(); -``` -::: - - -#### `savable` - -Sets the [savable](https://docs.craftcms.com/api/v3/craft-elements-db-entryquery.html#savable) property. - - - - - - -#### `savedDraftsOnly` - -Narrows the query results to only unpublished drafts which have been saved after initial creation. - - - - - -::: code -```twig -{# Fetch saved, unpublished draft entries #} -{% set entries = craft.entries() - .draftOf(false) - .savedDraftsOnly() - .all() %} -``` - -```php -// Fetch saved, unpublished draft entries -$entries = \craft\elements\Entry::find() - ->draftOf(false) - ->savedDraftsOnly() - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only entries that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all entries that match the search query #} -{% set entries = craft.entries() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all entries that match the search query -$entries = \craft\elements\Entry::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `section` - -Narrows the query results based on the sections the entries belong to. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | in a section with a handle of `foo`. -| `'not foo'` | not in a section with a handle of `foo`. -| `['foo', 'bar']` | in a section with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a section with a handle of `foo` or `bar`. -| a [Section](craft4:craft\models\Section) object | in a section represented by the object. - - - -::: code -```twig -{# Fetch entries in the Foo section #} -{% set entries = craft.entries() - .section('foo') - .all() %} -``` - -```php -// Fetch entries in the Foo section -$entries = \craft\elements\Entry::find() - ->section('foo') - ->all(); -``` -::: - - -#### `sectionId` - -Narrows the query results based on the sections the entries belong to, per the sections’ IDs. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | in a section with an ID of 1. -| `'not 1'` | not in a section with an ID of 1. -| `[1, 2]` | in a section with an ID of 1 or 2. -| `['not', 1, 2]` | not in a section with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch entries in the section with an ID of 1 #} -{% set entries = craft.entries() - .sectionId(1) - .all() %} -``` - -```php -// Fetch entries in the section with an ID of 1 -$entries = \craft\elements\Entry::find() - ->sectionId(1) - ->all(); -``` -::: - - -#### `siblingOf` - -Narrows the query results to only entries that are siblings of another entry in its structure. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | beside the entry with an ID of 1. -| a [Entry](craft4:craft\elements\Entry) object | beside the entry represented by the object. - - - -::: code -```twig -{# Fetch entries beside this one #} -{% set entries = craft.entries() - .siblingOf(myEntry) - .all() %} -``` - -```php -// Fetch entries beside this one -$entries = \craft\elements\Entry::find() - ->siblingOf($myEntry) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the entries should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch entries from the Foo site #} -{% set entries = craft.entries() - .site('foo') - .all() %} -``` - -```php -// Fetch entries from the Foo site -$entries = \craft\elements\Entry::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the entries should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch entries from the site with an ID of 1 #} -{% set entries = craft.entries() - .siteId(1) - .all() %} -``` - -```php -// Fetch entries from the site with an ID of 1 -$entries = \craft\elements\Entry::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the entries’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the entry by its ID in the elements_sites table #} -{% set entry = craft.entries() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the entry by its ID in the elements_sites table -$entry = \craft\elements\Entry::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `slug` - -Narrows the query results based on the entries’ slugs. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | with a slug of `foo`. -| `'foo*'` | with a slug that begins with `foo`. -| `'*foo'` | with a slug that ends with `foo`. -| `'*foo*'` | with a slug that contains `foo`. -| `'not *foo*'` | with a slug that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested entry slug from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the entry with that slug #} -{% set entry = craft.entries() - .slug(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested entry slug from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the entry with that slug -$entry = \craft\elements\Entry::find() - ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the entries’ statuses. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'live'` _(default)_ | that are live. -| `'pending'` | that are pending (enabled with a Post Date in the future). -| `'expired'` | that are expired (enabled with an Expiry Date in the past). -| `'disabled'` | that are disabled. -| `['live', 'pending']` | that are live or pending. -| `['not', 'live', 'pending']` | that are not live or pending. - - - -::: code -```twig -{# Fetch disabled entries #} -{% set entries = craft.entries() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled entries -$entries = \craft\elements\Entry::find() - ->status('disabled') - ->all(); -``` -::: - - -#### `title` - -Narrows the query results based on the entries’ titles. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch entries with a title that contains "Foo" #} -{% set entries = craft.entries() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch entries with a title that contains "Foo" -$entries = \craft\elements\Entry::find() - ->title('*Foo*') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only entries that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed entries #} -{% set entries = craft.entries() - .trashed() - .all() %} -``` - -```php -// Fetch trashed entries -$entries = \craft\elements\Entry::find() - ->trashed() - ->all(); -``` -::: - - -#### `type` - -Narrows the query results based on the entries’ entry types. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | of a type with a handle of `foo`. -| `'not foo'` | not of a type with a handle of `foo`. -| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. -| an [EntryType](craft4:craft\models\EntryType) object | of a type represented by the object. - - - -::: code -```twig -{# Fetch entries in the Foo section with a Bar entry type #} -{% set entries = craft.entries() - .section('foo') - .type('bar') - .all() %} -``` - -```php -// Fetch entries in the Foo section with a Bar entry type -$entries = \craft\elements\Entry::find() - ->section('foo') - ->type('bar') - ->all(); -``` -::: - - -#### `typeId` - -Narrows the query results based on the entries’ entry types, per the types’ IDs. - -Possible values include: - -| Value | Fetches entries… -| - | - -| `1` | of a type with an ID of 1. -| `'not 1'` | not of a type with an ID of 1. -| `[1, 2]` | of a type with an ID of 1 or 2. -| `['not', 1, 2]` | not of a type with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch entries of the entry type with an ID of 1 #} -{% set entries = craft.entries() - .typeId(1) - .all() %} -``` - -```php -// Fetch entries of the entry type with an ID of 1 -$entries = \craft\elements\Entry::find() - ->typeId(1) - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the entries’ UIDs. - - - - - -::: code -```twig -{# Fetch the entry by its UID #} -{% set entry = craft.entries() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the entry by its UID -$entry = \craft\elements\Entry::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique entries across all sites #} -{% set entries = craft.entries() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique entries across all sites -$entries = \craft\elements\Entry::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `uri` - -Narrows the query results based on the entries’ URIs. - - - -Possible values include: - -| Value | Fetches entries… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the entry with that URI #} -{% set entry = craft.entries() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the entry with that URI -$entry = \craft\elements\Entry::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching entries eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch entries eager-loaded with the "Related" field’s relations #} -{% set entries = craft.entries() - .with(['related']) - .all() %} -``` - -```php -// Fetch entries eager-loaded with the "Related" field’s relations -$entries = \craft\elements\Entry::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/4.x/entries.md)!!! diff --git a/docs/4.x/extend/README.md b/docs/4.x/extend/README.md index a8f92818d..0cf0036e6 100644 --- a/docs/4.x/extend/README.md +++ b/docs/4.x/extend/README.md @@ -146,6 +146,10 @@ Any time you’re working with PHP, [PhpStorm](https://www.jetbrains.com/phpstor DDEV comes [pre-configured with xdebug](https://ddev.readthedocs.io/en/stable/users/debugging-profiling/step-debugging/), and can be connected to your IDE of choice to support breakpoints and step-debugging. +#### Debug Toolbar + +Yii’s built-in [debug toolbar](repo:yiisoft/yii2-debug) is invaluable, especially while troubleshooting database queries, [events](events.md), and other performance issues. + #### Composer If your journey with Craft so far has not involved [Composer](https://getcomposer.org), certain concepts (like namespacing and auto-loading) may present additional difficulty. Consider reviewing our article on using the [starter project](kb:using-the-starter-project), and try running [updates](../updating.md#composer) or installing a plugin with Composer. diff --git a/docs/4.x/extend/changelogs-and-updates.md b/docs/4.x/extend/changelogs-and-updates.md index f5a745919..75781dd59 100644 --- a/docs/4.x/extend/changelogs-and-updates.md +++ b/docs/4.x/extend/changelogs-and-updates.md @@ -2,7 +2,11 @@ When you [publish](plugin-store.md) your plugin in the Plugin Store, you will be able to specify a path to your plugin’s changelog within the repository. -If this is set to a valid changelog path, the Plugin Store will re-download your changelog on each release. Those release notes will then be displayed for your plugin on the page at **Utilities** → **Updates**. +If this is set to a valid changelog path, the Plugin Store will re-download your changelog on each release. Those release notes will then be displayed on its Plugin Store page, as well as the **Utilities** → **Updates** screen of any project it is installed in. + +::: tip +Refer to [Craft’s own changelog](https://github.com/craftcms/cms/blob/develop/CHANGELOG.md) as an example of syntax and best practices. +::: ## Setting Up a Changelog @@ -39,22 +43,22 @@ All content that follows a version heading (up to the next H2) will be treated a When writing release notes, we recommend that you follow the guidelines at [keepachangelog.com](https://keepachangelog.com/), but all forms of [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) are allowed. The only thing that is *not* allowed is actual HTML code, which will be escaped. -### Notes, Warnings, and Tips +### Alerts -You can include important notes, warnings, and tips in your release notes using this syntax: +You can include notes and warnings in your release notes using [GitHub’s alert syntax](https://github.com/orgs/community/discussions/16925): ```markdown -> **Note** -> An important note. +> [!NOTE] +> Highlights information that users should take into account, even when skimming. -> **Warning** -> A word of warning. +> [!IMPORTANT] +> Crucial information necessary for users to succeed. -> **Tip** -> A helpful tip. +> [!WARNING] +> Critical content demanding immediate user attention due to potential risks. ``` -These notes will each be styled appropriately within the plugin’s changelog in the Plugin Store and within the Updates utility. The Updates utility will also auto-expand any updates that contain a note. +These alerts will each be styled appropriately within the plugin’s changelog in the Plugin Store and within the Updates utility. Updates which contain alerts will automatically be expanded in the Updates utility. ### Links diff --git a/docs/4.x/extend/controllers.md b/docs/4.x/extend/controllers.md index 868712e31..3b8cd6b01 100644 --- a/docs/4.x/extend/controllers.md +++ b/docs/4.x/extend/controllers.md @@ -405,7 +405,7 @@ public function actionEdit(?int $id = null, ?Widget $widget = null) $widgets = MyPlugin::getInstance()->getWidgets(); // Do we have an incoming Widget ID from the route? - if ($widgetId !== null) { + if ($id !== null) { // Was a Widget model passed back via route params? It should take priority: if ($widget === null) { // Nope, let’s look it up: @@ -473,16 +473,16 @@ public function actionSave() if (!$widgets->saveWidget($widget)) { // Hand the model back to the original route: return $this->asModelFailure( - $widget, + $widget, // Model, passed back under the key, below... Craft::t('my-plugin', 'Something went wrong!'), // Flash message 'widget', // Route param key ); } return $this->asModelSuccess( - $widget, + $widget, // Model (included in JSON responses) Craft::t('my-plugin', 'Widget saved.'), // Flash message - 'widget', // Route param key + 'widget', // Key the model will be under (in JSON responses) 'my-plugin/widgets/{id}', // Redirect “object template” ); } diff --git a/docs/4.x/extend/cp-section.md b/docs/4.x/extend/cp-section.md index 7e9226af4..87cee8447 100644 --- a/docs/4.x/extend/cp-section.md +++ b/docs/4.x/extend/cp-section.md @@ -69,7 +69,7 @@ namespace mynamespace; class Plugin extends \craft\base\Plugin { - public $hasCpSection = true; + public bool $hasCpSection = true; // ... } diff --git a/docs/4.x/extend/element-types.md b/docs/4.x/extend/element-types.md index d55ac8bd5..1f6b9f376 100644 --- a/docs/4.x/extend/element-types.md +++ b/docs/4.x/extend/element-types.md @@ -144,7 +144,7 @@ use craft\helpers\Db; public function afterSave(bool $isNew) { if (!$this->propagating) { - Db::upsert('{{%products}}', [ + Db::upsert('{{%plugin_products}}', [ 'id' => $this->id, ], [ 'price' => $this->price, diff --git a/docs/4.x/extend/graphql.md b/docs/4.x/extend/graphql.md index 4f0a04cd0..d1c15a2f3 100644 --- a/docs/4.x/extend/graphql.md +++ b/docs/4.x/extend/graphql.md @@ -380,13 +380,14 @@ Event::on( ### Modifying Type Fields -Craft’s includes a `defineGqlTypeFields` event you can use to add, remove or modify fields on any GraphQL type. +Attach a handler to to add, remove or modify fields on any GraphQL type. Below we’re removing IDs throughout the schema in favor of UIDs, and adding an `authorEmail` field to the entry interface: ```php -use craft\events\DefineGqlTypeFields; +use craft\events\DefineGqlTypeFieldsEvent; use craft\gql\TypeManager; +use GraphQL\Type\Definition\Type; use yii\base\Event; Event::on( diff --git a/docs/4.x/extend/plugin-store.md b/docs/4.x/extend/plugin-store.md index 710bd213e..bf9051608 100644 --- a/docs/4.x/extend/plugin-store.md +++ b/docs/4.x/extend/plugin-store.md @@ -4,20 +4,28 @@ If you want to make your plugin available in the in-app Plugin Store, and on [pl ## Choose a License -All plugins in the Plugin Store must have one of two licenses: +All plugins in the Plugin Store must select a software license. -- **[MIT](https://opensource.org/licenses/MIT)** – Use this if you aren’t planning on ever charging for your plugin, and you’re OK with other people pretty much doing whatever they want with your code, as long as they give credit back to you. ([Example](https://github.com/craftcms/element-api/blob/v2/LICENSE.md)) -- **[Craft](https://craftcms.github.io/license/)** – Use this if you are planning on charging for your plugin, and want to prevent people from using your code without paying up. ([Example](https://github.com/craftcms/cms/blob/develop/LICENSE.md)) +Commercial plugins are recommended to use the [Craft license](https://raw.githubusercontent.com/craftcms/license/master/index.md). -Create a `LICENSE.md` file at the root of your plugin’s repository, and paste in the license text, beginning with a copyright notice. +To use the Craft license: -``` -Copyright © -``` +1. Copy the license text into a `LICENSE.md` file at the root of your repository, and replace `[YOUR_NAME_HERE]` with your personal/organization name. +2. Set the `license` value in `composer.json` to `"proprietary"`. -::: tip -If you are going with the Craft License, don’t forget to change the `license` value in your `composer.json` file from `MIT` to `proprietary`. -::: +The following open source licenses are also allowed: + +- [Apache-2.0](https://raw.githubusercontent.com/licenses/license-templates/master/templates/apache.txt) +- [GPL-2.0](https://raw.githubusercontent.com/licenses/license-templates/master/templates/gpl2.txt) +- [GPL-3.0](https://raw.githubusercontent.com/licenses/license-templates/master/templates/gpl3.txt) +- [MIT](https://raw.githubusercontent.com/licenses/license-templates/master/templates/mit.txt) + +The MIT license is generally recommended, unless you have a good reason to use something else. + +To use an open source license: + +1. Copy the license text into a `LICENSE.txt` file at the root of your repository, prefixed with a copyright notice (e.g. `Copyright (c) Pixel & Tonic, Inc.`). +2. Set the `license` value in `composer.json` to the appropriate [license name](https://getcomposer.org/doc/04-schema.md#license). ## Registering your Plugin diff --git a/docs/4.x/extend/queue-jobs.md b/docs/4.x/extend/queue-jobs.md index d9f85fc7c..ea17c0074 100644 --- a/docs/4.x/extend/queue-jobs.md +++ b/docs/4.x/extend/queue-jobs.md @@ -103,11 +103,11 @@ public function execute($queue): void ### Dealing with Failed Jobs -In our first example, exceptions from the mailer can bubble out of our job—but in the second example, we’re to ensuring the job is not halted prematurely. +In our first example, exceptions from the mailer can bubble out of our job—but in the second example, we catch those errors so the job is not halted prematurely. This decision is up to you: if the work in a job is nonessential (or will be done again later, like ), you can catch and log errors and let the job end nominally; if the work is critical (like synchronizing something to an external API), it may be better to let the exception bubble out of `execute()`. -The queue wraps every job in its own `try` block, and will flag any jobs that generate exceptions as failed. The exception message that caused the failure will be recorded along with the job. Failed jobs can be retried from the control panel or with the `php craft queue/retry [id]` command. +The queue wraps every job in its own `try` block, and will mark any jobs that throw exceptions as _failed_. The exception message that caused the failure will be recorded along with the job. Failed jobs can be retried from the control panel or with the `php craft queue/retry [id]` command. #### Retryable Jobs diff --git a/docs/4.x/extend/utilities.md b/docs/4.x/extend/utilities.md index 05b01b5bb..1c2bf860a 100644 --- a/docs/4.x/extend/utilities.md +++ b/docs/4.x/extend/utilities.md @@ -64,7 +64,7 @@ You may also implement static `toolbarHtml()` and `footerHtml()` methods to inje Each utility automatically gets its own [permission](user-permissions.md). Craft checks these permissions before displaying a utility in the sidebar, and when the utility’s URL is requested. -However, those permissions do _not_ have any bearing on what functionality might be accessible to a user via other means. For example, if your utility displayed a form to authorized users and allowed them to download a specialized report of some kind, the [controller](controllers.md) or action that ultimately generates the report must also check the appropriate permissions. +However, those permissions do _not_ have any bearing on what functionality might be accessible to a user via other means. For example, if your utility displayed a form to authorized users and allowed them to download a specialized report of some kind, the [controller](controllers.md) or action that ultimately generates the report must also check the appropriate permissions. In general, those permissions should be discrete: an administrator would grant users access to the utility _and_ a _Modify Widgets_ permission that your plugin explicitly defines (and checks in the appropriate controller action). ## Registering your Utility diff --git a/docs/4.x/fields.md b/docs/4.x/fields.md index a1ff8e909..06311fe82 100644 --- a/docs/4.x/fields.md +++ b/docs/4.x/fields.md @@ -16,7 +16,6 @@ All fields share a few settings: - **Instructions** – Instruction text to guide authors; - **Field Type** – What [type](#field-types) of field it is; - @@ -37,6 +36,7 @@ Type | Description [Categories](categories-fields.md) | Attach category elements. [Checkboxes](checkboxes-fields.md) | Select any number of values from a list. [Color](color-fields.md) | Choose a color with the browser’s color picker UI. +[Countries](country-fields.md) | Select from a list of countries available in [address](addresses.md) elements. [Date](date-time-fields.md) | Choose a date and/or time, as well as a timezone. [Dropdown](dropdown-fields.md) | Choose one value from a list. [Email](email-fields.md) | Validate text input as an email address. diff --git a/docs/4.x/globals.md b/docs/4.x/globals.md index 4bb9b0973..77f31ab60 100644 --- a/docs/4.x/globals.md +++ b/docs/4.x/globals.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Globals Globals store content that is available globally throughout your templates but is not tied to any one URL. @@ -116,755 +120,5 @@ All global sets are already available as global variables to Twig templates. So Global set queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only global sets that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](craft4:craft\elements\GlobalSet) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [collect](#collect) | -| [dateCreated](#datecreated) | Narrows the query results based on the global sets’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the global sets’ last-updated dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [handle](#handle) | Narrows the query results based on the global sets’ handles. -| [id](#id) | Narrows the query results based on the global sets’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [limit](#limit) | Determines the number of global sets that should be returned. -| [offset](#offset) | Determines how many global sets should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the global sets should be returned in. (If empty, defaults to `sortOrder ASC`.) -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [relatedTo](#relatedto) | Narrows the query results to only global sets that are related to certain other elements. -| [search](#search) | Narrows the query results to only global sets that match a search query. -| [site](#site) | Determines which site(s) the global sets should be queried in. -| [siteId](#siteid) | Determines which site(s) the global sets should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the global sets’ IDs in the `elements_sites` table. -| [trashed](#trashed) | Narrows the query results to only global sets that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the global sets’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [with](#with) | Causes the query to return matching global sets eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only global sets that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all global sets that are related to myCategoryA and myCategoryB #} -{% set globalSets = craft.globalSets() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all global sets that are related to $myCategoryA and $myCategoryB -$globalSets = \craft\elements\GlobalSet::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching global sets as arrays of data, rather than [GlobalSet](craft4:craft\elements\GlobalSet) objects. - - - - - -::: code -```twig -{# Fetch global sets as arrays #} -{% set globalSets = craft.globalSets() - .asArray() - .all() %} -``` - -```php -// Fetch global sets as arrays -$globalSets = \craft\elements\GlobalSet::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `collect` - - - - - - - - -#### `dateCreated` - -Narrows the query results based on the global sets’ creation dates. - - - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch global sets created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set globalSets = craft.globalSets() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch global sets created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$globalSets = \craft\elements\GlobalSet::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the global sets’ last-updated dates. - - - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch global sets updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set globalSets = craft.globalSets() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch global sets updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$globalSets = \craft\elements\GlobalSet::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch global sets in a specific order #} -{% set globalSets = craft.globalSets() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch global sets in a specific order -$globalSets = \craft\elements\GlobalSet::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `handle` - -Narrows the query results based on the global sets’ handles. - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `'foo'` | with a handle of `foo`. -| `'not foo'` | not with a handle of `foo`. -| `['foo', 'bar']` | with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not with a handle of `foo` or `bar`. - - - -::: code -```twig -{# Fetch the global set with a handle of 'foo' #} -{% set globalSet = craft.globalSets() - .handle('foo') - .one() %} -``` - -```php -// Fetch the global set with a handle of 'foo' -$globalSet = \craft\elements\GlobalSet::find() - ->handle('foo') - ->one(); -``` -::: - - -#### `id` - -Narrows the query results based on the global sets’ IDs. - - - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the global set by its ID #} -{% set globalSet = craft.globalSets() - .id(1) - .one() %} -``` - -```php -// Fetch the global set by its ID -$globalSet = \craft\elements\GlobalSet::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching global sets as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch global sets in reverse #} -{% set globalSets = craft.globalSets() - .inReverse() - .all() %} -``` - -```php -// Fetch global sets in reverse -$globalSets = \craft\elements\GlobalSet::find() - ->inReverse() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of global sets that should be returned. - - - -::: code -```twig -{# Fetch up to 10 global sets #} -{% set globalSets = craft.globalSets() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 global sets -$globalSets = \craft\elements\GlobalSet::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many global sets should be skipped in the results. - - - -::: code -```twig -{# Fetch all global sets except for the first 3 #} -{% set globalSets = craft.globalSets() - .offset(3) - .all() %} -``` - -```php -// Fetch all global sets except for the first 3 -$globalSets = \craft\elements\GlobalSet::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the global sets should be returned in. (If empty, defaults to `sortOrder ASC`.) - - - -::: code -```twig -{# Fetch all global sets in order of date created #} -{% set globalSets = craft.globalSets() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all global sets in order of date created -$globalSets = \craft\elements\GlobalSet::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique global sets from Site A, or Site B if they don’t exist in Site A #} -{% set globalSets = craft.globalSets() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique global sets from Site A, or Site B if they don’t exist in Site A -$globalSets = \craft\elements\GlobalSet::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `relatedTo` - -Narrows the query results to only global sets that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all global sets that are related to myCategory #} -{% set globalSets = craft.globalSets() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all global sets that are related to $myCategory -$globalSets = \craft\elements\GlobalSet::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only global sets that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all global sets that match the search query #} -{% set globalSets = craft.globalSets() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all global sets that match the search query -$globalSets = \craft\elements\GlobalSet::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the global sets should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch global sets from the Foo site #} -{% set globalSets = craft.globalSets() - .site('foo') - .all() %} -``` - -```php -// Fetch global sets from the Foo site -$globalSets = \craft\elements\GlobalSet::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the global sets should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch global sets from the site with an ID of 1 #} -{% set globalSets = craft.globalSets() - .siteId(1) - .all() %} -``` - -```php -// Fetch global sets from the site with an ID of 1 -$globalSets = \craft\elements\GlobalSet::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the global sets’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches global sets… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the global set by its ID in the elements_sites table #} -{% set globalSet = craft.globalSets() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the global set by its ID in the elements_sites table -$globalSet = \craft\elements\GlobalSet::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `trashed` - -Narrows the query results to only global sets that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed global sets #} -{% set globalSets = craft.globalSets() - .trashed() - .all() %} -``` - -```php -// Fetch trashed global sets -$globalSets = \craft\elements\GlobalSet::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the global sets’ UIDs. - - - - - -::: code -```twig -{# Fetch the global set by its UID #} -{% set globalSet = craft.globalSets() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the global set by its UID -$globalSet = \craft\elements\GlobalSet::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique global sets across all sites #} -{% set globalSets = craft.globalSets() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique global sets across all sites -$globalSets = \craft\elements\GlobalSet::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching global sets eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch global sets eager-loaded with the "Related" field’s relations #} -{% set globalSets = craft.globalSets() - .with(['related']) - .all() %} -``` - -```php -// Fetch global sets eager-loaded with the "Related" field’s relations -$globalSets = \craft\elements\GlobalSet::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/4.x/globals.md)!!! diff --git a/docs/4.x/graphql.md b/docs/4.x/graphql.md index b5c7ae174..6656a9347 100644 --- a/docs/4.x/graphql.md +++ b/docs/4.x/graphql.md @@ -1,5 +1,6 @@ --- keywords: headless +containsGeneratedContent: yes --- # GraphQL API Pro @@ -176,7 +177,7 @@ You can manage your schemas in the control panel at **GraphQL** → **Schemas**. ### Using the GraphiQL IDE -The easiest way to start exploring your GraphQL API is with the built-in [GraphiQL](https://github.com/graphql/graphiql) IDE, which is available in the control panel from **GraphQL** → **Explore**. +The easiest way to start exploring your GraphQL API is with the built-in [GraphiQL](https://github.com/graphql/graphiql) IDE, which is available in the control panel from **GraphQL** → **GraphiQL**. ![The built-in GraphiQL IDE](./images/graphiql.png) @@ -1459,6 +1460,7 @@ This is the interface implemented by all users. | `status`| `String` | The element’s status. | `dateCreated`| `DateTime` | The date the element was created. | `dateUpdated`| `DateTime` | The date the element was last updated. +| `photo`| `AssetInterface` | The user’s photo. | `friendlyName`| `String` | The user’s first name or username. | `fullName`| `String` | The user’s full name. | `name`| `String!` | The user’s full name or username. diff --git a/docs/4.x/installation.md b/docs/4.x/installation.md index 191723820..8b343028a 100644 --- a/docs/4.x/installation.md +++ b/docs/4.x/installation.md @@ -2,7 +2,7 @@ The prevalence of modern, mature PHP development tools and infrastructure makes Craft easy to install, run, [upgrade](./upgrade.md), and [deploy](./deployment.md). -This [quick-start](#quick-start) guide focuses solely on setting up a local Craft development environment. +This [quick-start](#quick-start) guide focuses solely on setting up a local Craft development environment. If you’re ready to launch, jump to the [hosting](#hosting) or [deployment](#deployment) section. ::: tip If at any point you feel stuck, the [Tutorial](../getting-started-tutorial/README.md) is a comprehensive guide for _anyone_ who wants to get set up with a fast, reliable development environment. @@ -78,7 +78,7 @@ Done for the day? [`ddev stop`](https://ddev.readthedocs.io/en/stable/users/basi ### Workflow + Collaboration -We encourage starting with a local development environment (rather than a remote host) as a means of of a defined workflow—whatever it may be—to the reliability and longevity of a website. +We believe that starting with a local development environment (rather than directly on a remote server) fosters a workflow that will support the reliability and longevity of your project. diff --git a/docs/4.x/matrix-blocks.md b/docs/4.x/matrix-blocks.md index 21609d879..ab7bc3898 100644 --- a/docs/4.x/matrix-blocks.md +++ b/docs/4.x/matrix-blocks.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Matrix Blocks If you’ve ever worked with a hairball of content and markup managed in an increasingly-fragile WYSIWYG field, you’re probably going to like Matrix blocks. @@ -58,1034 +62,5 @@ In order for the returned Matrix block(s) to be populated with their custom fiel Matrix block queries support the following parameters: - - - - - - -| Param | Description -| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [allowOwnerDrafts](#allowownerdrafts) | Narrows the query results based on whether the Matrix blocks’ owners are drafts. -| [allowOwnerRevisions](#allowownerrevisions) | Narrows the query results based on whether the Matrix blocks’ owners are revisions. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](craft4:craft\elements\MatrixBlock) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [collect](#collect) | -| [dateCreated](#datecreated) | Narrows the query results based on the Matrix blocks’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the Matrix blocks’ last-updated dates. -| [field](#field) | Narrows the query results based on the field the Matrix blocks belong to. -| [fieldId](#fieldid) | Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [id](#id) | Narrows the query results based on the Matrix blocks’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [limit](#limit) | Determines the number of Matrix blocks that should be returned. -| [offset](#offset) | Determines how many Matrix blocks should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) -| [owner](#owner) | Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. -| [ownerId](#ownerid) | Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [primaryOwner](#primaryowner) | Sets the [primaryOwnerId](#primaryownerid) and [siteId](#siteid) parameters based on a given element. -| [primaryOwnerId](#primaryownerid) | Narrows the query results based on the primary owner element of the Matrix blocks, per the owners’ IDs. -| [relatedTo](#relatedto) | Narrows the query results to only Matrix blocks that are related to certain other elements. -| [search](#search) | Narrows the query results to only Matrix blocks that match a search query. -| [site](#site) | Determines which site(s) the Matrix blocks should be queried in. -| [siteId](#siteid) | Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the Matrix blocks’ IDs in the `elements_sites` table. -| [status](#status) | Narrows the query results based on the Matrix blocks’ statuses. -| [trashed](#trashed) | Narrows the query results to only Matrix blocks that have been soft-deleted. -| [type](#type) | Narrows the query results based on the Matrix blocks’ block types. -| [typeId](#typeid) | Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. -| [uid](#uid) | Narrows the query results based on the Matrix blocks’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [with](#with) | Causes the query to return matching Matrix blocks eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `allowOwnerDrafts` - -Narrows the query results based on whether the Matrix blocks’ owners are drafts. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `true` | which can belong to a draft. -| `false` | which cannot belong to a draft. - - - - -#### `allowOwnerRevisions` - -Narrows the query results based on whether the Matrix blocks’ owners are revisions. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `true` | which can belong to a revision. -| `false` | which cannot belong to a revision. - - - - -#### `andRelatedTo` - -Narrows the query results to only Matrix blocks that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all Matrix blocks that are related to myCategoryA and myCategoryB #} -{% set MatrixBlocks = craft.matrixBlocks() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all Matrix blocks that are related to $myCategoryA and $myCategoryB -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching Matrix blocks as arrays of data, rather than [MatrixBlock](craft4:craft\elements\MatrixBlock) objects. - - - - - -::: code -```twig -{# Fetch Matrix blocks as arrays #} -{% set MatrixBlocks = craft.matrixBlocks() - .asArray() - .all() %} -``` - -```php -// Fetch Matrix blocks as arrays -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `collect` - - - - - - - - -#### `dateCreated` - -Narrows the query results based on the Matrix blocks’ creation dates. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch Matrix blocks created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set MatrixBlocks = craft.matrixBlocks() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch Matrix blocks created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the Matrix blocks’ last-updated dates. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch Matrix blocks updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set MatrixBlocks = craft.matrixBlocks() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch Matrix blocks updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `field` - -Narrows the query results based on the field the Matrix blocks belong to. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'foo'` | in a field with a handle of `foo`. -| `'not foo'` | not in a field with a handle of `foo`. -| `['foo', 'bar']` | in a field with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a field with a handle of `foo` or `bar`. -| a [craft\fields\Matrix](craft4:craft\fields\Matrix) object | in a field represented by the object. - - - -::: code -```twig -{# Fetch Matrix blocks in the Foo field #} -{% set MatrixBlocks = craft.matrixBlocks() - .field('foo') - .all() %} -``` - -```php -// Fetch Matrix blocks in the Foo field -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->field('foo') - ->all(); -``` -::: - - -#### `fieldId` - -Narrows the query results based on the field the Matrix blocks belong to, per the fields’ IDs. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | in a field with an ID of 1. -| `'not 1'` | not in a field with an ID of 1. -| `[1, 2]` | in a field with an ID of 1 or 2. -| `['not', 1, 2]` | not in a field with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch Matrix blocks in the field with an ID of 1 #} -{% set MatrixBlocks = craft.matrixBlocks() - .fieldId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks in the field with an ID of 1 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->fieldId(1) - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch Matrix blocks in a specific order #} -{% set MatrixBlocks = craft.matrixBlocks() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch Matrix blocks in a specific order -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the Matrix blocks’ IDs. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the Matrix block by its ID #} -{% set MatrixBlock = craft.matrixBlocks() - .id(1) - .one() %} -``` - -```php -// Fetch the Matrix block by its ID -$MatrixBlock = \craft\elements\MatrixBlock::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching Matrix blocks as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch Matrix blocks in reverse #} -{% set MatrixBlocks = craft.matrixBlocks() - .inReverse() - .all() %} -``` - -```php -// Fetch Matrix blocks in reverse -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->inReverse() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of Matrix blocks that should be returned. - - - -::: code -```twig -{# Fetch up to 10 Matrix blocks #} -{% set MatrixBlocks = craft.matrixBlocks() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 Matrix blocks -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many Matrix blocks should be skipped in the results. - - - -::: code -```twig -{# Fetch all Matrix blocks except for the first 3 #} -{% set MatrixBlocks = craft.matrixBlocks() - .offset(3) - .all() %} -``` - -```php -// Fetch all Matrix blocks except for the first 3 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the Matrix blocks should be returned in. (If empty, defaults to `sortOrder ASC`.) - - - -::: code -```twig -{# Fetch all Matrix blocks in order of date created #} -{% set MatrixBlocks = craft.matrixBlocks() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all Matrix blocks in order of date created -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `owner` - -Sets the [ownerId](#ownerid) and [siteId](#siteid) parameters based on a given element. - - - -::: code -```twig -{# Fetch Matrix blocks created for this entry #} -{% set MatrixBlocks = craft.matrixBlocks() - .owner(myEntry) - .all() %} -``` - -```php -// Fetch Matrix blocks created for this entry -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->owner($myEntry) - ->all(); -``` -::: - - -#### `ownerId` - -Narrows the query results based on the owner element of the Matrix blocks, per the owners’ IDs. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | created for an element with an ID of 1. -| `'not 1'` | not created for an element with an ID of 1. -| `[1, 2]` | created for an element with an ID of 1 or 2. -| `['not', 1, 2]` | not created for an element with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch Matrix blocks created for an element with an ID of 1 #} -{% set MatrixBlocks = craft.matrixBlocks() - .ownerId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks created for an element with an ID of 1 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->ownerId(1) - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique Matrix blocks from Site A, or Site B if they don’t exist in Site A #} -{% set MatrixBlocks = craft.matrixBlocks() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique Matrix blocks from Site A, or Site B if they don’t exist in Site A -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `primaryOwner` - -Sets the [primaryOwnerId](#primaryownerid) and [siteId](#siteid) parameters based on a given element. - - - -::: code -```twig -{# Fetch Matrix blocks created for this entry #} -{% set MatrixBlocks = craft.matrixBlocks() - .primaryOwner(myEntry) - .all() %} -``` - -```php -// Fetch Matrix blocks created for this entry -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->primaryOwner($myEntry) - ->all(); -``` -::: - - -#### `primaryOwnerId` - -Narrows the query results based on the primary owner element of the Matrix blocks, per the owners’ IDs. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | created for an element with an ID of 1. -| `'not 1'` | not created for an element with an ID of 1. -| `[1, 2]` | created for an element with an ID of 1 or 2. -| `['not', 1, 2]` | not created for an element with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch Matrix blocks created for an element with an ID of 1 #} -{% set MatrixBlocks = craft.matrixBlocks() - .primaryOwnerId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks created for an element with an ID of 1 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->primaryOwnerId(1) - ->all(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only Matrix blocks that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all Matrix blocks that are related to myCategory #} -{% set MatrixBlocks = craft.matrixBlocks() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all Matrix blocks that are related to $myCategory -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only Matrix blocks that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all Matrix blocks that match the search query #} -{% set MatrixBlocks = craft.matrixBlocks() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all Matrix blocks that match the search query -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the Matrix blocks should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch Matrix blocks from the Foo site #} -{% set MatrixBlocks = craft.matrixBlocks() - .site('foo') - .all() %} -``` - -```php -// Fetch Matrix blocks from the Foo site -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the Matrix blocks should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch Matrix blocks from the site with an ID of 1 #} -{% set MatrixBlocks = craft.matrixBlocks() - .siteId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks from the site with an ID of 1 -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the Matrix blocks’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the Matrix block by its ID in the elements_sites table #} -{% set MatrixBlock = craft.matrixBlocks() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the Matrix block by its ID in the elements_sites table -$MatrixBlock = \craft\elements\MatrixBlock::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the Matrix blocks’ statuses. - - - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'enabled'` _(default)_ | that are enabled. -| `'disabled'` | that are disabled. -| `['not', 'disabled']` | that are not disabled. - - - -::: code -```twig -{# Fetch disabled Matrix blocks #} -{% set MatrixBlocks = craft.matrixBlocks() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled Matrix blocks -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->status('disabled') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only Matrix blocks that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed Matrix blocks #} -{% set MatrixBlocks = craft.matrixBlocks() - .trashed() - .all() %} -``` - -```php -// Fetch trashed Matrix blocks -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->trashed() - ->all(); -``` -::: - - -#### `type` - -Narrows the query results based on the Matrix blocks’ block types. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `'foo'` | of a type with a handle of `foo`. -| `'not foo'` | not of a type with a handle of `foo`. -| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. -| an [MatrixBlockType](craft4:craft\models\MatrixBlockType) object | of a type represented by the object. - - - -::: code -```twig -{# Fetch Matrix blocks with a Foo block type #} -{% set MatrixBlocks = myEntry.myMatrixField - .type('foo') - .all() %} -``` - -```php -// Fetch Matrix blocks with a Foo block type -$MatrixBlocks = $myEntry->myMatrixField - ->type('foo') - ->all(); -``` -::: - - -#### `typeId` - -Narrows the query results based on the Matrix blocks’ block types, per the types’ IDs. - -Possible values include: - -| Value | Fetches Matrix blocks… -| - | - -| `1` | of a type with an ID of 1. -| `'not 1'` | not of a type with an ID of 1. -| `[1, 2]` | of a type with an ID of 1 or 2. -| `['not', 1, 2]` | not of a type with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch Matrix blocks of the block type with an ID of 1 #} -{% set MatrixBlocks = myEntry.myMatrixField - .typeId(1) - .all() %} -``` - -```php -// Fetch Matrix blocks of the block type with an ID of 1 -$MatrixBlocks = $myEntry->myMatrixField - ->typeId(1) - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the Matrix blocks’ UIDs. - - - - - -::: code -```twig -{# Fetch the Matrix block by its UID #} -{% set MatrixBlock = craft.matrixBlocks() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the Matrix block by its UID -$MatrixBlock = \craft\elements\MatrixBlock::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique Matrix blocks across all sites #} -{% set MatrixBlocks = craft.matrixBlocks() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique Matrix blocks across all sites -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching Matrix blocks eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch Matrix blocks eager-loaded with the "Related" field’s relations #} -{% set MatrixBlocks = craft.matrixBlocks() - .with(['related']) - .all() %} -``` - -```php -// Fetch Matrix blocks eager-loaded with the "Related" field’s relations -$MatrixBlocks = \craft\elements\MatrixBlock::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/4.x/matrix-blocks.md)!!! diff --git a/docs/4.x/matrix-fields.md b/docs/4.x/matrix-fields.md index 0686a93b3..fb82df018 100644 --- a/docs/4.x/matrix-fields.md +++ b/docs/4.x/matrix-fields.md @@ -7,8 +7,8 @@ Matrix fields allow you to create multiple blocks of content within a single fie Matrix fields have the following settings: - **Configuration** – This is where you configure which block types should be available to your Matrix field, and which sub-fields each of those block types should have. -- **Min Blocks** – The minimum number of blocks that can be created within the field. (Default is no limit.) -- **Max Blocks** – The maximum number of blocks that can be created within the field. (Default is no limit.) +- **Min Blocks** – The _minimum_ number of blocks that can be created within the field. (Default is no lower limit.) +- **Max Blocks** – The _maximum_ number of blocks that can be created within the field. (Default is no upper limit.) ## The Field @@ -370,7 +370,7 @@ Instead, we’ll try three values: 1. Attempt to use the field value as an element query (load the blocks fresh, assuming there are no pending changes hanging in-memory); 1. Accept the value, verbatim (assuming Craft has left the in-memory blocks attached, and they _don’t_ need to be queried); -1. Default to an empty array (this fallback ensures) +1. Default to an empty array (this ensures whatever uses the `blocks` variable later on can safely assume it’s an array); ```twig {% set blocks = entry.myFieldHandle.all() ?? entry.myFieldHandle ?? [] %} diff --git a/docs/4.x/searching.md b/docs/4.x/searching.md index b133cdff7..d3b4245ba 100644 --- a/docs/4.x/searching.md +++ b/docs/4.x/searching.md @@ -273,7 +273,7 @@ You can configure any [custom field](./fields.md) to make its content available ![Searchable Checkbox](./images/searchable-checkbox.png) -Indexes are only updated once an element with the field is saved, though. If you have a large amount of content and users (admin or otherwise) rely heavily on search, consider [resaving the elements](#rebuilding-your-search-indexes) to populate the index. +Indexes are only updated once an element with the field is saved. If you have a large amount of content and users (admin or otherwise) rely heavily on search, consider [resaving the elements](#rebuilding-your-search-indexes) to populate the index. ::: tip For Matrix fields, the top-level **Use this field’s values as search keywords** setting determines whether _any_ sub-fields will factor into results for the parent—individual fields must also opt-in to indexing for any keywords to be bubbled up. @@ -281,6 +281,12 @@ For Matrix fields, the top-level **Use this field’s values as search keywords* For relational fields like [Assets](./assets-fields.md), [Categories](./categories-fields.md), and [Entries](./entries-fields.md), the setting determines whether titles of related elements should factor into search results. ::: +## Indexing Criteria + +Any time an indexable attribute or field on an element is updated (as indicated by Craft’s change-tracking feature, which powers drafts and revisions), an “Updating search indexes” job is pushed into the queue. Prior versions generate an indexing job whenever an element with _any_ searchable attributes or fields is saved, regardless of whether or not those specific attributes changed. + +The [eligible properties](#searching-for-specific-element-attributes) differ for each element type, the field layout a given element uses, and which of the underlying fields are flagged as searchable. + ## Rebuilding Your Search Indexes Craft does its best to keep its search indexes as up-to-date as possible, but there are a couple things that might render portions of them inaccurate. If you suspect your search indexes are out of date, you can have Craft rebuild them by bulk-resaving entries with the [`resave/entries`](console-commands.md#resave) command and including the `--update-search-index` flag: diff --git a/docs/4.x/tags.md b/docs/4.x/tags.md index 62b149c6e..b3e6fa629 100644 --- a/docs/4.x/tags.md +++ b/docs/4.x/tags.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Tags You can create folksonomies for your [entries](entries.md), [users](users.md), and [assets](assets.md) using Tags. Tags are another type of [element](./elements.md). @@ -88,871 +92,5 @@ We can display a list of the tags in a “Blog Tags” tag group by doing the fo Tag queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only tags that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching tags as arrays of data, rather than [Tag](craft4:craft\elements\Tag) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [collect](#collect) | -| [dateCreated](#datecreated) | Narrows the query results based on the tags’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the tags’ last-updated dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [group](#group) | Narrows the query results based on the tag groups the tags belong to. -| [groupId](#groupid) | Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. -| [id](#id) | Narrows the query results based on the tags’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [limit](#limit) | Determines the number of tags that should be returned. -| [offset](#offset) | Determines how many tags should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) -| [preferSites](#prefersites) | If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [relatedTo](#relatedto) | Narrows the query results to only tags that are related to certain other elements. -| [search](#search) | Narrows the query results to only tags that match a search query. -| [site](#site) | Determines which site(s) the tags should be queried in. -| [siteId](#siteid) | Determines which site(s) the tags should be queried in, per the site’s ID. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the tags’ IDs in the `elements_sites` table. -| [title](#title) | Narrows the query results based on the tags’ titles. -| [trashed](#trashed) | Narrows the query results to only tags that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the tags’ UIDs. -| [unique](#unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uri](#uri) | Narrows the query results based on the tags’ URIs. -| [with](#with) | Causes the query to return matching tags eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only tags that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all tags that are related to myCategoryA and myCategoryB #} -{% set tags = craft.tags() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all tags that are related to $myCategoryA and $myCategoryB -$tags = \craft\elements\Tag::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching tags as arrays of data, rather than [Tag](craft4:craft\elements\Tag) objects. - - - - - -::: code -```twig -{# Fetch tags as arrays #} -{% set tags = craft.tags() - .asArray() - .all() %} -``` - -```php -// Fetch tags as arrays -$tags = \craft\elements\Tag::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `collect` - - - - - - - - -#### `dateCreated` - -Narrows the query results based on the tags’ creation dates. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch tags created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set tags = craft.tags() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch tags created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$tags = \craft\elements\Tag::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the tags’ last-updated dates. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch tags updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set tags = craft.tags() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch tags updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$tags = \craft\elements\Tag::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch tags in a specific order #} -{% set tags = craft.tags() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch tags in a specific order -$tags = \craft\elements\Tag::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `group` - -Narrows the query results based on the tag groups the tags belong to. - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'foo'` | in a group with a handle of `foo`. -| `'not foo'` | not in a group with a handle of `foo`. -| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. -| a [TagGroup](craft4:craft\models\TagGroup) object | in a group represented by the object. - - - -::: code -```twig -{# Fetch tags in the Foo group #} -{% set tags = craft.tags() - .group('foo') - .all() %} -``` - -```php -// Fetch tags in the Foo group -$tags = \craft\elements\Tag::find() - ->group('foo') - ->all(); -``` -::: - - -#### `groupId` - -Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. - -Possible values include: - -| Value | Fetches tags… -| - | - -| `1` | in a group with an ID of 1. -| `'not 1'` | not in a group with an ID of 1. -| `[1, 2]` | in a group with an ID of 1 or 2. -| `['not', 1, 2]` | not in a group with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch tags in the group with an ID of 1 #} -{% set tags = craft.tags() - .groupId(1) - .all() %} -``` - -```php -// Fetch tags in the group with an ID of 1 -$tags = \craft\elements\Tag::find() - ->groupId(1) - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the tags’ IDs. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the tag by its ID #} -{% set tag = craft.tags() - .id(1) - .one() %} -``` - -```php -// Fetch the tag by its ID -$tag = \craft\elements\Tag::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch tags in reverse #} -{% set tags = craft.tags() - .inReverse() - .all() %} -``` - -```php -// Fetch tags in reverse -$tags = \craft\elements\Tag::find() - ->inReverse() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of tags that should be returned. - - - -::: code -```twig -{# Fetch up to 10 tags #} -{% set tags = craft.tags() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 tags -$tags = \craft\elements\Tag::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many tags should be skipped in the results. - - - -::: code -```twig -{# Fetch all tags except for the first 3 #} -{% set tags = craft.tags() - .offset(3) - .all() %} -``` - -```php -// Fetch all tags except for the first 3 -$tags = \craft\elements\Tag::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the tags should be returned in. (If empty, defaults to `title ASC`.) - - - -::: code -```twig -{# Fetch all tags in order of date created #} -{% set tags = craft.tags() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all tags in order of date created -$tags = \craft\elements\Tag::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique tags from Site A, or Site B if they don’t exist in Site A #} -{% set tags = craft.tags() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique tags from Site A, or Site B if they don’t exist in Site A -$tags = \craft\elements\Tag::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `relatedTo` - -Narrows the query results to only tags that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all tags that are related to myCategory #} -{% set tags = craft.tags() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all tags that are related to $myCategory -$tags = \craft\elements\Tag::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only tags that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all tags that match the search query #} -{% set tags = craft.tags() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all tags that match the search query -$tags = \craft\elements\Tag::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `site` - -Determines which site(s) the tags should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](craft4:craft\models\Site) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch tags from the Foo site #} -{% set tags = craft.tags() - .site('foo') - .all() %} -``` - -```php -// Fetch tags from the Foo site -$tags = \craft\elements\Tag::find() - ->site('foo') - ->all(); -``` -::: - - -#### `siteId` - -Determines which site(s) the tags should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches tags… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch tags from the site with an ID of 1 #} -{% set tags = craft.tags() - .siteId(1) - .all() %} -``` - -```php -// Fetch tags from the site with an ID of 1 -$tags = \craft\elements\Tag::find() - ->siteId(1) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the tags’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the tag by its ID in the elements_sites table #} -{% set tag = craft.tags() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the tag by its ID in the elements_sites table -$tag = \craft\elements\Tag::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `title` - -Narrows the query results based on the tags’ titles. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch tags with a title that contains "Foo" #} -{% set tags = craft.tags() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch tags with a title that contains "Foo" -$tags = \craft\elements\Tag::find() - ->title('*Foo*') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only tags that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed tags #} -{% set tags = craft.tags() - .trashed() - .all() %} -``` - -```php -// Fetch trashed tags -$tags = \craft\elements\Tag::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the tags’ UIDs. - - - - - -::: code -```twig -{# Fetch the tag by its UID #} -{% set tag = craft.tags() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the tag by its UID -$tag = \craft\elements\Tag::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique tags across all sites #} -{% set tags = craft.tags() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique tags across all sites -$tags = \craft\elements\Tag::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -#### `uri` - -Narrows the query results based on the tags’ URIs. - - - -Possible values include: - -| Value | Fetches tags… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the tag with that URI #} -{% set tag = craft.tags() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the tag with that URI -$tag = \craft\elements\Tag::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching tags eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch tags eager-loaded with the "Related" field’s relations #} -{% set tags = craft.tags() - .with(['related']) - .all() %} -``` - -```php -// Fetch tags eager-loaded with the "Related" field’s relations -$tags = \craft\elements\Tag::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/4.x/tags.md)!!! diff --git a/docs/4.x/updating.md b/docs/4.x/updating.md index c508251d0..b260016f4 100644 --- a/docs/4.x/updating.md +++ b/docs/4.x/updating.md @@ -78,7 +78,7 @@ If you have used the Craft CLI in the past, `composer update` may do nothing! Open `composer.json`, and look at the packages under the `require` key—if you see exact version numbers, Composer will never update those packages. ::: -Keep in mind that manually altering constraints _can_ lead to an irreconcilable set of packages—Composer will let you know about this before updating the lockfile. Generally speaking, the “major-version” constraints set automatically when using `composer require` should continue to work, while protecting your project from +Keep in mind that manually altering constraints _can_ lead to an irreconcilable set of packages—Composer will let you know about this before updating the lockfile. Generally speaking, the “major-version” constraints set automatically when using `composer require` should continue to work, while protecting your project from breaking changes in dependencies. ## Workflow diff --git a/docs/4.x/user-management.md b/docs/4.x/user-management.md index 1394b9282..87589788f 100644 --- a/docs/4.x/user-management.md +++ b/docs/4.x/user-management.md @@ -25,9 +25,9 @@ Considering how much damage an admin can do, we strongly advise caution when cre If you have Craft Pro, you can create User Groups to help organize your site’s user accounts, as well as batch-set permissions on them. -To create a new User Group, go to **Settings** → **Users** and press **+ New user group**. You can give your group a Name and Handle, plus any permissions you want every user within the group to have. +To create a new User Group, go to **Settings** → **Users** and press **+ New user group**. You can give your group a **Name** and **Handle**, plus any **Permissions** you want every user within the group to have. -After you create your groups, you can assign users to groups by going into their account settings and choosing the Permissions tab. +After you create your groups, you can assign users to groups by going into their account settings and choosing the **Permissions** tab. ## Permissions @@ -97,11 +97,10 @@ The permissions Craft comes with are: | ↳  Find and Replace | `utility:find-replace` | ↳  Migrations | `utility:migrations` -You may not see all of these options, initially—only ones that are relevant based on the current content schema will be displayed. For example, everything under _View categories_ will be hidden until you have at least one category group. +You may not see all of these options, initially—only ones that are relevant based on the current content schema will be displayed. For example, everything under _View categories_ will be hidden until you have at least one [category group](categories.md#category-groups). Plugins may register their own permissions, which can appear in a top-level group, under _Access the control panel_, or within _Utilities_. - ::: tip See the _Extending Craft_ [User Permissions](extend/user-permissions.md) page to learn how to register custom permissions from your module or plugin. ::: diff --git a/docs/4.x/users.md b/docs/4.x/users.md index 0f17efbd6..a77827d40 100644 --- a/docs/4.x/users.md +++ b/docs/4.x/users.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Users Users are Craft’s representation of people. @@ -26,7 +30,7 @@ You can’t create an inactive user from the control panel, but you can deactiva ### Addresses -Users each have an address book. [Addresses](./addresses.md) can be managed on behalf of a User via the control panel, or [by the user themselves](./dev/controller-actions.md#post-users-save-address). +Users each have an address book. [Addresses](./addresses.md) can be managed on behalf of a user via the control panel, or [by the user themselves](./dev/controller-actions.md#post-users-save-address). ## Querying Users @@ -78,1070 +82,5 @@ We can display a list of the users in an “Authors” user group by doing the f User queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [admin](#admin) | Narrows the query results to only users that have admin accounts. -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only users that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching users as arrays of data, rather than [User](craft4:craft\elements\User) objects. -| [assetUploaders](#assetuploaders) | Narrows the query results to only users that have uploaded an asset. -| [authors](#authors) | Narrows the query results to only users that are authors of an entry. -| [cache](#cache) | Enables query cache for this Query. -| [can](#can) | Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [collect](#collect) | -| [dateCreated](#datecreated) | Narrows the query results based on the users’ creation dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the users’ last-updated dates. -| [email](#email) | Narrows the query results based on the users’ email addresses. -| [firstName](#firstname) | Narrows the query results based on the users’ first names. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [fullName](#fullname) | Narrows the query results based on the users’ full names. -| [group](#group) | Narrows the query results based on the user group the users belong to. -| [groupId](#groupid) | Narrows the query results based on the user group the users belong to, per the groups’ IDs. -| [hasPhoto](#hasphoto) | Narrows the query results to only users that have (or don’t have) a user photo. -| [id](#id) | Narrows the query results based on the users’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching users as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [lastLoginDate](#lastlogindate) | Narrows the query results based on the users’ last login dates. -| [lastName](#lastname) | Narrows the query results based on the users’ last names. -| [limit](#limit) | Determines the number of users that should be returned. -| [offset](#offset) | Determines how many users should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) -| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [relatedTo](#relatedto) | Narrows the query results to only users that are related to certain other elements. -| [search](#search) | Narrows the query results to only users that match a search query. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the users’ IDs in the `elements_sites` table. -| [status](#status) | Narrows the query results based on the users’ statuses. -| [trashed](#trashed) | Narrows the query results to only users that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the users’ UIDs. -| [username](#username) | Narrows the query results based on the users’ usernames. -| [with](#with) | Causes the query to return matching users eager-loaded with related elements. -| [withGroups](#withgroups) | Causes the query to return matching users eager-loaded with their user groups. - - - - - -#### `admin` - -Narrows the query results to only users that have admin accounts. - - - -::: code -```twig -{# Fetch admins #} -{% set users = craft.users() - .admin() - .all() %} -``` - -```php -// Fetch admins -$users = \craft\elements\User::find() - ->admin() - ->all(); -``` -::: - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only users that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all users that are related to myCategoryA and myCategoryB #} -{% set users = craft.users() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all users that are related to $myCategoryA and $myCategoryB -$users = \craft\elements\User::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching users as arrays of data, rather than [User](craft4:craft\elements\User) objects. - - - - - -::: code -```twig -{# Fetch users as arrays #} -{% set users = craft.users() - .asArray() - .all() %} -``` - -```php -// Fetch users as arrays -$users = \craft\elements\User::find() - ->asArray() - ->all(); -``` -::: - - -#### `assetUploaders` - -Narrows the query results to only users that have uploaded an asset. - - - -::: code -```twig -{# Fetch all users who have uploaded an asset #} -{% set users = craft.users() - .assetUploaders() - .all() %} -``` - -```php -// Fetch all users who have uploaded an asset -$users = \craft\elements\User::find() - ->assetUploaders() - ->all(); -``` -::: - - -#### `authors` - -Narrows the query results to only users that are authors of an entry. - - - -::: code -```twig -{# Fetch authors #} -{% set users = craft.users() - .authors() - .all() %} -``` - -```php -// Fetch authors -$users = \craft\elements\User::find() - ->authors() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `can` - -Narrows the query results to only users that have a certain user permission, either directly on the user account or through one of their user groups. - -See [User Management](https://craftcms.com/docs/4.x/user-management.html) for a full list of available user permissions defined by Craft. - - - -::: code -```twig -{# Fetch users that can access the control panel #} -{% set users = craft.users() - .can('accessCp') - .all() %} -``` - -```php -// Fetch users that can access the control panel -$users = \craft\elements\User::find() - ->can('accessCp') - ->all(); -``` -::: - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `collect` - - - - - - - - -#### `dateCreated` - -Narrows the query results based on the users’ creation dates. - - - -Possible values include: - -| Value | Fetches users… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch users created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set users = craft.users() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch users created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$users = \craft\elements\User::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the users’ last-updated dates. - - - -Possible values include: - -| Value | Fetches users… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch users updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set users = craft.users() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch users updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$users = \craft\elements\User::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `email` - -Narrows the query results based on the users’ email addresses. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'me@domain.tld'` | with an email of `me@domain.tld`. -| `'not me@domain.tld'` | not with an email of `me@domain.tld`. -| `'*@domain.tld'` | with an email that ends with `@domain.tld`. - - - -::: code -```twig -{# Fetch users with a .co.uk domain on their email address #} -{% set users = craft.users() - .email('*.co.uk') - .all() %} -``` - -```php -// Fetch users with a .co.uk domain on their email address -$users = \craft\elements\User::find() - ->email('*.co.uk') - ->all(); -``` -::: - - -#### `firstName` - -Narrows the query results based on the users’ first names. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'Jane'` | with a first name of `Jane`. -| `'not Jane'` | not with a first name of `Jane`. - - - -::: code -```twig -{# Fetch all the Jane's #} -{% set users = craft.users() - .firstName('Jane') - .all() %} -``` - -```php -// Fetch all the Jane's -$users = \craft\elements\User::find() - ->firstName('Jane') - ->one(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch users in a specific order #} -{% set users = craft.users() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch users in a specific order -$users = \craft\elements\User::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `fullName` - -Narrows the query results based on the users’ full names. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'Jane Doe'` | with a full name of `Jane Doe`. -| `'not Jane Doe'` | not with a full name of `Jane Doe`. - - - -::: code -```twig -{# Fetch all the Jane Doe's #} -{% set users = craft.users() - .fullName('Jane Doe') - .all() %} -``` - -```php -// Fetch all the Jane Doe's -$users = \craft\elements\User::find() - ->fullName('JaneDoe') - ->one(); -``` -::: - - -#### `group` - -Narrows the query results based on the user group the users belong to. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'foo'` | in a group with a handle of `foo`. -| `'not foo'` | not in a group with a handle of `foo`. -| `['foo', 'bar']` | in a group with a handle of `foo` or `bar`. -| `['and', 'foo', 'bar']` | in both groups with handles of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a group with a handle of `foo` or `bar`. -| a [UserGroup](craft4:craft\models\UserGroup) object | in a group represented by the object. - - - -::: code -```twig -{# Fetch users in the Foo user group #} -{% set users = craft.users() - .group('foo') - .all() %} -``` - -```php -// Fetch users in the Foo user group -$users = \craft\elements\User::find() - ->group('foo') - ->all(); -``` -::: - - -#### `groupId` - -Narrows the query results based on the user group the users belong to, per the groups’ IDs. - -Possible values include: - -| Value | Fetches users… -| - | - -| `1` | in a group with an ID of 1. -| `'not 1'` | not in a group with an ID of 1. -| `[1, 2]` | in a group with an ID of 1 or 2. -| `['and', 1, 2]` | in both groups with IDs of 1 or 2. -| `['not', 1, 2]` | not in a group with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch users in a group with an ID of 1 #} -{% set users = craft.users() - .groupId(1) - .all() %} -``` - -```php -// Fetch users in a group with an ID of 1 -$users = \craft\elements\User::find() - ->groupId(1) - ->all(); -``` -::: - - -#### `hasPhoto` - -Narrows the query results to only users that have (or don’t have) a user photo. - - - -::: code -```twig -{# Fetch users with photos #} -{% set users = craft.users() - .hasPhoto() - .all() %} -``` - -```php -// Fetch users without photos -$users = \craft\elements\User::find() - ->hasPhoto() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the users’ IDs. - - - -Possible values include: - -| Value | Fetches users… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the user by its ID #} -{% set user = craft.users() - .id(1) - .one() %} -``` - -```php -// Fetch the user by its ID -$user = \craft\elements\User::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching users as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch users in reverse #} -{% set users = craft.users() - .inReverse() - .all() %} -``` - -```php -// Fetch users in reverse -$users = \craft\elements\User::find() - ->inReverse() - ->all(); -``` -::: - - -#### `lastLoginDate` - -Narrows the query results based on the users’ last login dates. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'>= 2018-04-01'` | that last logged in on or after 2018-04-01. -| `'< 2018-05-01'` | that last logged in before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that last logged in between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that last logged in at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch users that logged in recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set users = craft.users() - .lastLoginDate(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch users that logged in recently -$aWeekAgo = (new \DateTime('7 days ago'))->format(\DateTime::ATOM); - -$users = \craft\elements\User::find() - ->lastLoginDate(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `lastName` - -Narrows the query results based on the users’ last names. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'Doe'` | with a last name of `Doe`. -| `'not Doe'` | not with a last name of `Doe`. - - - -::: code -```twig -{# Fetch all the Doe's #} -{% set users = craft.users() - .lastName('Doe') - .all() %} -``` - -```php -// Fetch all the Doe's -$users = \craft\elements\User::find() - ->lastName('Doe') - ->one(); -``` -::: - - -#### `limit` - -Determines the number of users that should be returned. - - - -::: code -```twig -{# Fetch up to 10 users #} -{% set users = craft.users() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 users -$users = \craft\elements\User::find() - ->limit(10) - ->all(); -``` -::: - - -#### `offset` - -Determines how many users should be skipped in the results. - - - -::: code -```twig -{# Fetch all users except for the first 3 #} -{% set users = craft.users() - .offset(3) - .all() %} -``` - -```php -// Fetch all users except for the first 3 -$users = \craft\elements\User::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the users should be returned in. (If empty, defaults to `username ASC`.) - - - -::: code -```twig -{# Fetch all users in order of date created #} -{% set users = craft.users() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all users in order of date created -$users = \craft\elements\User::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique users from Site A, or Site B if they don’t exist in Site A #} -{% set users = craft.users() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique users from Site A, or Site B if they don’t exist in Site A -$users = \craft\elements\User::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `relatedTo` - -Narrows the query results to only users that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all users that are related to myCategory #} -{% set users = craft.users() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all users that are related to $myCategory -$users = \craft\elements\User::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only users that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all users that match the search query #} -{% set users = craft.users() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all users that match the search query -$users = \craft\elements\User::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the users’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches users… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the user by its ID in the elements_sites table #} -{% set user = craft.users() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the user by its ID in the elements_sites table -$user = \craft\elements\User::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the users’ statuses. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'inactive'` | with inactive accounts. -| `'active'` | with active accounts. -| `'pending'` | with accounts that are still pending activation. -| `'credentialed'` | with either active or pending accounts. -| `'suspended'` | with suspended accounts. -| `'locked'` | with locked accounts (regardless of whether they’re active or suspended). -| `['active', 'suspended']` | with active or suspended accounts. -| `['not', 'active', 'suspended']` | without active or suspended accounts. - - - -::: code -```twig -{# Fetch active and locked users #} -{% set users = craft.users() - .status(['active', 'locked']) - .all() %} -``` - -```php -// Fetch active and locked users -$users = \craft\elements\User::find() - ->status(['active', 'locked']) - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only users that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed users #} -{% set users = craft.users() - .trashed() - .all() %} -``` - -```php -// Fetch trashed users -$users = \craft\elements\User::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the users’ UIDs. - - - - - -::: code -```twig -{# Fetch the user by its UID #} -{% set user = craft.users() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the user by its UID -$user = \craft\elements\User::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `username` - -Narrows the query results based on the users’ usernames. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'foo'` | with a username of `foo`. -| `'not foo'` | not with a username of `foo`. - - - -::: code -```twig -{# Get the requested username #} -{% set requestedUsername = craft.app.request.getSegment(2) %} - -{# Fetch that user #} -{% set user = craft.users() - .username(requestedUsername|literal) - .one() %} -``` - -```php -// Get the requested username -$requestedUsername = \Craft::$app->request->getSegment(2); - -// Fetch that user -$user = \craft\elements\User::find() - ->username(\craft\helpers\Db::escapeParam($requestedUsername)) - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching users eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch users eager-loaded with the "Related" field’s relations #} -{% set users = craft.users() - .with(['related']) - .all() %} -``` - -```php -// Fetch users eager-loaded with the "Related" field’s relations -$users = \craft\elements\User::find() - ->with(['related']) - ->all(); -``` -::: - - -#### `withGroups` - -Causes the query to return matching users eager-loaded with their user groups. - -Possible values include: - -| Value | Fetches users… -| - | - -| `'>= 2018-04-01'` | that last logged-in on or after 2018-04-01. -| `'< 2018-05-01'` | that last logged-in before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that last logged-in between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# fetch users with their user groups #} -{% set users = craft.users() - .withGroups() - .all() %} -``` - -```php -// fetch users with their user groups -$users = \craft\elements\User::find() - ->withGroups() - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/cms/4.x/users.md)!!! diff --git a/docs/commerce/2.x/dev/element-queries/order-queries.md b/docs/commerce/2.x/dev/element-queries/order-queries.md index 0c2dfa46f..fa3d962c8 100644 --- a/docs/commerce/2.x/dev/element-queries/order-queries.md +++ b/docs/commerce/2.x/dev/element-queries/order-queries.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Order Queries You can fetch orders in your templates or PHP code using **order queries**. @@ -53,1040 +57,5 @@ We can display an order with a given order number by doing the following: Order queries support the following parameters: - - -- [anyStatus](#anystatus) -- [asArray](#asarray) -- [customer](#customer) -- [customerId](#customerid) -- [dateCreated](#datecreated) -- [dateOrdered](#dateordered) -- [datePaid](#datepaid) -- [dateUpdated](#dateupdated) -- [email](#email) -- [expiryDate](#expirydate) -- [fixedOrder](#fixedorder) -- [gateway](#gateway) -- [gatewayId](#gatewayid) -- [hasPurchasables](#haspurchasables) -- [hasTransactions](#hastransactions) -- [id](#id) -- [ignorePlaceholders](#ignoreplaceholders) -- [inReverse](#inreverse) -- [isCompleted](#iscompleted) -- [isPaid](#ispaid) -- [isUnpaid](#isunpaid) -- [limit](#limit) -- [number](#number) -- [offset](#offset) -- [orderBy](#orderby) -- [orderStatus](#orderstatus) -- [orderStatusId](#orderstatusid) -- [preferSites](#prefersites) -- [reference](#reference) -- [relatedTo](#relatedto) -- [search](#search) -- [shortNumber](#shortnumber) -- [trashed](#trashed) -- [uid](#uid) -- [user](#user) -- [with](#with) - -### `anyStatus` - -Clears out the [status()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. - - - - - -::: code -```twig -{# Fetch all orders, regardless of status #} -{% set orders = craft.orders() - .anyStatus() - .all() %} -``` - -```php -// Fetch all orders, regardless of status -$orders = \craft\commerce\elements\Order::find() - ->anyStatus() - ->all(); -``` -::: - - -### `asArray` - -Causes the query to return matching orders as arrays of data, rather than [Order](commerce2:craft\commerce\elements\Order) objects. - - - - - -::: code -```twig -{# Fetch orders as arrays #} -{% set orders = craft.orders() - .asArray() - .all() %} -``` - -```php -// Fetch orders as arrays -$orders = \craft\commerce\elements\Order::find() - ->asArray() - ->all(); -``` -::: - - -### `customer` - -Narrows the query results based on the customer. - -Possible values include: - -| Value | Fetches orders… -| - | - -| a [Customer](commerce2:craft\commerce\models\Customer) object | with a customer represented by the object. - - - -::: code -```twig -{# Fetch the current user's orders #} -{% set orders = craft.orders() - .customer(currentUser.customerFieldHandle) - .all() %} -``` - -```php -// Fetch the current user's orders -$user = Craft::$app->user->getIdentity(); -$orders = \craft\commerce\elements\Order::find() - ->customer($user->customerFieldHandle) - ->all(); -``` -::: - - -### `customerId` - -Narrows the query results based on the customer, per their ID. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a customer with an ID of 1. -| `'not 1'` | not with a customer with an ID of 1. -| `[1, 2]` | with a customer with an ID of 1 or 2. -| `['not', 1, 2]` | not with a customer with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the current user's orders #} -{% set orders = craft.orders() - .customerId(currentUser.customerFieldHandle.id) - .all() %} -``` - -```php -// Fetch the current user's orders -$user = Craft::$app->user->getIdentity(); -$orders = \craft\commerce\elements\Order::find() - ->customerId($user->customerFieldHandle->id) - ->all(); -``` -::: - - -### `dateCreated` - -Narrows the query results based on the orders’ creation dates. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set orders = craft.orders() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch orders created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -### `dateOrdered` - -Narrows the query results based on the orders’ completion dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were completed on or after 2018-04-01. -| `'< 2018-05-01'` | that were completed before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders that were completed recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set orders = craft.orders() - .dateOrdered(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch orders that were completed recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateOrdered(">= {$aWeekAgo}") - ->all(); -``` -::: - - -### `datePaid` - -Narrows the query results based on the orders’ paid dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were paid on or after 2018-04-01. -| `'< 2018-05-01'` | that were paid before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders that were paid for recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set orders = craft.orders() - .datePaid(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch orders that were paid for recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->datePaid(">= {$aWeekAgo}") - ->all(); -``` -::: - - -### `dateUpdated` - -Narrows the query results based on the orders’ last-updated dates. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set orders = craft.orders() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch orders updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -### `email` - -Narrows the query results based on the customers’ email addresses. - -Possible values include: - -| Value | Fetches orders with customers… -| - | - -| `'foo@bar.baz'` | with an email of `foo@bar.baz`. -| `'not foo@bar.baz'` | not with an email of `foo@bar.baz`. -| `'*@bar.baz'` | with an email that ends with `@bar.baz`. - - - -::: code -```twig -{# Fetch orders from customers with a .co.uk domain on their email address #} -{% set orders = craft.orders() - .email('*.co.uk') - .all() %} -``` - -```php -// Fetch orders from customers with a .co.uk domain on their email address -$orders = \craft\commerce\elements\Order::find() - ->email('*.co.uk') - ->all(); -``` -::: - - -### `expiryDate` - -Narrows the query results based on the orders’ expiry dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. -| `'< 2020-05-01'` | that will expire before 2020-05-01 -| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. - - - -::: code -```twig -{# Fetch orders expiring this month #} -{% set nextMonth = date('first day of next month')|atom %} - -{% set orders = craft.orders() - .expiryDate("< #{nextMonth}") - .all() %} -``` - -```php -// Fetch orders expiring this month -$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->expiryDate("< {$nextMonth}") - ->all(); -``` -::: - - -### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - - - -::: code -```twig -{# Fetch orders in a specific order #} -{% set orders = craft.orders() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch orders in a specific order -$orders = \craft\commerce\elements\Order::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -### `gateway` - -Narrows the query results based on the gateway. - -Possible values include: - -| Value | Fetches orders… -| - | - -| a [Gateway](commerce2:craft\commerce\base\Gateway) object | with a gateway represented by the object. - - - - -### `gatewayId` - -Narrows the query results based on the gateway, per its ID. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a gateway with an ID of 1. -| `'not 1'` | not with a gateway with an ID of 1. -| `[1, 2]` | with a gateway with an ID of 1 or 2. -| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. - - - - -### `hasPurchasables` - -Narrows the query results to only orders that have certain purchasables. - -Possible values include: - -| Value | Fetches orders… -| - | - -| a [PurchasableInterface](commerce2:craft\commerce\base\PurchasableInterface) object | with a purchasable represented by the object. -| an array of [PurchasableInterface](commerce2:craft\commerce\base\PurchasableInterface) objects | with all the purchasables represented by the objects. - - - - -### `hasTransactions` - -Narrows the query results to only carts that have at least one transaction. - - - -::: code -```twig -{# Fetch carts that have attempted payments #} -{% set orders = craft.orders() - .hasTransactions() - .all() %} -``` - -```php -// Fetch carts that have attempted payments -$orders = \craft\commerce\elements\Order::find() - ->hasTransactions() - ->all(); -``` -::: - - -### `id` - -Narrows the query results based on the orders’ IDs. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the order by its ID #} -{% set order = craft.orders() - .id(1) - .one() %} -``` - -```php -// Fetch the order by its ID -$order = \craft\commerce\elements\Order::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -### `ignorePlaceholders` - -Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch orders in reverse #} -{% set orders = craft.orders() - .inReverse() - .all() %} -``` - -```php -// Fetch orders in reverse -$orders = \craft\commerce\elements\Order::find() - ->inReverse() - ->all(); -``` -::: - - -### `isCompleted` - -Narrows the query results to only orders that are completed. - - - -::: code -```twig -{# Fetch completed orders #} -{% set orders = craft.orders() - .isCompleted() - .all() %} -``` - -```php -// Fetch completed orders -$orders = \craft\commerce\elements\Order::find() - ->isCompleted() - ->all(); -``` -::: - - -### `isPaid` - -Narrows the query results to only orders that are paid. - - - -::: code -```twig -{# Fetch paid orders #} -{% set orders = craft.orders() - .isPaid() - .all() %} -``` - -```php -// Fetch paid orders -$orders = \craft\commerce\elements\Order::find() - ->isPaid() - ->all(); -``` -::: - - -### `isUnpaid` - -Narrows the query results to only orders that are not paid. - - - -::: code -```twig -{# Fetch unpaid orders #} -{% set orders = craft.orders() - .isUnpaid() - .all() %} -``` - -```php -// Fetch unpaid orders -$orders = \craft\commerce\elements\Order::find() - ->isUnpaid() - ->all(); -``` -::: - - -### `limit` - -Determines the number of orders that should be returned. - - - -::: code -```twig -{# Fetch up to 10 orders #} -{% set orders = craft.orders() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 orders -$orders = \craft\commerce\elements\Order::find() - ->limit(10) - ->all(); -``` -::: - - -### `number` - -Narrows the query results based on the order number. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'` | with a matching order number - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderNumber = craft.app.request.getQueryParam('number') %} -{% set order = craft.orders() - .number(orderNumber) - .one() %} -``` - -```php -// Fetch the requested order -$orderNumber = Craft::$app->request->getQueryParam('number'); -$order = \craft\commerce\elements\Order::find() - ->number($orderNumber) - ->one(); -``` -::: - - -### `offset` - -Determines how many orders should be skipped in the results. - - - -::: code -```twig -{# Fetch all orders except for the first 3 #} -{% set orders = craft.orders() - .offset(3) - .all() %} -``` - -```php -// Fetch all orders except for the first 3 -$orders = \craft\commerce\elements\Order::find() - ->offset(3) - ->all(); -``` -::: - - -### `orderBy` - -Determines the order that the orders should be returned in. - - - -::: code -```twig -{# Fetch all orders in order of date created #} -{% set orders = craft.orders() - .orderBy('dateCreated asc') - .all() %} -``` - -```php -// Fetch all orders in order of date created -$orders = \craft\commerce\elements\Order::find() - ->orderBy('dateCreated asc') - ->all(); -``` -::: - - -### `orderStatus` - -Narrows the query results based on the order statuses. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'foo'` | with an order status with a handle of `foo`. -| `'not foo'` | not with an order status with a handle of `foo`. -| `['foo', 'bar']` | with an order status with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not with an order status with a handle of `foo` or `bar`. -| a [OrderStatus](commerce2:craft\commerce\models\OrderStatus) object | with an order status represented by the object. - - - -::: code -```twig -{# Fetch shipped orders #} -{% set orders = craft.orders() - .orderStatus('shipped') - .all() %} -``` - -```php -// Fetch shipped orders -$orders = \craft\commerce\elements\Order::find() - ->orderStatus('shipped') - ->all(); -``` -::: - - -### `orderStatusId` - -Narrows the query results based on the order statuses, per their IDs. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an order status with an ID of 1. -| `'not 1'` | not with an order status with an ID of 1. -| `[1, 2]` | with an order status with an ID of 1 or 2. -| `['not', 1, 2]` | not with an order status with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch orders with an order status with an ID of 1 #} -{% set orders = craft.orders() - .authorGroupId(1) - .all() %} -``` - -```php -// Fetch orders with an order status with an ID of 1 -$orders = \craft\commerce\elements\Order::find() - ->authorGroupId(1) - ->all(); -``` -::: - - -### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned -for Site B. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique orders from Site A, or Site B if they don’t exist in Site A #} -{% set orders = craft.orders() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique orders from Site A, or Site B if they don’t exist in Site A -$orders = \craft\commerce\elements\Order::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -### `reference` - -Narrows the query results based on the order reference. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'xxxx'` | with a matching order reference - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderReference = craft.app.request.getQueryParam('ref') %} -{% set order = craft.orders() - .reference(orderReference) - .one() %} -``` - -```php -// Fetch the requested order -$orderReference = Craft::$app->request->getQueryParam('ref'); -$order = \craft\commerce\elements\Order::find() - ->reference($orderReference) - ->one(); -``` -::: - - -### `relatedTo` - -Narrows the query results to only orders that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all orders that are related to myCategory #} -{% set orders = craft.orders() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all orders that are related to $myCategory -$orders = \craft\commerce\elements\Order::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -### `search` - -Narrows the query results to only orders that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all orders that match the search query #} -{% set orders = craft.orders() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all orders that match the search query -$orders = \craft\commerce\elements\Order::find() - ->search($searchQuery) - ->all(); -``` -::: - - -### `shortNumber` - -Narrows the query results based on the order short number. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'xxxxxxx'` | with a matching order number - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderNumber = craft.app.request.getQueryParam('shortNumber') %} -{% set order = craft.orders() - .shortNumber(orderNumber) - .one() %} -``` - -```php -// Fetch the requested order -$orderNumber = Craft::$app->request->getQueryParam('shortNumber'); -$order = \craft\commerce\elements\Order::find() - ->shortNumber($orderNumber) - ->one(); -``` -::: - - -### `trashed` - -Narrows the query results to only orders that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed orders #} -{% set orders = craft.orders() - .trashed() - .all() %} -``` - -```php -// Fetch trashed orders -$orders = \craft\commerce\elements\Order::find() - ->trashed() - ->all(); -``` -::: - - -### `uid` - -Narrows the query results based on the orders’ UIDs. - - - - - -::: code -```twig -{# Fetch the order by its UID #} -{% set order = craft.orders() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the order by its UID -$order = \craft\commerce\elements\Order::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -### `user` - -Narrows the query results based on the customer’s user account. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a customer with a user account ID of 1. -| a [User](https://docs.craftcms.com/api/v3/craft-elements-user.html) object | with a customer with a user account represented by the object. - - - -::: code -```twig -{# Fetch the current user's orders #} -{% set orders = craft.orders() - .user(currentUser) - .all() %} -``` - -```php -// Fetch the current user's orders -$user = Craft::$app->user->getIdentity(); -$orders = \craft\commerce\elements\Order::find() - ->user($user) - ->all(); -``` -::: - - -### `with` - -Causes the query to return matching orders eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch orders eager-loaded with the "Related" field’s relations #} -{% set orders = craft.orders() - .with(['related']) - .all() %} -``` - -```php -// Fetch orders eager-loaded with the "Related" field’s relations -$orders = \craft\commerce\elements\Order::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/commerce/2.x/order-queries.md)!!! diff --git a/docs/commerce/2.x/dev/element-queries/product-queries.md b/docs/commerce/2.x/dev/element-queries/product-queries.md index 2be668368..d4051baec 100644 --- a/docs/commerce/2.x/dev/element-queries/product-queries.md +++ b/docs/commerce/2.x/dev/element-queries/product-queries.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Product Queries You can fetch products in your templates or PHP code using **product queries**. @@ -49,1009 +53,5 @@ We can display the 10 most recent Clothing products by doing the following: Product queries support the following parameters: - - -- [after](#after) -- [anyStatus](#anystatus) -- [asArray](#asarray) -- [availableForPurchase](#availableforpurchase) -- [before](#before) -- [dateCreated](#datecreated) -- [dateUpdated](#dateupdated) -- [expiryDate](#expirydate) -- [fixedOrder](#fixedorder) -- [hasVariant](#hasvariant) -- [id](#id) -- [ignorePlaceholders](#ignoreplaceholders) -- [inReverse](#inreverse) -- [limit](#limit) -- [offset](#offset) -- [orderBy](#orderby) -- [postDate](#postdate) -- [preferSites](#prefersites) -- [relatedTo](#relatedto) -- [search](#search) -- [site](#site) -- [siteId](#siteid) -- [slug](#slug) -- [status](#status) -- [title](#title) -- [trashed](#trashed) -- [type](#type) -- [typeId](#typeid) -- [uid](#uid) -- [unique](#unique) -- [uri](#uri) -- [with](#with) - -### `after` - -Narrows the query results to only products that were posted on or after a certain date. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'2018-04-01'` | that were posted after 2018-04-01. -| a [DateTime](http://php.net/class.datetime) object | that were posted after the date represented by the object. - - - -::: code -```twig -{# Fetch products posted this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set products = craft.products() - .after(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch products posted this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$products = \craft\commerce\elements\Product::find() - ->after($firstDayOfMonth) - ->all(); -``` -::: - - -### `anyStatus` - -Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. - - - - - -::: code -```twig -{# Fetch all products, regardless of status #} -{% set products = craft.products() - .anyStatus() - .all() %} -``` - -```php -// Fetch all products, regardless of status -$products = \craft\commerce\elements\Product::find() - ->anyStatus() - ->all(); -``` -::: - - -### `asArray` - -Causes the query to return matching products as arrays of data, rather than [Product](commerce2:craft\commerce\elements\Product) objects. - - - - - -::: code -```twig -{# Fetch products as arrays #} -{% set products = craft.products() - .asArray() - .all() %} -``` - -```php -// Fetch products as arrays -$products = \craft\commerce\elements\Product::find() - ->asArray() - ->all(); -``` -::: - - -### `availableForPurchase` - -Narrows the query results to only products that are available for purchase. - - - -::: code -```twig -{# Fetch products that are available for purchase #} -{% set products = craft.products() - .availableForPurchase() - .all() %} -``` - -```php -// Fetch products that are available for purchase -$products = \craft\commerce\elements\Product::find() - ->availableForPurchase() - ->all(); -``` -::: - - -### `before` - -Narrows the query results to only products that were posted before a certain date. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'2018-04-01'` | that were posted before 2018-04-01. -| a [DateTime](http://php.net/class.datetime) object | that were posted before the date represented by the object. - - - -::: code -```twig -{# Fetch products posted before this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set products = craft.products() - .before(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch products posted before this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$products = \craft\commerce\elements\Product::find() - ->before($firstDayOfMonth) - ->all(); -``` -::: - - -### `dateCreated` - -Narrows the query results based on the products’ creation dates. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch products created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set products = craft.products() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch products created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -### `dateUpdated` - -Narrows the query results based on the products’ last-updated dates. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch products updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set products = craft.products() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch products updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -### `expiryDate` - -Narrows the query results based on the products’ expiry dates. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. -| `'< 2020-05-01'` | that will expire before 2020-05-01 -| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. - - - -::: code -```twig -{# Fetch products expiring this month #} -{% set nextMonth = date('first day of next month')|atom %} - -{% set products = craft.products() - .expiryDate("< #{nextMonth}") - .all() %} -``` - -```php -// Fetch products expiring this month -$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->expiryDate("< {$nextMonth}") - ->all(); -``` -::: - - -### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - - - -::: code -```twig -{# Fetch products in a specific order #} -{% set products = craft.products() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch products in a specific order -$products = \craft\commerce\elements\Product::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -### `hasVariant` - -Narrows the query results to only products that have certain variants. - -Possible values include: - -| Value | Fetches products… -| - | - -| a [VariantQuery](commerce2:craft\commerce\elements\db\VariantQuery) object | with variants that match the query. - - - - -### `id` - -Narrows the query results based on the products’ IDs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the product by its ID #} -{% set product = craft.products() - .id(1) - .one() %} -``` - -```php -// Fetch the product by its ID -$product = \craft\commerce\elements\Product::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -### `ignorePlaceholders` - -Causes the query to return matching products as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch products in reverse #} -{% set products = craft.products() - .inReverse() - .all() %} -``` - -```php -// Fetch products in reverse -$products = \craft\commerce\elements\Product::find() - ->inReverse() - ->all(); -``` -::: - - -### `limit` - -Determines the number of products that should be returned. - - - -::: code -```twig -{# Fetch up to 10 products #} -{% set products = craft.products() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 products -$products = \craft\commerce\elements\Product::find() - ->limit(10) - ->all(); -``` -::: - - -### `offset` - -Determines how many products should be skipped in the results. - - - -::: code -```twig -{# Fetch all products except for the first 3 #} -{% set products = craft.products() - .offset(3) - .all() %} -``` - -```php -// Fetch all products except for the first 3 -$products = \craft\commerce\elements\Product::find() - ->offset(3) - ->all(); -``` -::: - - -### `orderBy` - -Determines the order that the products should be returned in. - - - -::: code -```twig -{# Fetch all products in order of date created #} -{% set products = craft.products() - .orderBy('dateCreated asc') - .all() %} -``` - -```php -// Fetch all products in order of date created -$products = \craft\commerce\elements\Product::find() - ->orderBy('dateCreated asc') - ->all(); -``` -::: - - -### `postDate` - -Narrows the query results based on the products’ post dates. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. -| `'< 2018-05-01'` | that were posted before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch products posted last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set products = craft.products() - .postDate(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch products posted last month -$start = new \DateTime('first day of next month')->format(\DateTime::ATOM); -$end = new \DateTime('first day of this month')->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->postDate(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned -for Site B. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique products from Site A, or Site B if they don’t exist in Site A #} -{% set products = craft.products() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique products from Site A, or Site B if they don’t exist in Site A -$products = \craft\commerce\elements\Product::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -### `relatedTo` - -Narrows the query results to only products that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all products that are related to myCategory #} -{% set products = craft.products() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all products that are related to $myCategory -$products = \craft\commerce\elements\Product::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -### `search` - -Narrows the query results to only products that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all products that match the search query #} -{% set products = craft.products() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all products that match the search query -$products = \craft\commerce\elements\Product::find() - ->search($searchQuery) - ->all(); -``` -::: - - -### `site` - -Determines which site(s) the products should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a `\craft\commerce\elements\db\Site` object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch products from the Foo site #} -{% set products = craft.products() - .site('foo') - .all() %} -``` - -```php -// Fetch products from the Foo site -$products = \craft\commerce\elements\Product::find() - ->site('foo') - ->all(); -``` -::: - - -### `siteId` - -Determines which site(s) the products should be queried in, per the site’s ID. - - - -The current site will be used by default. - - - -::: code -```twig -{# Fetch products from the site with an ID of 1 #} -{% set products = craft.products() - .siteId(1) - .all() %} -``` - -```php -// Fetch products from the site with an ID of 1 -$products = \craft\commerce\elements\Product::find() - ->siteId(1) - ->all(); -``` -::: - - -### `slug` - -Narrows the query results based on the products’ slugs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | with a slug of `foo`. -| `'foo*'` | with a slug that begins with `foo`. -| `'*foo'` | with a slug that ends with `foo`. -| `'*foo*'` | with a slug that contains `foo`. -| `'not *foo*'` | with a slug that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested product slug from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the product with that slug #} -{% set product = craft.products() - .slug(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested product slug from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the product with that slug -$product = \craft\commerce\elements\Product::find() - ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -### `status` - -Narrows the query results based on the products’ statuses. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'live'` _(default)_ | that are live. -| `'pending'` | that are pending (enabled with a Post Date in the future). -| `'expired'` | that are expired (enabled with an Expiry Date in the past). -| `'disabled'` | that are disabled. -| `['live', 'pending']` | that are live or pending. - - - -::: code -```twig -{# Fetch disabled products #} -{% set products = craft.products() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled products -$products = \craft\commerce\elements\Product::find() - ->status('disabled') - ->all(); -``` -::: - - -### `title` - -Narrows the query results based on the products’ titles. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch products with a title that contains "Foo" #} -{% set products = craft.products() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch products with a title that contains "Foo" -$products = \craft\commerce\elements\Product::find() - ->title('*Foo*') - ->all(); -``` -::: - - -### `trashed` - -Narrows the query results to only products that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed products #} -{% set products = craft.products() - .trashed() - .all() %} -``` - -```php -// Fetch trashed products -$products = \craft\commerce\elements\Product::find() - ->trashed() - ->all(); -``` -::: - - -### `type` - -Narrows the query results based on the products’ types. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | of a type with a handle of `foo`. -| `'not foo'` | not of a type with a handle of `foo`. -| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. -| an [ProductType](commerce2:craft\commerce\models\ProductType) object | of a type represented by the object. - - - -::: code -```twig -{# Fetch products with a Foo product type #} -{% set products = craft.products() - .type('foo') - .all() %} -``` - -```php -// Fetch products with a Foo product type -$products = \craft\commerce\elements\Product::find() - ->type('foo') - ->all(); -``` -::: - - -### `typeId` - -Narrows the query results based on the products’ types, per the types’ IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with an ID of 1. -| `'not 1'` | not of a type with an ID of 1. -| `[1, 2]` | of a type with an ID of 1 or 2. -| `['not', 1, 2]` | not of a type with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch products of the product type with an ID of 1 #} -{% set products = craft.products() - .typeId(1) - .all() %} -``` - -```php -// Fetch products of the product type with an ID of 1 -$products = \craft\commerce\elements\Product::find() - ->typeId(1) - ->all(); -``` -::: - - -### `uid` - -Narrows the query results based on the products’ UIDs. - - - - - -::: code -```twig -{# Fetch the product by its UID #} -{% set product = craft.products() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the product by its UID -$product = \craft\commerce\elements\Product::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique products across all sites #} -{% set products = craft.products() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique products across all sites -$products = \craft\commerce\elements\Product::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -### `uri` - -Narrows the query results based on the products’ URIs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the product with that URI #} -{% set product = craft.products() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the product with that URI -$product = \craft\commerce\elements\Product::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -### `with` - -Causes the query to return matching products eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch products eager-loaded with the "Related" field’s relations #} -{% set products = craft.products() - .with(['related']) - .all() %} -``` - -```php -// Fetch products eager-loaded with the "Related" field’s relations -$products = \craft\commerce\elements\Product::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/commerce/2.x/product-queries.md)!!! diff --git a/docs/commerce/2.x/dev/element-queries/subscription-queries.md b/docs/commerce/2.x/dev/element-queries/subscription-queries.md index 85a14e168..010c198fa 100644 --- a/docs/commerce/2.x/dev/element-queries/subscription-queries.md +++ b/docs/commerce/2.x/dev/element-queries/subscription-queries.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Subscription Queries You can fetch subscriptions in your templates or PHP code using **subscription queries**. @@ -53,960 +57,5 @@ We can display all of the current user’s subscriptions by doing the following: Subscription queries support the following parameters: - - -- [anyStatus](#anystatus) -- [asArray](#asarray) -- [dateCanceled](#datecanceled) -- [dateCreated](#datecreated) -- [dateExpired](#dateexpired) -- [dateSuspended](#datesuspended) -- [dateUpdated](#dateupdated) -- [fixedOrder](#fixedorder) -- [gatewayId](#gatewayid) -- [hasStarted](#hasstarted) -- [id](#id) -- [ignorePlaceholders](#ignoreplaceholders) -- [inReverse](#inreverse) -- [isCanceled](#iscanceled) -- [isExpired](#isexpired) -- [isSuspended](#issuspended) -- [limit](#limit) -- [nextPaymentDate](#nextpaymentdate) -- [offset](#offset) -- [onTrial](#ontrial) -- [orderBy](#orderby) -- [orderId](#orderid) -- [plan](#plan) -- [planId](#planid) -- [preferSites](#prefersites) -- [reference](#reference) -- [relatedTo](#relatedto) -- [search](#search) -- [status](#status) -- [trashed](#trashed) -- [trialDays](#trialdays) -- [uid](#uid) -- [user](#user) -- [userId](#userid) -- [with](#with) - -### `anyStatus` - -Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. - - - - - -::: code -```twig -{# Fetch all subscriptions, regardless of status #} -{% set subscriptions = craft.subscriptions() - .anyStatus() - .all() %} -``` - -```php -// Fetch all subscriptions, regardless of status -$subscriptions = \craft\commerce\elements\Subscription::find() - ->anyStatus() - ->all(); -``` -::: - - -### `asArray` - -Causes the query to return matching subscriptions as arrays of data, rather than `\craft\commerce\elements\Subscription` objects. - - - - - -::: code -```twig -{# Fetch subscriptions as arrays #} -{% set subscriptions = craft.subscriptions() - .asArray() - .all() %} -``` - -```php -// Fetch subscriptions as arrays -$subscriptions = \craft\commerce\elements\Subscription::find() - ->asArray() - ->all(); -``` -::: - - -### `dateCanceled` - -Narrows the query results based on the subscriptions’ cancellation date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were canceled on or after 2018-04-01. -| `'< 2018-05-01'` | that were canceled before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were canceled between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions that were canceled recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateCanceled(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that were canceled recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateCanceled(">= {$aWeekAgo}") - ->all(); -``` -::: - - -### `dateCreated` - -Narrows the query results based on the subscriptions’ creation dates. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch subscriptions created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -### `dateExpired` - -Narrows the query results based on the subscriptions’ expiration date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that expired on or after 2018-04-01. -| `'< 2018-05-01'` | that expired before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that expired between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions that expired recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateExpired(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that expired recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateExpired(">= {$aWeekAgo}") - ->all(); -``` -::: - - -### `dateSuspended` - -Narrows the query results based on the subscriptions’ suspension date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were suspended on or after 2018-04-01. -| `'< 2018-05-01'` | that were suspended before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were suspended between 2018-04-01 and 2018-05-01. - - -::: code -```twig -{# Fetch subscriptions that were suspended recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateSuspended(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that were suspended recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateSuspended(">= {$aWeekAgo}") - ->all(); -``` -::: - - -### `dateUpdated` - -Narrows the query results based on the subscriptions’ last-updated dates. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch subscriptions updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - - - -::: code -```twig -{# Fetch subscriptions in a specific order #} -{% set subscriptions = craft.subscriptions() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch subscriptions in a specific order -$subscriptions = \craft\commerce\elements\Subscription::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -### `gatewayId` - -Narrows the query results based on the gateway, per its ID. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with a gateway with an ID of 1. -| `'not 1'` | not with a gateway with an ID of 1. -| `[1, 2]` | with a gateway with an ID of 1 or 2. -| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. - - - - -### `hasStarted` - -Narrows the query results to only subscriptions that have started. - - - -::: code -```twig -{# Fetch started subscriptions #} -{% set subscriptions = craft.subscriptions() - .hasStarted() - .all() %} -``` - -```php -// Fetch started subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->hasStarted() - ->all(); -``` -::: - - -### `id` - -Narrows the query results based on the subscriptions’ IDs. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the subscription by its ID #} -{% set subscription = craft.subscriptions() - .id(1) - .one() %} -``` - -```php -// Fetch the subscription by its ID -$subscription = \craft\commerce\elements\Subscription::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -### `ignorePlaceholders` - -Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch subscriptions in reverse #} -{% set subscriptions = craft.subscriptions() - .inReverse() - .all() %} -``` - -```php -// Fetch subscriptions in reverse -$subscriptions = \craft\commerce\elements\Subscription::find() - ->inReverse() - ->all(); -``` -::: - - -### `isCanceled` - -Narrows the query results to only subscriptions that are canceled. - - - -::: code -```twig -{# Fetch canceled subscriptions #} -{% set subscriptions = craft.subscriptions() - .isCanceled() - .all() %} -``` - -```php -// Fetch canceled subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isCanceled() - ->all(); -``` -::: - - -### `isExpired` - -Narrows the query results to only subscriptions that have expired. - - - -::: code -```twig -{# Fetch expired subscriptions #} -{% set subscriptions = craft.subscriptions() - .isExpired() - .all() %} -``` - -```php -// Fetch expired subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isExpired() - ->all(); -``` -::: - - -### `isSuspended` - -Narrows the query results to only subscriptions that are suspended. - - - -::: code -```twig -{# Fetch suspended subscriptions #} -{% set subscriptions = craft.subscriptions() - .isSuspended() - .all() %} -``` - -```php -// Fetch suspended subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isSuspended() - ->all(); -``` -::: - - -### `limit` - -Determines the number of subscriptions that should be returned. - - - -::: code -```twig -{# Fetch up to 10 subscriptions #} -{% set subscriptions = craft.subscriptions() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->limit(10) - ->all(); -``` -::: - - -### `nextPaymentDate` - -Narrows the query results based on the subscriptions’ next payment dates. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | with a next payment on or after 2018-04-01. -| `'< 2018-05-01'` | with a next payment before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | with a next payment between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions with a payment due soon #} -{% set aWeekFromNow = date('+7 days')|atom %} - -{% set subscriptions = craft.subscriptions() - .nextPaymentDate("< #{aWeekFromNow}") - .all() %} -``` - -```php -// Fetch subscriptions with a payment due soon -$aWeekFromNow = new \DateTime('+7 days')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->nextPaymentDate("< {$aWeekFromNow}") - ->all(); -``` -::: - - -### `offset` - -Determines how many subscriptions should be skipped in the results. - - - -::: code -```twig -{# Fetch all subscriptions except for the first 3 #} -{% set subscriptions = craft.subscriptions() - .offset(3) - .all() %} -``` - -```php -// Fetch all subscriptions except for the first 3 -$subscriptions = \craft\commerce\elements\Subscription::find() - ->offset(3) - ->all(); -``` -::: - - -### `onTrial` - -Narrows the query results to only subscriptions that are on trial. - - - -::: code -```twig -{# Fetch trialed subscriptions #} -{% set subscriptions = craft.subscriptions() - .onTrial() - .all() %} -``` - -```php -// Fetch trialed subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isPaid() - ->all(); -``` -::: - - -### `orderBy` - -Determines the order that the subscriptions should be returned in. - - - -::: code -```twig -{# Fetch all subscriptions in order of date created #} -{% set subscriptions = craft.subscriptions() - .orderBy('dateCreated asc') - .all() %} -``` - -```php -// Fetch all subscriptions in order of date created -$subscriptions = \craft\commerce\elements\Subscription::find() - ->orderBy('dateCreated asc') - ->all(); -``` -::: - - -### `orderId` - -Narrows the query results based on the order, per its ID. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with an order with an ID of 1. -| `'not 1'` | not with an order with an ID of 1. -| `[1, 2]` | with an order with an ID of 1 or 2. -| `['not', 1, 2]` | not with an order with an ID of 1 or 2. - - - - -### `plan` - -Narrows the query results based on the subscription plan. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'foo'` | for a plan with a handle of `foo`. -| `['foo', 'bar']` | for plans with a handle of `foo` or `bar`. -| a [Plan](commerce2:craft\commerce\base\Plan) object | for a plan represented by the object. - - - -::: code -```twig -{# Fetch Supporter plan subscriptions #} -{% set subscriptions = craft.subscriptions() - .plan('supporter') - .all() %} -``` - -```php -// Fetch Supporter plan subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->plan('supporter') - ->all(); -``` -::: - - -### `planId` - -Narrows the query results based on the subscription plans’ IDs. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | for a plan with an ID of 1. -| `[1, 2]` | for plans with an ID of 1 or 2. -| `['not', 1, 2]` | for plans not with an ID of 1 or 2. - - - - -### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned -for Site B. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A #} -{% set subscriptions = craft.subscriptions() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A -$subscriptions = \craft\commerce\elements\Subscription::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -### `reference` - -Narrows the query results based on the reference. - - - - - - -### `relatedTo` - -Narrows the query results to only subscriptions that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all subscriptions that are related to myCategory #} -{% set subscriptions = craft.subscriptions() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all subscriptions that are related to $myCategory -$subscriptions = \craft\commerce\elements\Subscription::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -### `search` - -Narrows the query results to only subscriptions that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all subscriptions that match the search query #} -{% set subscriptions = craft.subscriptions() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all subscriptions that match the search query -$subscriptions = \craft\commerce\elements\Subscription::find() - ->search($searchQuery) - ->all(); -``` -::: - - -### `status` - -Narrows the query results based on the subscriptions’ statuses. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'active'` _(default)_ | that are active. -| `'expired'` | that have expired. - - - -::: code -```twig -{# Fetch expired subscriptions #} -{% set subscriptions = craft.subscriptions() - .status('expired') - .all() %} -``` - -```php -// Fetch expired subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->status('expired') - ->all(); -``` -::: - - -### `trashed` - -Narrows the query results to only subscriptions that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed subscriptions #} -{% set subscriptions = craft.subscriptions() - .trashed() - .all() %} -``` - -```php -// Fetch trashed subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->trashed() - ->all(); -``` -::: - - -### `trialDays` - -Narrows the query results based on the number of trial days. - - - - - - -### `uid` - -Narrows the query results based on the subscriptions’ UIDs. - - - - - -::: code -```twig -{# Fetch the subscription by its UID #} -{% set subscription = craft.subscriptions() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the subscription by its UID -$subscription = \craft\commerce\elements\Subscription::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -### `user` - -Narrows the query results based on the subscriptions’ user accounts. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'foo'` | for a user account with a username of `foo` -| `['foo', 'bar']` | for user accounts with a username of `foo` or `bar`. -| a [User](https://docs.craftcms.com/api/v3/craft-elements-user.html) object | for a user account represented by the object. - - - -::: code -```twig -{# Fetch the current user's subscriptions #} -{% set subscriptions = craft.subscriptions() - .user(currentUser) - .all() %} -``` - -```php -// Fetch the current user's subscriptions -$user = Craft::$app->user->getIdentity(); -$subscriptions = \craft\commerce\elements\Subscription::find() - ->user($user) - ->all(); -``` -::: - - -### `userId` - -Narrows the query results based on the subscriptions’ user accounts’ IDs. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | for a user account with an ID of 1. -| `[1, 2]` | for user accounts with an ID of 1 or 2. -| `['not', 1, 2]` | for user accounts not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the current user's subscriptions #} -{% set subscriptions = craft.subscriptions() - .userId(currentUser.id) - .all() %} -``` - -```php -// Fetch the current user's subscriptions -$user = Craft::$app->user->getIdentity(); -$subscriptions = \craft\commerce\elements\Subscription::find() - ->userId($user->id) - ->all(); -``` -::: - - -### `with` - -Causes the query to return matching subscriptions eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch subscriptions eager-loaded with the "Related" field’s relations #} -{% set subscriptions = craft.subscriptions() - .with(['related']) - .all() %} -``` - -```php -// Fetch subscriptions eager-loaded with the "Related" field’s relations -$subscriptions = \craft\commerce\elements\Subscription::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/commerce/2.x/subscription-queries.md)!!! diff --git a/docs/commerce/2.x/dev/element-queries/variant-queries.md b/docs/commerce/2.x/dev/element-queries/variant-queries.md index 02dc78384..cc19a890f 100644 --- a/docs/commerce/2.x/dev/element-queries/variant-queries.md +++ b/docs/commerce/2.x/dev/element-queries/variant-queries.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Variant Queries You can fetch variants in your templates or PHP code using **variant queries**. @@ -49,891 +53,5 @@ We can display a specific variant by its ID by doing the following: ``` - - -- [anyStatus](#anystatus) -- [asArray](#asarray) -- [dateCreated](#datecreated) -- [dateUpdated](#dateupdated) -- [fixedOrder](#fixedorder) -- [hasProduct](#hasproduct) -- [hasSales](#hassales) -- [hasStock](#hasstock) -- [id](#id) -- [ignorePlaceholders](#ignoreplaceholders) -- [inReverse](#inreverse) -- [isDefault](#isdefault) -- [limit](#limit) -- [maxQty](#maxqty) -- [minQty](#minqty) -- [offset](#offset) -- [orderBy](#orderby) -- [preferSites](#prefersites) -- [price](#price) -- [product](#product) -- [productId](#productid) -- [relatedTo](#relatedto) -- [search](#search) -- [site](#site) -- [siteId](#siteid) -- [sku](#sku) -- [status](#status) -- [stock](#stock) -- [title](#title) -- [trashed](#trashed) -- [typeId](#typeid) -- [uid](#uid) -- [unique](#unique) -- [with](#with) - -### `anyStatus` - -Clears out the [status](#status) and [enabledForSite()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-enabledforsite) parameters. - - - - - -::: code -```twig -{# Fetch all variants, regardless of status #} -{% set variants = craft.variants() - .anyStatus() - .all() %} -``` - -```php -// Fetch all variants, regardless of status -$variants = \craft\commerce\elements\Variant::find() - ->anyStatus() - ->all(); -``` -::: - - -### `asArray` - -Causes the query to return matching variants as arrays of data, rather than [Variant](commerce2:craft\commerce\elements\Variant) objects. - - - - - -::: code -```twig -{# Fetch variants as arrays #} -{% set variants = craft.variants() - .asArray() - .all() %} -``` - -```php -// Fetch variants as arrays -$variants = \craft\commerce\elements\Variant::find() - ->asArray() - ->all(); -``` -::: - - -### `dateCreated` - -Narrows the query results based on the variants’ creation dates. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch variants created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set variants = craft.variants() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch variants created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$variants = \craft\commerce\elements\Variant::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -### `dateUpdated` - -Narrows the query results based on the variants’ last-updated dates. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch variants updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set variants = craft.variants() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch variants updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$variants = \craft\commerce\elements\Variant::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - - - -::: code -```twig -{# Fetch variants in a specific order #} -{% set variants = craft.variants() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch variants in a specific order -$variants = \craft\commerce\elements\Variant::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -### `hasProduct` - -Narrows the query results to only variants for certain products. - -Possible values include: - -| Value | Fetches variants… -| - | - -| a [ProductQuery](commerce2:craft\commerce\elements\db\ProductQuery) object | for products that match the query. - - - - -### `hasSales` - -Narrows the query results to only variants that are on sale. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `true` | on sale -| `false` | not on sale - - - - -### `hasStock` - -Narrows the query results to only variants that have stock. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `true` | with stock. -| `false` | with no stock. - - - - -### `id` - -Narrows the query results based on the variants’ IDs. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the variant by its ID #} -{% set variant = craft.variants() - .id(1) - .one() %} -``` - -```php -// Fetch the variant by its ID -$variant = \craft\commerce\elements\Variant::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -### `ignorePlaceholders` - -Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch variants in reverse #} -{% set variants = craft.variants() - .inReverse() - .all() %} -``` - -```php -// Fetch variants in reverse -$variants = \craft\commerce\elements\Variant::find() - ->inReverse() - ->all(); -``` -::: - - -### `isDefault` - -Narrows the query results to only default variants. - - - -::: code -```twig -{# Fetch default variants #} -{% set variants = craft.variants() - .isDefault() - .all() %} -``` - -```php -// Fetch default variants -$variants = \craft\commerce\elements\Variant::find() - ->isDefault() - ->all(); -``` -::: - - -### `limit` - -Determines the number of variants that should be returned. - - - -::: code -```twig -{# Fetch up to 10 variants #} -{% set variants = craft.variants() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 variants -$variants = \craft\commerce\elements\Variant::find() - ->limit(10) - ->all(); -``` -::: - - -### `maxQty` - -Narrows the query results based on the variants’ max quantity. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a maxQty of 100. -| `'>= 100'` | with a maxQty of at least 100. -| `'< 100'` | with a maxQty of less than 100. - - - - -### `minQty` - -Narrows the query results based on the variants’ min quantity. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a minQty of 100. -| `'>= 100'` | with a minQty of at least 100. -| `'< 100'` | with a minQty of less than 100. - - - - -### `offset` - -Determines how many variants should be skipped in the results. - - - -::: code -```twig -{# Fetch all variants except for the first 3 #} -{% set variants = craft.variants() - .offset(3) - .all() %} -``` - -```php -// Fetch all variants except for the first 3 -$variants = \craft\commerce\elements\Variant::find() - ->offset(3) - ->all(); -``` -::: - - -### `orderBy` - -Determines the order that the variants should be returned in. - - - -::: code -```twig -{# Fetch all variants in order of date created #} -{% set variants = craft.variants() - .orderBy('dateCreated asc') - .all() %} -``` - -```php -// Fetch all variants in order of date created -$variants = \craft\commerce\elements\Variant::find() - ->orderBy('dateCreated asc') - ->all(); -``` -::: - - -### `preferSites` - -If [unique](#unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned -for Site B. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique variants from Site A, or Site B if they don’t exist in Site A #} -{% set variants = craft.variants() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique variants from Site A, or Site B if they don’t exist in Site A -$variants = \craft\commerce\elements\Variant::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -### `price` - -Narrows the query results based on the variants’ price. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a price of 100. -| `'>= 100'` | with a price of at least 100. -| `'< 100'` | with a price of less than 100. - - - - -### `product` - -Narrows the query results based on the variants’ product. - -Possible values include: - -| Value | Fetches variants… -| - | - -| a [Product](commerce2:craft\commerce\elements\Product) object | for a product represented by the object. - - - - -### `productId` - -Narrows the query results based on the variants’ products’ IDs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | for a product with an ID of 1. -| `[1, 2]` | for product with an ID of 1 or 2. -| `['not', 1, 2]` | for product not with an ID of 1 or 2. - - - - -### `relatedTo` - -Narrows the query results to only variants that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all variants that are related to myCategory #} -{% set variants = craft.variants() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all variants that are related to $myCategory -$variants = \craft\commerce\elements\Variant::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -### `search` - -Narrows the query results to only variants that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all variants that match the search query #} -{% set variants = craft.variants() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all variants that match the search query -$variants = \craft\commerce\elements\Variant::find() - ->search($searchQuery) - ->all(); -``` -::: - - -### `site` - -Determines which site(s) the variants should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a `\craft\commerce\elements\db\Site` object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch variants from the Foo site #} -{% set variants = craft.variants() - .site('foo') - .all() %} -``` - -```php -// Fetch variants from the Foo site -$variants = \craft\commerce\elements\Variant::find() - ->site('foo') - ->all(); -``` -::: - - -### `siteId` - -Determines which site(s) the variants should be queried in, per the site’s ID. - - - -The current site will be used by default. - - - -::: code -```twig -{# Fetch variants from the site with an ID of 1 #} -{% set variants = craft.variants() - .siteId(1) - .all() %} -``` - -```php -// Fetch variants from the site with an ID of 1 -$variants = \craft\commerce\elements\Variant::find() - ->siteId(1) - ->all(); -``` -::: - - -### `sku` - -Narrows the query results based on the variants’ SKUs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'foo'` | with a SKU of `foo`. -| `'foo*'` | with a SKU that begins with `foo`. -| `'*foo'` | with a SKU that ends with `foo`. -| `'*foo*'` | with a SKU that contains `foo`. -| `'not *foo*'` | with a SKU that doesn’t contain `foo`. -| `['*foo*', '*bar*'` | with a SKU that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a SKU that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested variant SKU from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the variant with that slug #} -{% set variant = craft.variants() - .sku(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested variant SKU from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the variant with that slug -$variant = \craft\commerce\elements\Variant::find() - ->sku(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -### `status` - -Narrows the query results based on the variants’ statuses. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'enabled'` _(default)_ | that are enabled. -| `'disabled'` | that are disabled. - - - -::: code -```twig -{# Fetch disabled variants #} -{% set variants = craft.variants() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled variants -$variants = \craft\commerce\elements\Variant::find() - ->status('disabled') - ->all(); -``` -::: - - -### `stock` - -Narrows the query results based on the variants’ stock. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `0` | with no stock. -| `'>= 5'` | with a stock of at least 5. -| `'< 10'` | with a stock of less than 10. - - - - -### `title` - -Narrows the query results based on the variants’ titles. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch variants with a title that contains "Foo" #} -{% set variants = craft.variants() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch variants with a title that contains "Foo" -$variants = \craft\commerce\elements\Variant::find() - ->title('*Foo*') - ->all(); -``` -::: - - -### `trashed` - -Narrows the query results to only variants that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed variants #} -{% set variants = craft.variants() - .trashed() - .all() %} -``` - -```php -// Fetch trashed variants -$variants = \craft\commerce\elements\Variant::find() - ->trashed() - ->all(); -``` -::: - - -### `typeId` - -Narrows the query results based on the variants’ product types, per their IDs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | for a product of a type with an ID of 1. -| `[1, 2]` | for product of a type with an ID of 1 or 2. -| `['not', 1, 2]` | for product of a type not with an ID of 1 or 2. - - - - -### `uid` - -Narrows the query results based on the variants’ UIDs. - - - - - -::: code -```twig -{# Fetch the variant by its UID #} -{% set variant = craft.variants() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the variant by its UID -$variant = \craft\commerce\elements\Variant::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -### `unique` - -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique variants across all sites #} -{% set variants = craft.variants() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique variants across all sites -$variants = \craft\commerce\elements\Variant::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -### `with` - -Causes the query to return matching variants eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch variants eager-loaded with the "Related" field’s relations #} -{% set variants = craft.variants() - .with(['related']) - .all() %} -``` - -```php -// Fetch variants eager-loaded with the "Related" field’s relations -$variants = \craft\commerce\elements\Variant::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/commerce/2.x/variant-queries.md)!!! diff --git a/docs/commerce/3.x/config-settings.md b/docs/commerce/3.x/config-settings.md index 2367b0978..6ebdf7bf3 100644 --- a/docs/commerce/3.x/config-settings.md +++ b/docs/commerce/3.x/config-settings.md @@ -37,789 +37,5 @@ You can access the Commerce [general settings model](commerce3:craft\commerce\mo Here’s the full list of Commerce config settings: - - -## System - -### `defaultView` - -

- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'commerce/orders'` - -Defined by -: [Settings::$defaultView](commerce3:craft\commerce\models\Settings::$defaultView) - -Since -: 2.2 - -
- -Commerce’s default control panel view. (Defaults to order index.) - - - -### `emailSenderAddress` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `null` - -Defined by -: [Settings::$emailSenderAddress](commerce3:craft\commerce\models\Settings::$emailSenderAddress) - -
- -Default email address Commerce system messages should be sent from. - -If `null` (default), Craft’s [MailSettings::$fromEmail](craft3:craft\models\MailSettings::$fromEmail) will be used. - - - -### `emailSenderAddressPlaceholder` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `null` - -Defined by -: [Settings::$emailSenderAddressPlaceholder](commerce3:craft\commerce\models\Settings::$emailSenderAddressPlaceholder) - -
- -Placeholder value displayed for the sender address control panel settings field. - -If `null` (default), Craft’s [MailSettings::$fromEmail](craft3:craft\models\MailSettings::$fromEmail) will be used. - - - -### `emailSenderName` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `null` - -Defined by -: [Settings::$emailSenderName](commerce3:craft\commerce\models\Settings::$emailSenderName) - -
- -Default from name used for Commerce system emails. - -If `null` (default), Craft’s [MailSettings::$fromName](craft3:craft\models\MailSettings::$fromName) will be used. - - - -### `emailSenderNamePlaceholder` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `null` - -Defined by -: [Settings::$emailSenderNamePlaceholder](commerce3:craft\commerce\models\Settings::$emailSenderNamePlaceholder) - -
- -Placeholder value displayed for the sender name control panel settings field. - -If `null` (default), Craft’s [MailSettings::$fromName](craft3:craft\models\MailSettings::$fromName) will be used. - - - -### `showCustomerInfoTab` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [Settings::$showCustomerInfoTab](commerce3:craft\commerce\models\Settings::$showCustomerInfoTab) - -Since -: 3.0 - -
- -Whether the [customer info tab](customers.md#user-customer-info-tab) should be shown when viewing users in the control panel. - - - -## Cart - -### `activeCartDuration` - -
- -Allowed types -: `mixed` - -Default value -: `3600` (1 hour) - -Defined by -: [Settings::$activeCartDuration](commerce3:craft\commerce\models\Settings::$activeCartDuration) - -Since -: 2.2 - -
- -How long a cart should go without being updated before it’s considered inactive. - -See [craft\helpers\ConfigHelper::durationInSeconds()](craft3:craft\helpers\ConfigHelper::durationInSeconds()) for a list of supported value types. - - - -### `allowCheckoutWithoutPayment` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$allowCheckoutWithoutPayment](commerce3:craft\commerce\models\Settings::$allowCheckoutWithoutPayment) - -Since -: 3.3 - -
- -Whether carts are can be marked as completed without a payment. - - - -### `allowEmptyCartOnCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$allowEmptyCartOnCheckout](commerce3:craft\commerce\models\Settings::$allowEmptyCartOnCheckout) - -Since -: 2.2 - -
- -Whether carts are allowed to be empty on checkout. - - - -### `autoSetCartShippingMethodOption` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$autoSetCartShippingMethodOption](commerce3:craft\commerce\models\Settings::$autoSetCartShippingMethodOption) - -
- -Whether the first available shipping method option should be set automatically on carts. - - - -### `autoSetNewCartAddresses` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [Settings::$autoSetNewCartAddresses](commerce3:craft\commerce\models\Settings::$autoSetNewCartAddresses) - -
- -Whether the customer’s primary shipping and billing addresses should be set automatically on new carts. - - - -### `cartVariable` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'cart'` - -Defined by -: [Settings::$cartVariable](commerce3:craft\commerce\models\Settings::$cartVariable) - -
- -Key to be used when returning cart information in a response. - - - -### `loadCartRedirectUrl` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [Settings::$loadCartRedirectUrl](commerce3:craft\commerce\models\Settings::$loadCartRedirectUrl) - -Since -: 3.1 - -
- -Default URL to be loaded after using the [load cart controller action](orders-carts.md#loading-a-cart). - -If `null` (default), Craft’s default [`siteUrl`](config3:siteUrl) will be used. - - - -### `purgeInactiveCarts` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [Settings::$purgeInactiveCarts](commerce3:craft\commerce\models\Settings::$purgeInactiveCarts) - -
- -Whether inactive carts should automatically be deleted from the database during garbage collection. - -::: tip -You can control how long a cart should go without being updated before it gets deleted [`purgeInactiveCartsDuration`](#purgeinactivecartsduration) setting. -::: - - - -### `purgeInactiveCartsDuration` - -
- -Allowed types -: `mixed` - -Default value -: `7776000` (90 days) - -Defined by -: [Settings::$purgeInactiveCartsDuration](commerce3:craft\commerce\models\Settings::$purgeInactiveCartsDuration) - -
- -Default length of time before inactive carts are purged. (Defaults to 90 days.) - -See [craft\helpers\ConfigHelper::durationInSeconds()](craft3:craft\helpers\ConfigHelper::durationInSeconds()) for a list of supported value types. - - - -### `updateCartSearchIndexes` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [Settings::$updateCartSearchIndexes](commerce3:craft\commerce\models\Settings::$updateCartSearchIndexes) - -Since -: 3.1.5 - -
- -Whether the search index for a cart should be updated when saving the cart via `commerce/cart/*` controller actions. - -May be set to `false` to reduce performance impact on high-traffic sites. - -::: warning -Setting this to `false` will result in fewer index update queue jobs, but you’ll need to manually re-index orders to ensure up-to-date cart search results in the control panel. -::: - - - -### `validateCartCustomFieldsOnSubmission` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$validateCartCustomFieldsOnSubmission](commerce3:craft\commerce\models\Settings::$validateCartCustomFieldsOnSubmission) - -Since -: 3.0.12 - -
- -Whether to validate custom fields when a cart is updated. - -Set to `true` to allow custom content fields to return validation errors when a cart is updated. - - - -## Orders - -### `freeOrderPaymentStrategy` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'complete'` - -Defined by -: [Settings::$freeOrderPaymentStrategy](commerce3:craft\commerce\models\Settings::$freeOrderPaymentStrategy) - -
- -How Commerce should handle free orders. - -The default `'complete'` setting automatically completes zero-balance orders without forwarding them to the payment gateway. - -The `'process'` setting forwards zero-balance orders to the payment gateway for processing. This can be useful if the customer’s balance -needs to be updated or otherwise adjusted by the payment gateway. - - - -### `minimumTotalPriceStrategy` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'default'` - -Defined by -: [Settings::$minimumTotalPriceStrategy](commerce3:craft\commerce\models\Settings::$minimumTotalPriceStrategy) - -
- -How Commerce should handle minimum total price for an order. - -Options: - -- `'default'` [rounds](commerce3:\craft\commerce\helpers\Currency::round()) the sum of the item subtotal and adjustments. -- `'zero'` returns `0` if the result from `'default'` would’ve been negative; minimum order total is `0`. -- `'shipping'` returns the total shipping cost if the `'default'` result would’ve been negative; minimum order total equals shipping amount. - - - -### `orderReferenceFormat` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'{{number[:7]}}'` - -Defined by -: [Settings::$orderReferenceFormat](commerce3:craft\commerce\models\Settings::$orderReferenceFormat) - -
- -Human-friendly reference number format for orders. Result must be unique. - -See [Order Numbers](orders-carts.md#order-numbers). - - - -### `pdfAllowRemoteImages` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$pdfAllowRemoteImages](commerce3:craft\commerce\models\Settings::$pdfAllowRemoteImages) - -
- -Whether to allow non-local images in generated order PDFs. - - - -### `pdfPaperOrientation` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'portrait'` - -Defined by -: [Settings::$pdfPaperOrientation](commerce3:craft\commerce\models\Settings::$pdfPaperOrientation) - -
- -The orientation of the paper to use for generated order PDF files. - -Options are `'portrait'` and `'landscape'`. - - - -### `pdfPaperSize` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'letter'` - -Defined by -: [Settings::$pdfPaperSize](commerce3:craft\commerce\models\Settings::$pdfPaperSize) - -
- -The size of the paper to use for generated order PDFs. - -The full list of supported paper sizes can be found [in the dompdf library](https://github.com/dompdf/dompdf/blob/master/src/Adapter/CPDF.php#L45). - - - -### `requireBillingAddressAtCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$requireBillingAddressAtCheckout](commerce3:craft\commerce\models\Settings::$requireBillingAddressAtCheckout) - -
- -Whether a billing address is required before making payment on an order. - - - -### `requireShippingAddressAtCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$requireShippingAddressAtCheckout](commerce3:craft\commerce\models\Settings::$requireShippingAddressAtCheckout) - -
- -Whether a shipping address is required before making payment on an order. - - - -### `requireShippingMethodSelectionAtCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$requireShippingMethodSelectionAtCheckout](commerce3:craft\commerce\models\Settings::$requireShippingMethodSelectionAtCheckout) - -
- -Whether shipping method selection is required before making payment on an order. - - - -### `updateBillingDetailsUrl` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [Settings::$updateBillingDetailsUrl](commerce3:craft\commerce\models\Settings::$updateBillingDetailsUrl) - -
- -URL for a user to resolve billing issues with their subscription. - -::: tip -The example templates include [a template for this page](https://github.com/craftcms/commerce/tree/main/example-templates/dist/shop/plans/update-billing-details.twig). -::: - - - -### `useBillingAddressForTax` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$useBillingAddressForTax](commerce3:craft\commerce\models\Settings::$useBillingAddressForTax) - -
- -Whether taxes should be calculated based on the billing address instead of the shipping address. - - - -### `validateBusinessTaxIdAsVatId` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$validateBusinessTaxIdAsVatId](commerce3:craft\commerce\models\Settings::$validateBusinessTaxIdAsVatId) - -
- -Whether to enable validation requiring the `businessTaxId` to be a valid VAT ID. - -When set to `false`, no validation is applied to `businessTaxId`. - -When set to `true`, `businessTaxId` must contain a valid VAT ID. - -::: tip -This setting strictly toggles input validation and has no impact on tax configuration or behavior elsewhere in the system. -::: - - - -## Payments - -### `allowPartialPaymentOnCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$allowPartialPaymentOnCheckout](commerce3:craft\commerce\models\Settings::$allowPartialPaymentOnCheckout) - -
- -Whether [partial payment](making-payments.md#checkout-with-partial-payment) can be made from the front end when the gateway allows them. - -The `false` default does not allow partial payments on the front end. - - - -### `gatewayPostRedirectTemplate` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [Settings::$gatewayPostRedirectTemplate](commerce3:craft\commerce\models\Settings::$gatewayPostRedirectTemplate) - -
- -The path to the template that should be used to perform POST requests to offsite payment gateways. - -The template must contain a form that posts to the URL supplied by the `actionUrl` variable and outputs all hidden inputs with -the `inputs` variable. - -```twig - - - - - Redirecting... - - -
-

Redirecting to payment page...

-

- {{ inputs|raw }} - -

-
- - -``` - -::: tip -Since this template is simply used for redirecting, it only appears for a few seconds, so we suggest making it load fast with minimal -images and inline styles to reduce HTTP requests. -::: - -If empty (default), each gateway will decide how to handle after-payment redirects. - - - -### `paymentCurrency` - -
- -Allowed types -: [array](https://php.net/language.types.array) - -Default value -: `null` - -Defined by -: [Settings::$paymentCurrency](commerce3:craft\commerce\models\Settings::$paymentCurrency) - -
- -ISO codes for supported payment currencies. - -See [Payment Currencies](payment-currencies.md). - - - -## Units - -### `dimensionUnits` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'mm'` - -Defined by -: [Settings::$dimensionUnits](commerce3:craft\commerce\models\Settings::$dimensionUnits) - -
- -Unit type for dimension measurements. - -Options: - -- `'mm'` -- `'cm'` -- `'m'` -- `'ft'` -- `'in'` - - - -### `weightUnits` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'g'` - -Defined by -: [Settings::$weightUnits](commerce3:craft\commerce\models\Settings::$weightUnits) - -
- -Units to be used for weight measurements. - -Options: - -- `'g'` -- `'kg'` -- `'lb'` - - - - - + +!!!include(docs/.artifacts/commerce/3.x/config.md)!!! diff --git a/docs/commerce/3.x/orders-carts.md b/docs/commerce/3.x/orders-carts.md index 694785ffc..12cd62b3a 100644 --- a/docs/commerce/3.x/orders-carts.md +++ b/docs/commerce/3.x/orders-carts.md @@ -1,6 +1,8 @@ --- sidebarDepth: 2 +containsGeneratedContent: yes --- + # Orders & Carts Variants are added to a _cart_ that can be completed to become an _order_. Carts and orders are both listed in the control panel under **Commerce** → **Orders**. @@ -756,1396 +758,5 @@ We can display an order with a given order number by doing the following: Order queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only orders that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching orders as arrays of data, rather than [Order](commerce3:craft\commerce\elements\Order) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [customer](#customer) | Narrows the query results based on the customer. -| [customerId](#customerid) | Narrows the query results based on the customer, per their ID. -| [dateAuthorized](#dateauthorized) | Narrows the query results based on the orders’ authorized dates. -| [dateCreated](#datecreated) | Narrows the query results based on the orders’ creation dates. -| [dateOrdered](#dateordered) | Narrows the query results based on the orders’ completion dates. -| [datePaid](#datepaid) | Narrows the query results based on the orders’ paid dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the orders’ last-updated dates. -| [email](#email) | Narrows the query results based on the customers’ email addresses. -| [expiryDate](#expirydate) | Narrows the query results based on the orders’ expiry dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [gateway](#gateway) | Narrows the query results based on the gateway. -| [gatewayId](#gatewayid) | Narrows the query results based on the gateway, per its ID. -| [hasLineItems](#haslineitems) | Narrows the query results to only orders that have line items. -| [hasPurchasables](#haspurchasables) | Narrows the query results to only orders that have certain purchasables. -| [hasTransactions](#hastransactions) | Narrows the query results to only carts that have at least one transaction. -| [id](#id) | Narrows the query results based on the orders’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [isCompleted](#iscompleted) | Narrows the query results to only orders that are completed. -| [isPaid](#ispaid) | Narrows the query results to only orders that are paid. -| [isUnpaid](#isunpaid) | Narrows the query results to only orders that are not paid. -| [limit](#limit) | Determines the number of orders that should be returned. -| [number](#number) | Narrows the query results based on the order number. -| [offset](#offset) | Determines how many orders should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the orders should be returned in. (If empty, defaults to `id ASC`.) -| [orderLanguage](#orderlanguage) | Narrows the query results based on the order language, per the language string provided. -| [orderSiteId](#ordersiteid) | Narrows the query results based on the order language, per the language string provided. -| [orderStatus](#orderstatus) | Narrows the query results based on the order statuses. -| [orderStatusId](#orderstatusid) | Narrows the query results based on the order statuses, per their IDs. -| [origin](#origin) | Narrows the query results based on the origin. -| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. -| [reference](#reference) | Narrows the query results based on the order reference. -| [relatedTo](#relatedto) | Narrows the query results to only orders that are related to certain other elements. -| [search](#search) | Narrows the query results to only orders that match a search query. -| [shortNumber](#shortnumber) | Narrows the query results based on the order short number. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the orders’ IDs in the `elements_sites` table. -| [trashed](#trashed) | Narrows the query results to only orders that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the orders’ UIDs. -| [user](#user) | Narrows the query results based on the customer’s user account. -| [with](#with) | Causes the query to return matching orders eager-loaded with related elements. -| [withAddresses](#withaddresses) | Eager loads the the shipping and billing addressees on the resulting orders. -| [withAdjustments](#withadjustments) | Eager loads the order adjustments on the resulting orders. -| [withAll](#withall) | Eager loads all relational data (addresses, adjustents, customers, line items, transactions) for the resulting orders. -| [withCustomer](#withcustomer) | Eager loads the customer (and related user) on the resulting orders. -| [withLineItems](#withlineitems) | Eager loads the line items on the resulting orders. -| [withTransactions](#withtransactions) | Eager loads the transactions on the resulting orders. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only orders that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all orders that are related to myCategoryA and myCategoryB #} -{% set orders = craft.orders() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all orders that are related to $myCategoryA and $myCategoryB -$orders = \craft\commerce\elements\Order::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all orders, regardless of status #} -{% set orders = craft.orders() - .anyStatus() - .all() %} -``` - -```php -// Fetch all orders, regardless of status -$orders = \craft\commerce\elements\Order::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching orders as arrays of data, rather than [Order](commerce3:craft\commerce\elements\Order) objects. - - - - - -::: code -```twig -{# Fetch orders as arrays #} -{% set orders = craft.orders() - .asArray() - .all() %} -``` - -```php -// Fetch orders as arrays -$orders = \craft\commerce\elements\Order::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `customer` - -Narrows the query results based on the customer. - -Possible values include: - -| Value | Fetches orders… -| - | - -| a [Customer](commerce3:craft\commerce\models\Customer) object | with a customer represented by the object. - - - -::: code -```twig -{# Fetch the current user's orders #} -{% set orders = craft.orders() - .customer(currentUser.customerFieldHandle) - .all() %} -``` - -```php -// Fetch the current user's orders -$user = Craft::$app->user->getIdentity(); -$orders = \craft\commerce\elements\Order::find() - ->customer($user->customerFieldHandle) - ->all(); -``` -::: - - -#### `customerId` - -Narrows the query results based on the customer, per their ID. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a customer with an ID of 1. -| `'not 1'` | not with a customer with an ID of 1. -| `[1, 2]` | with a customer with an ID of 1 or 2. -| `['not', 1, 2]` | not with a customer with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the current user's orders #} -{% set orders = craft.orders() - .customerId(currentUser.customerFieldHandle.id) - .all() %} -``` - -```php -// Fetch the current user's orders -$user = Craft::$app->user->getIdentity(); -$orders = \craft\commerce\elements\Order::find() - ->customerId($user->customerFieldHandle->id) - ->all(); -``` -::: - - -#### `dateAuthorized` - -Narrows the query results based on the orders’ authorized dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were authorized on or after 2018-04-01. -| `'< 2018-05-01'` | that were authorized before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders that were authorized recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set orders = craft.orders() - .dateAuthorized(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch orders that were authorized recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateAuthorized(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateCreated` - -Narrows the query results based on the orders’ creation dates. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set orders = craft.orders() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch orders created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateOrdered` - -Narrows the query results based on the orders’ completion dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were completed on or after 2018-04-01. -| `'< 2018-05-01'` | that were completed before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders that were completed recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set orders = craft.orders() - .dateOrdered(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch orders that were completed recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateOrdered(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `datePaid` - -Narrows the query results based on the orders’ paid dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were paid on or after 2018-04-01. -| `'< 2018-05-01'` | that were paid before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders that were paid for recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set orders = craft.orders() - .datePaid(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch orders that were paid for recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->datePaid(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the orders’ last-updated dates. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set orders = craft.orders() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch orders updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `email` - -Narrows the query results based on the customers’ email addresses. - -Possible values include: - -| Value | Fetches orders with customers… -| - | - -| `'foo@bar.baz'` | with an email of `foo@bar.baz`. -| `'not foo@bar.baz'` | not with an email of `foo@bar.baz`. -| `'*@bar.baz'` | with an email that ends with `@bar.baz`. - - - -::: code -```twig -{# Fetch orders from customers with a .co.uk domain on their email address #} -{% set orders = craft.orders() - .email('*.co.uk') - .all() %} -``` - -```php -// Fetch orders from customers with a .co.uk domain on their email address -$orders = \craft\commerce\elements\Order::find() - ->email('*.co.uk') - ->all(); -``` -::: - - -#### `expiryDate` - -Narrows the query results based on the orders’ expiry dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. -| `'< 2020-05-01'` | that will expire before 2020-05-01 -| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. - - - -::: code -```twig -{# Fetch orders expiring this month #} -{% set nextMonth = date('first day of next month')|atom %} - -{% set orders = craft.orders() - .expiryDate("< #{nextMonth}") - .all() %} -``` - -```php -// Fetch orders expiring this month -$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->expiryDate("< {$nextMonth}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - - - -::: code -```twig -{# Fetch orders in a specific order #} -{% set orders = craft.orders() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch orders in a specific order -$orders = \craft\commerce\elements\Order::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `gateway` - -Narrows the query results based on the gateway. - -Possible values include: - -| Value | Fetches orders… -| - | - -| a [Gateway](commerce3:craft\commerce\base\Gateway) object | with a gateway represented by the object. - - - - -#### `gatewayId` - -Narrows the query results based on the gateway, per its ID. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a gateway with an ID of 1. -| `'not 1'` | not with a gateway with an ID of 1. -| `[1, 2]` | with a gateway with an ID of 1 or 2. -| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. - - - - -#### `hasLineItems` - -Narrows the query results to only orders that have line items. - - - -::: code -```twig -{# Fetch orders that do or do not have line items #} -{% set orders = craft.orders() - .hasLineItems() - .all() %} -``` - -```php -// Fetch unpaid orders -$orders = \craft\commerce\elements\Order::find() - ->hasLineItems() - ->all(); -``` -::: - - -#### `hasPurchasables` - -Narrows the query results to only orders that have certain purchasables. - -Possible values include: - -| Value | Fetches orders… -| - | - -| a [PurchasableInterface](commerce3:craft\commerce\base\PurchasableInterface) object | with a purchasable represented by the object. -| an array of [PurchasableInterface](commerce3:craft\commerce\base\PurchasableInterface) objects | with all the purchasables represented by the objects. - - - - -#### `hasTransactions` - -Narrows the query results to only carts that have at least one transaction. - - - -::: code -```twig -{# Fetch carts that have attempted payments #} -{% set orders = craft.orders() - .hasTransactions() - .all() %} -``` - -```php -// Fetch carts that have attempted payments -$orders = \craft\commerce\elements\Order::find() - ->hasTransactions() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the orders’ IDs. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the order by its ID #} -{% set order = craft.orders() - .id(1) - .one() %} -``` - -```php -// Fetch the order by its ID -$order = \craft\commerce\elements\Order::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch orders in reverse #} -{% set orders = craft.orders() - .inReverse() - .all() %} -``` - -```php -// Fetch orders in reverse -$orders = \craft\commerce\elements\Order::find() - ->inReverse() - ->all(); -``` -::: - - -#### `isCompleted` - -Narrows the query results to only orders that are completed. - - - -::: code -```twig -{# Fetch completed orders #} -{% set orders = craft.orders() - .isCompleted() - .all() %} -``` - -```php -// Fetch completed orders -$orders = \craft\commerce\elements\Order::find() - ->isCompleted() - ->all(); -``` -::: - - -#### `isPaid` - -Narrows the query results to only orders that are paid. - - - -::: code -```twig -{# Fetch paid orders #} -{% set orders = craft.orders() - .isPaid() - .all() %} -``` - -```php -// Fetch paid orders -$orders = \craft\commerce\elements\Order::find() - ->isPaid() - ->all(); -``` -::: - - -#### `isUnpaid` - -Narrows the query results to only orders that are not paid. - - - -::: code -```twig -{# Fetch unpaid orders #} -{% set orders = craft.orders() - .isUnpaid() - .all() %} -``` - -```php -// Fetch unpaid orders -$orders = \craft\commerce\elements\Order::find() - ->isUnpaid() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of orders that should be returned. - - - -::: code -```twig -{# Fetch up to 10 orders #} -{% set orders = craft.orders() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 orders -$orders = \craft\commerce\elements\Order::find() - ->limit(10) - ->all(); -``` -::: - - -#### `number` - -Narrows the query results based on the order number. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'` | with a matching order number - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderNumber = craft.app.request.getQueryParam('number') %} -{% set order = craft.orders() - .number(orderNumber) - .one() %} -``` - -```php -// Fetch the requested order -$orderNumber = Craft::$app->request->getQueryParam('number'); -$order = \craft\commerce\elements\Order::find() - ->number($orderNumber) - ->one(); -``` -::: - - -#### `offset` - -Determines how many orders should be skipped in the results. - - - -::: code -```twig -{# Fetch all orders except for the first 3 #} -{% set orders = craft.orders() - .offset(3) - .all() %} -``` - -```php -// Fetch all orders except for the first 3 -$orders = \craft\commerce\elements\Order::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the orders should be returned in. (If empty, defaults to `id ASC`.) - - - -::: code -```twig -{# Fetch all orders in order of date created #} -{% set orders = craft.orders() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all orders in order of date created -$orders = \craft\commerce\elements\Order::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `orderLanguage` - -Narrows the query results based on the order language, per the language string provided. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `en` | with an order language that is `'en'`. -| `'not en'` | not with an order language that is not `'en'`. -| `['en', 'en-us']` | with an order language that is `'en'` or `'en-us'`. -| `['not', 'en']` | not with an order language that is not `'en'`. - - - -::: code -```twig -{# Fetch orders with an order status with an ID of 1 #} -{% set orders = craft.orders() - .orderLanguage('en') - .all() %} -``` - -```php -// Fetch orders with an order status with an ID of 1 -$orders = \craft\commerce\elements\Order::find() - ->orderLanguage('en') - ->all(); -``` -::: - - -#### `orderSiteId` - -Narrows the query results based on the order language, per the language string provided. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an order site ID of 1. -| `'not 1'` | not with an order site ID that is no 1. -| `[1, 2]` | with an order site ID of 1 or 2. -| `['not', 1, 2]` | not with an order site ID of 1 or 2. - - - -::: code -```twig -{# Fetch orders with an order site ID of 1 #} -{% set orders = craft.orders() - .orderSiteId(1) - .all() %} -``` - -```php -// Fetch orders with an order site ID of 1 -$orders = \craft\commerce\elements\Order::find() - ->orderSiteId(1) - ->all(); -``` -::: - - -#### `orderStatus` - -Narrows the query results based on the order statuses. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'foo'` | with an order status with a handle of `foo`. -| `'not foo'` | not with an order status with a handle of `foo`. -| `['foo', 'bar']` | with an order status with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not with an order status with a handle of `foo` or `bar`. -| a [OrderStatus](commerce3:craft\commerce\models\OrderStatus) object | with an order status represented by the object. - - - -::: code -```twig -{# Fetch shipped orders #} -{% set orders = craft.orders() - .orderStatus('shipped') - .all() %} -``` - -```php -// Fetch shipped orders -$orders = \craft\commerce\elements\Order::find() - ->orderStatus('shipped') - ->all(); -``` -::: - - -#### `orderStatusId` - -Narrows the query results based on the order statuses, per their IDs. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an order status with an ID of 1. -| `'not 1'` | not with an order status with an ID of 1. -| `[1, 2]` | with an order status with an ID of 1 or 2. -| `['not', 1, 2]` | not with an order status with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch orders with an order status with an ID of 1 #} -{% set orders = craft.orders() - .orderStatusId(1) - .all() %} -``` - -```php -// Fetch orders with an order status with an ID of 1 -$orders = \craft\commerce\elements\Order::find() - ->orderStatusId(1) - ->all(); -``` -::: - - -#### `origin` - -Narrows the query results based on the origin. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'web'` | with an origin of `web`. -| `'not remote'` | not with an origin of `remote`. -| `['web', 'cp']` | with an order origin of `web` or `cp`. -| `['not', 'remote', 'cp']` | not with an origin of `web` or `cp`. - - - -::: code -```twig -{# Fetch shipped orders #} -{% set orders = craft.orders() - .origin('web') - .all() %} -``` - -```php -// Fetch shipped orders -$orders = \craft\commerce\elements\Order::find() - ->origin('web') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned -for Site B. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique orders from Site A, or Site B if they don’t exist in Site A #} -{% set orders = craft.orders() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique orders from Site A, or Site B if they don’t exist in Site A -$orders = \craft\commerce\elements\Order::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `reference` - -Narrows the query results based on the order reference. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'xxxx'` | with a matching order reference - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderReference = craft.app.request.getQueryParam('ref') %} -{% set order = craft.orders() - .reference(orderReference) - .one() %} -``` - -```php -// Fetch the requested order -$orderReference = Craft::$app->request->getQueryParam('ref'); -$order = \craft\commerce\elements\Order::find() - ->reference($orderReference) - ->one(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only orders that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all orders that are related to myCategory #} -{% set orders = craft.orders() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all orders that are related to $myCategory -$orders = \craft\commerce\elements\Order::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only orders that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all orders that match the search query #} -{% set orders = craft.orders() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all orders that match the search query -$orders = \craft\commerce\elements\Order::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `shortNumber` - -Narrows the query results based on the order short number. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'xxxxxxx'` | with a matching order number - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderNumber = craft.app.request.getQueryParam('shortNumber') %} -{% set order = craft.orders() - .shortNumber(orderNumber) - .one() %} -``` - -```php -// Fetch the requested order -$orderNumber = Craft::$app->request->getQueryParam('shortNumber'); -$order = \craft\commerce\elements\Order::find() - ->shortNumber($orderNumber) - ->one(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the orders’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the order by its ID in the elements_sites table #} -{% set order = craft.orders() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the order by its ID in the elements_sites table -$order = \craft\commerce\elements\Order::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `trashed` - -Narrows the query results to only orders that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed orders #} -{% set orders = craft.orders() - .trashed() - .all() %} -``` - -```php -// Fetch trashed orders -$orders = \craft\commerce\elements\Order::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the orders’ UIDs. - - - - - -::: code -```twig -{# Fetch the order by its UID #} -{% set order = craft.orders() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the order by its UID -$order = \craft\commerce\elements\Order::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `user` - -Narrows the query results based on the customer’s user account. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a customer with a user account ID of 1. -| a [User](https://docs.craftcms.com/api/v3/craft-elements-user.html) object | with a customer with a user account represented by the object. - - - -::: code -```twig -{# Fetch the current user's orders #} -{% set orders = craft.orders() - .user(currentUser) - .all() %} -``` - -```php -// Fetch the current user's orders -$user = Craft::$app->user->getIdentity(); -$orders = \craft\commerce\elements\Order::find() - ->user($user) - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching orders eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch orders eager-loaded with the "Related" field’s relations #} -{% set orders = craft.orders() - .with(['related']) - .all() %} -``` - -```php -// Fetch orders eager-loaded with the "Related" field’s relations -$orders = \craft\commerce\elements\Order::find() - ->with(['related']) - ->all(); -``` -::: - - -#### `withAddresses` - -Eager loads the the shipping and billing addressees on the resulting orders. - -Possible values include: - -| Value | Fetches addresses -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withAdjustments` - -Eager loads the order adjustments on the resulting orders. - -Possible values include: - -| Value | Fetches adjustments -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withAll` - -Eager loads all relational data (addresses, adjustents, customers, line items, transactions) for the resulting orders. - -Possible values include: - -| Value | Fetches addresses, adjustents, customers, line items, transactions -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withCustomer` - -Eager loads the customer (and related user) on the resulting orders. - -Possible values include: - -| Value | Fetches adjustments -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withLineItems` - -Eager loads the line items on the resulting orders. - -Possible values include: - -| Value | Fetches line items… -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withTransactions` - -Eager loads the transactions on the resulting orders. - -Possible values include: - -| Value | Fetches transactions… -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - - - + +!!!include(docs/.artifacts/commerce/3.x/orders-carts.md)!!! diff --git a/docs/commerce/3.x/products-variants.md b/docs/commerce/3.x/products-variants.md index 1f1984b20..05801ecab 100644 --- a/docs/commerce/3.x/products-variants.md +++ b/docs/commerce/3.x/products-variants.md @@ -1,6 +1,8 @@ --- sidebarDepth: 2 +containsGeneratedContent: yes --- + # Products & Variants A _product_ is an [element](/3.x/elements.md) that describes what’s for sale. A _variant_ is the [purchasable](purchasables.md) the customer ultimately orders. @@ -209,2578 +211,5 @@ To fetch the same information with GraphQL, we could write a query like this: } ``` -## Product Query Parameters - -Product queries support the following parameters: - - - - - - - -| Param | Description -| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [after](#product-after) | Narrows the query results to only products that were posted on or after a certain date. -| [afterPopulate](#product-afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#product-andrelatedto) | Narrows the query results to only products that are related to certain other elements. -| [anyStatus](#product-anystatus) | Removes element filters based on their statuses. -| [asArray](#product-asarray) | Causes the query to return matching products as arrays of data, rather than [Product](commerce3:craft\commerce\elements\Product) objects. -| [availableForPurchase](#product-availableforpurchase) | Narrows the query results to only products that are available for purchase. -| [before](#product-before) | Narrows the query results to only products that were posted before a certain date. -| [cache](#product-cache) | Enables query cache for this Query. -| [clearCachedResult](#product-clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#product-datecreated) | Narrows the query results based on the products’ creation dates. -| [dateUpdated](#product-dateupdated) | Narrows the query results based on the products’ last-updated dates. -| [defaultHeight](#product-defaultheight) | Narrows the query results based on the products’ default variant height dimension IDs. -| [defaultLength](#product-defaultlength) | Narrows the query results based on the products’ default variant length dimension IDs. -| [defaultPrice](#product-defaultprice) | Narrows the query results based on the products’ default variant price. -| [defaultSku](#product-defaultsku) | Narrows the query results based on the default productvariants defaultSku -| [defaultWeight](#product-defaultweight) | Narrows the query results based on the products’ default variant weight dimension IDs. -| [defaultWidth](#product-defaultwidth) | Narrows the query results based on the products’ default variant width dimension IDs. -| [expiryDate](#product-expirydate) | Narrows the query results based on the products’ expiry dates. -| [fixedOrder](#product-fixedorder) | Causes the query results to be returned in the order specified by [id](#product-id). -| [hasVariant](#product-hasvariant) | Narrows the query results to only products that have certain variants. -| [id](#product-id) | Narrows the query results based on the products’ IDs. -| [ignorePlaceholders](#product-ignoreplaceholders) | Causes the query to return matching products as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#product-inreverse) | Causes the query results to be returned in reverse order. -| [limit](#product-limit) | Determines the number of products that should be returned. -| [offset](#product-offset) | Determines how many products should be skipped in the results. -| [orderBy](#product-orderby) | Determines the order that the products should be returned in. (If empty, defaults to `postDate DESC`.) -| [postDate](#product-postdate) | Narrows the query results based on the products’ post dates. -| [preferSites](#product-prefersites) | If [unique](#product-unique) is set, this determines which site should be selected when querying multi-site elements. -| [relatedTo](#product-relatedto) | Narrows the query results to only products that are related to certain other elements. -| [search](#product-search) | Narrows the query results to only products that match a search query. -| [site](#product-site) | Determines which site(s) the products should be queried in. -| [siteId](#product-siteid) | Determines which site(s) the products should be queried in, per the site’s ID. -| [siteSettingsId](#product-sitesettingsid) | Narrows the query results based on the products’ IDs in the `elements_sites` table. -| [slug](#product-slug) | Narrows the query results based on the products’ slugs. -| [status](#product-status) | Narrows the query results based on the products’ statuses. -| [title](#product-title) | Narrows the query results based on the products’ titles. -| [trashed](#product-trashed) | Narrows the query results to only products that have been soft-deleted. -| [type](#product-type) | Narrows the query results based on the products’ types. -| [typeId](#product-typeid) | Narrows the query results based on the products’ types, per the types’ IDs. -| [uid](#product-uid) | Narrows the query results based on the products’ UIDs. -| [unique](#product-unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uri](#product-uri) | Narrows the query results based on the products’ URIs. -| [with](#product-with) | Causes the query to return matching products eager-loaded with related elements. - - - - - -

# after

- -Narrows the query results to only products that were posted on or after a certain date. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'2018-04-01'` | that were posted after 2018-04-01. -| a [DateTime](https://php.net/class.datetime) object | that were posted after the date represented by the object. - - - -::: code -```twig -{# Fetch products posted this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set products = craft.products() - .after(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch products posted this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$products = \craft\commerce\elements\Product::find() - ->after($firstDayOfMonth) - ->all(); -``` -::: - - -

# afterPopulate

- -Performs any post-population processing on elements. - - - - - - - - - - -

# andRelatedTo

- -Narrows the query results to only products that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all products that are related to myCategoryA and myCategoryB #} -{% set products = craft.products() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all products that are related to $myCategoryA and $myCategoryB -$products = \craft\commerce\elements\Product::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -

# anyStatus

- -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all products, regardless of status #} -{% set products = craft.products() - .anyStatus() - .all() %} -``` - -```php -// Fetch all products, regardless of status -$products = \craft\commerce\elements\Product::find() - ->anyStatus() - ->all(); -``` -::: - - -

# asArray

- -Causes the query to return matching products as arrays of data, rather than [Product](commerce3:craft\commerce\elements\Product) objects. - - - - - -::: code -```twig -{# Fetch products as arrays #} -{% set products = craft.products() - .asArray() - .all() %} -``` - -```php -// Fetch products as arrays -$products = \craft\commerce\elements\Product::find() - ->asArray() - ->all(); -``` -::: - - -

# availableForPurchase

- -Narrows the query results to only products that are available for purchase. - - - -::: code -```twig -{# Fetch products that are available for purchase #} -{% set products = craft.products() - .availableForPurchase() - .all() %} -``` - -```php -// Fetch products that are available for purchase -$products = \craft\commerce\elements\Product::find() - ->availableForPurchase() - ->all(); -``` -::: - - -

# before

- -Narrows the query results to only products that were posted before a certain date. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'2018-04-01'` | that were posted before 2018-04-01. -| a [DateTime](https://php.net/class.datetime) object | that were posted before the date represented by the object. - - - -::: code -```twig -{# Fetch products posted before this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set products = craft.products() - .before(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch products posted before this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$products = \craft\commerce\elements\Product::find() - ->before($firstDayOfMonth) - ->all(); -``` -::: - - -

# cache

- -Enables query cache for this Query. - - - - - - - - - - -

# clearCachedResult

- -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -

# dateCreated

- -Narrows the query results based on the products’ creation dates. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch products created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set products = craft.products() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch products created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -

# dateUpdated

- -Narrows the query results based on the products’ last-updated dates. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch products updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set products = craft.products() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch products updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -

# defaultHeight

- -Narrows the query results based on the products’ default variant height dimension IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with a dimension of 1. -| `'not 1'` | not a dimension of 1. -| `[1, 2]` | of a a dimension 1 or 2. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product default dimension of 1 #} -{% set products = craft.products() - .defaultHeight(1) - .all() %} -``` - -```php -// Fetch products of the product default dimension of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultHeight(1) - ->all(); -``` -::: - - -

# defaultLength

- -Narrows the query results based on the products’ default variant length dimension IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with a dimension of 1. -| `'not 1'` | not a dimension of 1. -| `[1, 2]` | of a a dimension 1 or 2. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product default dimension of 1 #} -{% set products = craft.products() - .defaulLength(1) - .all() %} -``` - -```php -// Fetch products of the product default dimension of 1 -$products = \craft\commerce\elements\Product::find() - ->defaulLength(1) - ->all(); -``` -::: - - -

# defaultPrice

- -Narrows the query results based on the products’ default variant price. - -Possible values include: - -| Value | Fetches products… -| - | - -| `10` | of a price of 10. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a default variant price between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product type with an ID of 1 #} -{% set products = craft.products() - .defaultPrice(1) - .all() %} -``` - -```php -// Fetch products of the product type with an ID of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultPrice(1) - ->all(); -``` -::: - - -

# defaultSku

- -Narrows the query results based on the default productvariants defaultSku - -Possible values include: - -| Value | Fetches products… -| - | - -| `xxx-001` | of products defaukt SKU of `xxx-001`. -| `'not xxx-001'` | not a defaukt SKU of `xxx-001`. -| `['not xxx-001', 'not xxx-002']` | of a default SKU of xxx-001 or xxx-002. -| `['not', `xxx-001`, `xxx-002`]` | not a product defaukt SKU of `xxx-001` or `xxx-001`. - - - -::: code -```twig -{# Fetch products of the product defaukt SKU of `xxx-001` #} -{% set products = craft.products() - .defaultSku('xxx-001') - .all() %} -``` - -```php -// Fetch products of the product defaukt SKU of `xxx-001` -$products = \craft\commerce\elements\Product::find() - ->defaultSku('xxx-001') - ->all(); -``` -::: - - -

# defaultWeight

- -Narrows the query results based on the products’ default variant weight dimension IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with a dimension of 1. -| `'not 1'` | not a dimension of 1. -| `[1, 2]` | of a a dimension 1 or 2. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product default dimension of 1 #} -{% set products = craft.products() - .defaultWeight(1) - .all() %} -``` - -```php -// Fetch products of the product default dimension of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultWeight(1) - ->all(); -``` -::: - - -

# defaultWidth

- -Narrows the query results based on the products’ default variant width dimension IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with a dimension of 1. -| `'not 1'` | not a dimension of 1. -| `[1, 2]` | of a a dimension 1 or 2. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product default dimension of 1 #} -{% set products = craft.products() - .defaultWidth(1) - .all() %} -``` - -```php -// Fetch products of the product default dimension of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultWidth(1) - ->all(); -``` -::: - - -

# expiryDate

- -Narrows the query results based on the products’ expiry dates. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. -| `'< 2020-05-01'` | that will expire before 2020-05-01 -| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. - - - -::: code -```twig -{# Fetch products expiring this month #} -{% set nextMonth = date('first day of next month')|atom %} - -{% set products = craft.products() - .expiryDate("< #{nextMonth}") - .all() %} -``` - -```php -// Fetch products expiring this month -$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->expiryDate("< {$nextMonth}") - ->all(); -``` -::: - - -

# fixedOrder

- -Causes the query results to be returned in the order specified by [id](#product-id). - - - - - -::: code -```twig -{# Fetch products in a specific order #} -{% set products = craft.products() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch products in a specific order -$products = \craft\commerce\elements\Product::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -

# hasVariant

- -Narrows the query results to only products that have certain variants. - -Possible values include: - -| Value | Fetches products… -| - | - -| a [VariantQuery](commerce3:craft\commerce\elements\db\VariantQuery) object | with variants that match the query. - - - - -

# id

- -Narrows the query results based on the products’ IDs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the product by its ID #} -{% set product = craft.products() - .id(1) - .one() %} -``` - -```php -// Fetch the product by its ID -$product = \craft\commerce\elements\Product::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#product-fixedorder) if you want the results to be returned in a specific order. -::: - - -

# ignorePlaceholders

- -Causes the query to return matching products as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -

# inReverse

- -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch products in reverse #} -{% set products = craft.products() - .inReverse() - .all() %} -``` - -```php -// Fetch products in reverse -$products = \craft\commerce\elements\Product::find() - ->inReverse() - ->all(); -``` -::: - - -

# limit

- -Determines the number of products that should be returned. - - - -::: code -```twig -{# Fetch up to 10 products #} -{% set products = craft.products() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 products -$products = \craft\commerce\elements\Product::find() - ->limit(10) - ->all(); -``` -::: - - -

# offset

- -Determines how many products should be skipped in the results. - - - -::: code -```twig -{# Fetch all products except for the first 3 #} -{% set products = craft.products() - .offset(3) - .all() %} -``` - -```php -// Fetch all products except for the first 3 -$products = \craft\commerce\elements\Product::find() - ->offset(3) - ->all(); -``` -::: - - -

# orderBy

- -Determines the order that the products should be returned in. (If empty, defaults to `postDate DESC`.) - - - -::: code -```twig -{# Fetch all products in order of date created #} -{% set products = craft.products() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all products in order of date created -$products = \craft\commerce\elements\Product::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -

# postDate

- -Narrows the query results based on the products’ post dates. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. -| `'< 2018-05-01'` | that were posted before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch products posted last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set products = craft.products() - .postDate(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch products posted last month -$start = new \DateTime('first day of next month')->format(\DateTime::ATOM); -$end = new \DateTime('first day of this month')->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->postDate(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -

# preferSites

- -If [unique](#product-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned -for Site B. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique products from Site A, or Site B if they don’t exist in Site A #} -{% set products = craft.products() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique products from Site A, or Site B if they don’t exist in Site A -$products = \craft\commerce\elements\Product::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -

# relatedTo

- -Narrows the query results to only products that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all products that are related to myCategory #} -{% set products = craft.products() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all products that are related to $myCategory -$products = \craft\commerce\elements\Product::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - - - -Narrows the query results to only products that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all products that match the search query #} -{% set products = craft.products() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all products that match the search query -$products = \craft\commerce\elements\Product::find() - ->search($searchQuery) - ->all(); -``` -::: - - -

# site

- -Determines which site(s) the products should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](https://docs.craftcms.com/api/v3/craft-models-site.html) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#product-unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch products from the Foo site #} -{% set products = craft.products() - .site('foo') - .all() %} -``` - -```php -// Fetch products from the Foo site -$products = \craft\commerce\elements\Product::find() - ->site('foo') - ->all(); -``` -::: - - -

# siteId

- -Determines which site(s) the products should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch products from the site with an ID of 1 #} -{% set products = craft.products() - .siteId(1) - .all() %} -``` - -```php -// Fetch products from the site with an ID of 1 -$products = \craft\commerce\elements\Product::find() - ->siteId(1) - ->all(); -``` -::: - - -

# siteSettingsId

- -Narrows the query results based on the products’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the product by its ID in the elements_sites table #} -{% set product = craft.products() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the product by its ID in the elements_sites table -$product = \craft\commerce\elements\Product::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -

# slug

- -Narrows the query results based on the products’ slugs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | with a slug of `foo`. -| `'foo*'` | with a slug that begins with `foo`. -| `'*foo'` | with a slug that ends with `foo`. -| `'*foo*'` | with a slug that contains `foo`. -| `'not *foo*'` | with a slug that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested product slug from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the product with that slug #} -{% set product = craft.products() - .slug(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested product slug from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the product with that slug -$product = \craft\commerce\elements\Product::find() - ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -

# status

- -Narrows the query results based on the products’ statuses. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'live'` _(default)_ | that are live. -| `'pending'` | that are pending (enabled with a Post Date in the future). -| `'expired'` | that are expired (enabled with an Expiry Date in the past). -| `'disabled'` | that are disabled. -| `['live', 'pending']` | that are live or pending. - - - -::: code -```twig -{# Fetch disabled products #} -{% set products = craft.products() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled products -$products = \craft\commerce\elements\Product::find() - ->status('disabled') - ->all(); -``` -::: - - -

# title

- -Narrows the query results based on the products’ titles. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch products with a title that contains "Foo" #} -{% set products = craft.products() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch products with a title that contains "Foo" -$products = \craft\commerce\elements\Product::find() - ->title('*Foo*') - ->all(); -``` -::: - - -

# trashed

- -Narrows the query results to only products that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed products #} -{% set products = craft.products() - .trashed() - .all() %} -``` - -```php -// Fetch trashed products -$products = \craft\commerce\elements\Product::find() - ->trashed() - ->all(); -``` -::: - - -

# type

- -Narrows the query results based on the products’ types. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | of a type with a handle of `foo`. -| `'not foo'` | not of a type with a handle of `foo`. -| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. -| an [ProductType](commerce3:craft\commerce\models\ProductType) object | of a type represented by the object. - - - -::: code -```twig -{# Fetch products with a Foo product type #} -{% set products = craft.products() - .type('foo') - .all() %} -``` - -```php -// Fetch products with a Foo product type -$products = \craft\commerce\elements\Product::find() - ->type('foo') - ->all(); -``` -::: - - -

# typeId

- -Narrows the query results based on the products’ types, per the types’ IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with an ID of 1. -| `'not 1'` | not of a type with an ID of 1. -| `[1, 2]` | of a type with an ID of 1 or 2. -| `['not', 1, 2]` | not of a type with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch products of the product type with an ID of 1 #} -{% set products = craft.products() - .typeId(1) - .all() %} -``` - -```php -// Fetch products of the product type with an ID of 1 -$products = \craft\commerce\elements\Product::find() - ->typeId(1) - ->all(); -``` -::: - - -

# uid

- -Narrows the query results based on the products’ UIDs. - - - - - -::: code -```twig -{# Fetch the product by its UID #} -{% set product = craft.products() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the product by its UID -$product = \craft\commerce\elements\Product::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -

# unique

- -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique products across all sites #} -{% set products = craft.products() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique products across all sites -$products = \craft\commerce\elements\Product::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -

# uri

- -Narrows the query results based on the products’ URIs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the product with that URI #} -{% set product = craft.products() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the product with that URI -$product = \craft\commerce\elements\Product::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -

# with

- -Causes the query to return matching products eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch products eager-loaded with the "Related" field’s relations #} -{% set products = craft.products() - .with(['related']) - .all() %} -``` - -```php -// Fetch products eager-loaded with the "Related" field’s relations -$products = \craft\commerce\elements\Product::find() - ->with(['related']) - ->all(); -``` -::: - - - - - -## Variants - -A variant describes the individual properties of a product as an item that may be purchased. - -Those properties inclue a SKU, price, and dimensions. Even if a product doesn’t appear to have any variants in the control panel, it still uses one *default variant* behind the scenes. - -Let’s compare examples of a single-variant an multi-variant product: a paperback book and a t-shirt. - -A book sold in only one format does not have meaningful variations for the customer to choose, but it would still have a specific SKU, price, weight, and dimensions. A single, implicit default variant needs to exist and that’s what would be added to the cart. - -A t-shirt, on the other hand, would have at least one variant for each available color and size combination. You wouldn’t sell the t-shirt without a specific color and size, so multiple variants would be necessary. If the shirt came in “small” and “large” sizes and “red” or “blue” colors, four unique variants could exist: - -- small, red -- small, blue -- large, red -- large, blue - -### Variant Properties - -Each variant includes the following unique properties: - -| Property | Type | Required? | -| ------------- | ------------------- | -------------- | -| SKU | string | | -| Price | number | | -| Stock | number or unlimited | | -| Allowed Qty | range | | -| Dimensions | number (l × w × h) | | -| Weight | number | | -| Related Sales | relationship (Sale) | | - -Each variant may also have any number of custom fields to allow other distinguishing traits. - -Commerce does not automatically create every possible unique variant for you—that’s up to the store manager. - -### Default Variant - -Every product has a default variant. Whenever a product is created, a default variant will be created as well. - -If a product type has multiple variants enabled, the author can choose which one should be used by default. Products that do not have multiple variants still have a default variant, but the author can’t add additional variants. - -For a single-variant product, variant details are shown in a unified view with custom product fields: - -![Single-Variant Product](./images/single-variant.png) - -When a product supports multiple variants, the default variant will be identified in a **Variants** field where more variants can be added: - -![Multi-Variant Product](./images/multi-variant.png) - -### Variant Stock - -Variants can have unlimited stock or a specific quantity. - -A finite stock amount will automatically be reduced whenever someone completes an order, until the stock amount reaches zero. At that point the variant’s “Available for purchase” setting won’t be changed, but zero-stock variants cannot be added to a cart. - -For returns or refunds that aren’t ultimately delivered to the customer, you’ll need to either manually update product stock or use [the `orderStatusChange` event](extend/events.md#orderstatuschange) to automate further stock adjustments. - -## Querying Variants - -You can fetch variants using **variant queries**. - -::: code -```twig -{# Create a new variant query #} -{% set myVariantQuery = craft.variants() %} -``` -```php -// Create a new variant query -$myVariantQuery = \craft\commerce\elements\Variant::find(); -``` -```graphql -# Create a new variant query -{ - variants { - # ... - } -} -``` -::: - -Once you’ve created a variant query, you can set [parameters](#variant-query-parameters) on it to narrow down the results, and then [execute it](https://craftcms.com/docs/3.x/element-queries.html#executing-element-queries) by calling `.all()`. An array of [Variant](commerce3:craft\commerce\elements\Variant) objects will be returned. - -You can also fetch only the number of items a query might return, which is better for performance when you don’t need the variant data. - -::: code -```twig -{# Count all enabled variants #} -{% set myVariantCount = craft.variants() - .status('enabled') - .count() %} -``` -```php -use craft\commerce\elements\Variant; - -// Count all enabled variants -$myVariantCount = Variant::find() - ->status(Variant::STATUS_ENABLED) - ->count(); -``` -```graphql -# Count all enabled variants -{ - variantCount(status: "enabled") -} -``` -::: - -::: tip -See [Element Queries](https://craftcms.com/docs/3.x/element-queries.html) in the Craft docs to learn about how element queries work. -::: - -### Example - -We can display a specific variant by its ID in Twig by doing the following: - -1. Create a variant query with `craft.variants()`. -2. Set the [`id`](#id) parameter on it. -3. Fetch the variant with `.one()`. -4. Output information about the variant as HTML. - -```twig -{# Get the requested variant ID from the query string #} -{% set variantId = craft.app.request.getQueryParam('id') %} - -{# Create a variant query with the 'id' parameter #} -{% set myVariantQuery = craft.variants() - .id(variantId) %} - -{# Fetch the variant #} -{% set variant = myVariantQuery.one() %} - -{# Make sure it exists #} -{% if not variant %} - {% exit 404 %} -{% endif %} - -{# Display the variant #} -

{{ variant.title }}

- -``` - -Fetching the equivalent with GraphQL could look like this: - -```graphql -# Fetch variant having ID = 46 -{ - variants(id: 46) { - title - } -} -``` - -## Variant Query Parameters - -Variant queries support the following parameters: - - - - - - - -| Param | Description -| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#variant-afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#variant-andrelatedto) | Narrows the query results to only variants that are related to certain other elements. -| [anyStatus](#variant-anystatus) | Removes element filters based on their statuses. -| [asArray](#variant-asarray) | Causes the query to return matching variants as arrays of data, rather than [Variant](commerce3:craft\commerce\elements\Variant) objects. -| [cache](#variant-cache) | Enables query cache for this Query. -| [clearCachedResult](#variant-clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCreated](#variant-datecreated) | Narrows the query results based on the variants’ creation dates. -| [dateUpdated](#variant-dateupdated) | Narrows the query results based on the variants’ last-updated dates. -| [fixedOrder](#variant-fixedorder) | Causes the query results to be returned in the order specified by [id](#variant-id). -| [hasProduct](#variant-hasproduct) | Narrows the query results to only variants for certain products. -| [hasSales](#variant-hassales) | Narrows the query results to only variants that are on sale. -| [hasStock](#variant-hasstock) | Narrows the query results to only variants that have stock. -| [hasUnlimitedStock](#variant-hasunlimitedstock) | Narrows the query results to only variants that have been set to unlimited stock. -| [height](#variant-height) | Narrows the query results based on the variants’ height dimension. -| [id](#variant-id) | Narrows the query results based on the variants’ IDs. -| [ignorePlaceholders](#variant-ignoreplaceholders) | Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#variant-inreverse) | Causes the query results to be returned in reverse order. -| [isDefault](#variant-isdefault) | Narrows the query results to only default variants. -| [length](#variant-length) | Narrows the query results based on the variants’ length dimension. -| [limit](#variant-limit) | Determines the number of variants that should be returned. -| [maxQty](#variant-maxqty) | Narrows the query results based on the variants’ max quantity. -| [minQty](#variant-minqty) | Narrows the query results based on the variants’ min quantity. -| [offset](#variant-offset) | Determines how many variants should be skipped in the results. -| [orderBy](#variant-orderby) | Determines the order that the variants should be returned in. (If empty, defaults to `sortOrder ASC`.) -| [preferSites](#variant-prefersites) | If [unique](#variant-unique) is set, this determines which site should be selected when querying multi-site elements. -| [price](#variant-price) | Narrows the query results based on the variants’ price. -| [product](#variant-product) | Narrows the query results based on the variants’ product. -| [productId](#variant-productid) | Narrows the query results based on the variants’ products’ IDs. -| [relatedTo](#variant-relatedto) | Narrows the query results to only variants that are related to certain other elements. -| [search](#variant-search) | Narrows the query results to only variants that match a search query. -| [site](#variant-site) | Determines which site(s) the variants should be queried in. -| [siteId](#variant-siteid) | Determines which site(s) the variants should be queried in, per the site’s ID. -| [siteSettingsId](#variant-sitesettingsid) | Narrows the query results based on the variants’ IDs in the `elements_sites` table. -| [sku](#variant-sku) | Narrows the query results based on the variants’ SKUs. -| [status](#variant-status) | Narrows the query results based on the variants’ statuses. -| [stock](#variant-stock) | Narrows the query results based on the variants’ stock. -| [title](#variant-title) | Narrows the query results based on the variants’ titles. -| [trashed](#variant-trashed) | Narrows the query results to only variants that have been soft-deleted. -| [typeId](#variant-typeid) | Narrows the query results based on the variants’ product types, per their IDs. -| [uid](#variant-uid) | Narrows the query results based on the variants’ UIDs. -| [unique](#variant-unique) | Determines whether only elements with unique IDs should be returned by the query. -| [weight](#variant-weight) | Narrows the query results based on the variants’ weight dimension. -| [width](#variant-width) | Narrows the query results based on the variants’ width dimension. -| [with](#variant-with) | Causes the query to return matching variants eager-loaded with related elements. - - - - - -

# afterPopulate

- -Performs any post-population processing on elements. - - - - - - - - - - -

# andRelatedTo

- -Narrows the query results to only variants that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all variants that are related to myCategoryA and myCategoryB #} -{% set variants = craft.variants() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all variants that are related to $myCategoryA and $myCategoryB -$variants = \craft\commerce\elements\Variant::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -

# anyStatus

- -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all variants, regardless of status #} -{% set variants = craft.variants() - .anyStatus() - .all() %} -``` - -```php -// Fetch all variants, regardless of status -$variants = \craft\commerce\elements\Variant::find() - ->anyStatus() - ->all(); -``` -::: - - -

# asArray

- -Causes the query to return matching variants as arrays of data, rather than [Variant](commerce3:craft\commerce\elements\Variant) objects. - - - - - -::: code -```twig -{# Fetch variants as arrays #} -{% set variants = craft.variants() - .asArray() - .all() %} -``` - -```php -// Fetch variants as arrays -$variants = \craft\commerce\elements\Variant::find() - ->asArray() - ->all(); -``` -::: - - -

# cache

- -Enables query cache for this Query. - - - - - - - - - - -

# clearCachedResult

- -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -

# dateCreated

- -Narrows the query results based on the variants’ creation dates. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch variants created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set variants = craft.variants() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch variants created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$variants = \craft\commerce\elements\Variant::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -

# dateUpdated

- -Narrows the query results based on the variants’ last-updated dates. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch variants updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set variants = craft.variants() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch variants updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$variants = \craft\commerce\elements\Variant::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -

# fixedOrder

- -Causes the query results to be returned in the order specified by [id](#variant-id). - - - - - -::: code -```twig -{# Fetch variants in a specific order #} -{% set variants = craft.variants() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch variants in a specific order -$variants = \craft\commerce\elements\Variant::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -

# hasProduct

- -Narrows the query results to only variants for certain products. - -Possible values include: - -| Value | Fetches variants… -| - | - -| a [ProductQuery](commerce3:craft\commerce\elements\db\ProductQuery) object | for products that match the query. - - - - -

# hasSales

- -Narrows the query results to only variants that are on sale. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `true` | on sale -| `false` | not on sale - - - - -

# hasStock

- -Narrows the query results to only variants that have stock. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `true` | with stock. -| `false` | with no stock. - - - - -

# hasUnlimitedStock

- -Narrows the query results to only variants that have been set to unlimited stock. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `true` | with unlimited stock checked. -| `false` | with unlimited stock not checked. - - - - -

# height

- -Narrows the query results based on the variants’ height dimension. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a height of 100. -| `'>= 100'` | with a height of at least 100. -| `'< 100'` | with a height of less than 100. - - - - -

# id

- -Narrows the query results based on the variants’ IDs. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the variant by its ID #} -{% set variant = craft.variants() - .id(1) - .one() %} -``` - -```php -// Fetch the variant by its ID -$variant = \craft\commerce\elements\Variant::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#variant-fixedorder) if you want the results to be returned in a specific order. -::: - - -

# ignorePlaceholders

- -Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -

# inReverse

- -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch variants in reverse #} -{% set variants = craft.variants() - .inReverse() - .all() %} -``` - -```php -// Fetch variants in reverse -$variants = \craft\commerce\elements\Variant::find() - ->inReverse() - ->all(); -``` -::: - - -

# isDefault

- -Narrows the query results to only default variants. - - - -::: code -```twig -{# Fetch default variants #} -{% set variants = craft.variants() - .isDefault() - .all() %} -``` - -```php -// Fetch default variants -$variants = \craft\commerce\elements\Variant::find() - ->isDefault() - ->all(); -``` -::: - - -

# length

- -Narrows the query results based on the variants’ length dimension. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a length of 100. -| `'>= 100'` | with a length of at least 100. -| `'< 100'` | with a length of less than 100. - - - - -

# limit

- -Determines the number of variants that should be returned. - - - -::: code -```twig -{# Fetch up to 10 variants #} -{% set variants = craft.variants() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 variants -$variants = \craft\commerce\elements\Variant::find() - ->limit(10) - ->all(); -``` -::: - - -

# maxQty

- -Narrows the query results based on the variants’ max quantity. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a maxQty of 100. -| `'>= 100'` | with a maxQty of at least 100. -| `'< 100'` | with a maxQty of less than 100. - - - - -

# minQty

- -Narrows the query results based on the variants’ min quantity. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a minQty of 100. -| `'>= 100'` | with a minQty of at least 100. -| `'< 100'` | with a minQty of less than 100. - - - - -

# offset

- -Determines how many variants should be skipped in the results. - - - -::: code -```twig -{# Fetch all variants except for the first 3 #} -{% set variants = craft.variants() - .offset(3) - .all() %} -``` - -```php -// Fetch all variants except for the first 3 -$variants = \craft\commerce\elements\Variant::find() - ->offset(3) - ->all(); -``` -::: - - -

# orderBy

- -Determines the order that the variants should be returned in. (If empty, defaults to `sortOrder ASC`.) - - - -::: code -```twig -{# Fetch all variants in order of date created #} -{% set variants = craft.variants() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all variants in order of date created -$variants = \craft\commerce\elements\Variant::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -

# preferSites

- -If [unique](#variant-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned -for Site B. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique variants from Site A, or Site B if they don’t exist in Site A #} -{% set variants = craft.variants() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique variants from Site A, or Site B if they don’t exist in Site A -$variants = \craft\commerce\elements\Variant::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -

# price

- -Narrows the query results based on the variants’ price. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a price of 100. -| `'>= 100'` | with a price of at least 100. -| `'< 100'` | with a price of less than 100. - - - - -

# product

- -Narrows the query results based on the variants’ product. - -Possible values include: - -| Value | Fetches variants… -| - | - -| a [Product](commerce3:craft\commerce\elements\Product) object | for a product represented by the object. - - - - -

# productId

- -Narrows the query results based on the variants’ products’ IDs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | for a product with an ID of 1. -| `[1, 2]` | for product with an ID of 1 or 2. -| `['not', 1, 2]` | for product not with an ID of 1 or 2. - - - - -

# relatedTo

- -Narrows the query results to only variants that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all variants that are related to myCategory #} -{% set variants = craft.variants() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all variants that are related to $myCategory -$variants = \craft\commerce\elements\Variant::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - - - -Narrows the query results to only variants that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all variants that match the search query #} -{% set variants = craft.variants() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all variants that match the search query -$variants = \craft\commerce\elements\Variant::find() - ->search($searchQuery) - ->all(); -``` -::: - - -

# site

- -Determines which site(s) the variants should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](https://docs.craftcms.com/api/v3/craft-models-site.html) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#variant-unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch variants from the Foo site #} -{% set variants = craft.variants() - .site('foo') - .all() %} -``` - -```php -// Fetch variants from the Foo site -$variants = \craft\commerce\elements\Variant::find() - ->site('foo') - ->all(); -``` -::: - - -

# siteId

- -Determines which site(s) the variants should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch variants from the site with an ID of 1 #} -{% set variants = craft.variants() - .siteId(1) - .all() %} -``` - -```php -// Fetch variants from the site with an ID of 1 -$variants = \craft\commerce\elements\Variant::find() - ->siteId(1) - ->all(); -``` -::: - - -

# siteSettingsId

- -Narrows the query results based on the variants’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the variant by its ID in the elements_sites table #} -{% set variant = craft.variants() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the variant by its ID in the elements_sites table -$variant = \craft\commerce\elements\Variant::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -

# sku

- -Narrows the query results based on the variants’ SKUs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'foo'` | with a SKU of `foo`. -| `'foo*'` | with a SKU that begins with `foo`. -| `'*foo'` | with a SKU that ends with `foo`. -| `'*foo*'` | with a SKU that contains `foo`. -| `'not *foo*'` | with a SKU that doesn’t contain `foo`. -| `['*foo*', '*bar*'` | with a SKU that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a SKU that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested variant SKU from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the variant with that slug #} -{% set variant = craft.variants() - .sku(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested variant SKU from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the variant with that slug -$variant = \craft\commerce\elements\Variant::find() - ->sku(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -

# status

- -Narrows the query results based on the variants’ statuses. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'enabled'` _(default)_ | that are enabled. -| `'disabled'` | that are disabled. -| `['not', 'disabled']` | that are not disabled. - - - -::: code -```twig -{# Fetch disabled variants #} -{% set variants = craft.variants() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled variants -$variants = \craft\commerce\elements\Variant::find() - ->status('disabled') - ->all(); -``` -::: - - -

# stock

- -Narrows the query results based on the variants’ stock. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `0` | with no stock. -| `'>= 5'` | with a stock of at least 5. -| `'< 10'` | with a stock of less than 10. - - - - -

# title

- -Narrows the query results based on the variants’ titles. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch variants with a title that contains "Foo" #} -{% set variants = craft.variants() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch variants with a title that contains "Foo" -$variants = \craft\commerce\elements\Variant::find() - ->title('*Foo*') - ->all(); -``` -::: - - -

# trashed

- -Narrows the query results to only variants that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed variants #} -{% set variants = craft.variants() - .trashed() - .all() %} -``` - -```php -// Fetch trashed variants -$variants = \craft\commerce\elements\Variant::find() - ->trashed() - ->all(); -``` -::: - - -

# typeId

- -Narrows the query results based on the variants’ product types, per their IDs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | for a product of a type with an ID of 1. -| `[1, 2]` | for product of a type with an ID of 1 or 2. -| `['not', 1, 2]` | for product of a type not with an ID of 1 or 2. - - - - -

# uid

- -Narrows the query results based on the variants’ UIDs. - - - - - -::: code -```twig -{# Fetch the variant by its UID #} -{% set variant = craft.variants() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the variant by its UID -$variant = \craft\commerce\elements\Variant::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -

# unique

- -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique variants across all sites #} -{% set variants = craft.variants() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique variants across all sites -$variants = \craft\commerce\elements\Variant::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -

# weight

- -Narrows the query results based on the variants’ weight dimension. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a weight of 100. -| `'>= 100'` | with a weight of at least 100. -| `'< 100'` | with a weight of less than 100. - - - - -

# width

- -Narrows the query results based on the variants’ width dimension. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a width of 100. -| `'>= 100'` | with a width of at least 100. -| `'< 100'` | with a width of less than 100. - - - - -

# with

- -Causes the query to return matching variants eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch variants eager-loaded with the "Related" field’s relations #} -{% set variants = craft.variants() - .with(['related']) - .all() %} -``` - -```php -// Fetch variants eager-loaded with the "Related" field’s relations -$variants = \craft\commerce\elements\Variant::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/commerce/3.x/products-variants.md)!!! diff --git a/docs/commerce/3.x/subscriptions.md b/docs/commerce/3.x/subscriptions.md index 07f0f7e69..dcd1235d8 100644 --- a/docs/commerce/3.x/subscriptions.md +++ b/docs/commerce/3.x/subscriptions.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Subscriptions Subscriptions are handled by gateways. A payment gateway must handle subscription plan support in order to establish a Commerce subscription for a user. @@ -98,1073 +102,5 @@ We can display all of the current user’s subscriptions by doing the following: Subscription queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only subscriptions that are related to certain other elements. -| [anyStatus](#anystatus) | Removes element filters based on their statuses. -| [asArray](#asarray) | Causes the query to return matching subscriptions as arrays of data, rather than [Subscription](commerce3:craft\commerce\elements\Subscription) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). -| [dateCanceled](#datecanceled) | Narrows the query results based on the subscriptions’ cancellation date. -| [dateCreated](#datecreated) | Narrows the query results based on the subscriptions’ creation dates. -| [dateExpired](#dateexpired) | Narrows the query results based on the subscriptions’ expiration date. -| [dateSuspended](#datesuspended) | Narrows the query results based on the subscriptions’ suspension date. -| [dateUpdated](#dateupdated) | Narrows the query results based on the subscriptions’ last-updated dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [gatewayId](#gatewayid) | Narrows the query results based on the gateway, per its ID. -| [hasStarted](#hasstarted) | Narrows the query results to only subscriptions that have started. -| [id](#id) | Narrows the query results based on the subscriptions’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [isCanceled](#iscanceled) | Narrows the query results to only subscriptions that are canceled. -| [isExpired](#isexpired) | Narrows the query results to only subscriptions that have expired. -| [isSuspended](#issuspended) | Narrows the query results to only subscriptions that are suspended. -| [limit](#limit) | Determines the number of subscriptions that should be returned. -| [nextPaymentDate](#nextpaymentdate) | Narrows the query results based on the subscriptions’ next payment dates. -| [offset](#offset) | Determines how many subscriptions should be skipped in the results. -| [onTrial](#ontrial) | Narrows the query results to only subscriptions that are on trial. -| [orderBy](#orderby) | Determines the order that the subscriptions should be returned in. (If empty, defaults to `dateCreated DESC`.) -| [orderId](#orderid) | Narrows the query results based on the order, per its ID. -| [plan](#plan) | Narrows the query results based on the subscription plan. -| [planId](#planid) | Narrows the query results based on the subscription plans’ IDs. -| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. -| [reference](#reference) | Narrows the query results based on the reference. -| [relatedTo](#relatedto) | Narrows the query results to only subscriptions that are related to certain other elements. -| [search](#search) | Narrows the query results to only subscriptions that match a search query. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the subscriptions’ IDs in the `elements_sites` table. -| [status](#status) | Narrows the query results based on the subscriptions’ statuses. -| [trashed](#trashed) | Narrows the query results to only subscriptions that have been soft-deleted. -| [trialDays](#trialdays) | Narrows the query results based on the number of trial days. -| [uid](#uid) | Narrows the query results based on the subscriptions’ UIDs. -| [user](#user) | Narrows the query results based on the subscriptions’ user accounts. -| [userId](#userid) | Narrows the query results based on the subscriptions’ user accounts’ IDs. -| [with](#with) | Causes the query to return matching subscriptions eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only subscriptions that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all subscriptions that are related to myCategoryA and myCategoryB #} -{% set subscriptions = craft.subscriptions() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all subscriptions that are related to $myCategoryA and $myCategoryB -$subscriptions = \craft\commerce\elements\Subscription::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `anyStatus` - -Removes element filters based on their statuses. - - - - - -::: code -```twig -{# Fetch all subscriptions, regardless of status #} -{% set subscriptions = craft.subscriptions() - .anyStatus() - .all() %} -``` - -```php -// Fetch all subscriptions, regardless of status -$subscriptions = \craft\commerce\elements\Subscription::find() - ->anyStatus() - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching subscriptions as arrays of data, rather than [Subscription](commerce3:craft\commerce\elements\Subscription) objects. - - - - - -::: code -```twig -{# Fetch subscriptions as arrays #} -{% set subscriptions = craft.subscriptions() - .asArray() - .all() %} -``` - -```php -// Fetch subscriptions as arrays -$subscriptions = \craft\commerce\elements\Subscription::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/3.x/element-queries.html#cache). - - - - - - -#### `dateCanceled` - -Narrows the query results based on the subscriptions’ cancellation date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were canceled on or after 2018-04-01. -| `'< 2018-05-01'` | that were canceled before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were canceled between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions that were canceled recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateCanceled(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that were canceled recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateCanceled(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateCreated` - -Narrows the query results based on the subscriptions’ creation dates. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch subscriptions created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateExpired` - -Narrows the query results based on the subscriptions’ expiration date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that expired on or after 2018-04-01. -| `'< 2018-05-01'` | that expired before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that expired between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions that expired recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateExpired(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that expired recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateExpired(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateSuspended` - -Narrows the query results based on the subscriptions’ suspension date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were suspended on or after 2018-04-01. -| `'< 2018-05-01'` | that were suspended before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were suspended between 2018-04-01 and 2018-05-01. - - -::: code -```twig -{# Fetch subscriptions that were suspended recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateSuspended(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that were suspended recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateSuspended(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the subscriptions’ last-updated dates. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch subscriptions updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - - - -::: code -```twig -{# Fetch subscriptions in a specific order #} -{% set subscriptions = craft.subscriptions() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch subscriptions in a specific order -$subscriptions = \craft\commerce\elements\Subscription::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `gatewayId` - -Narrows the query results based on the gateway, per its ID. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with a gateway with an ID of 1. -| `'not 1'` | not with a gateway with an ID of 1. -| `[1, 2]` | with a gateway with an ID of 1 or 2. -| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. - - - - -#### `hasStarted` - -Narrows the query results to only subscriptions that have started. - - - -::: code -```twig -{# Fetch started subscriptions #} -{% set subscriptions = craft.subscriptions() - .hasStarted() - .all() %} -``` - -```php -// Fetch started subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->hasStarted() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the subscriptions’ IDs. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the subscription by its ID #} -{% set subscription = craft.subscriptions() - .id(1) - .one() %} -``` - -```php -// Fetch the subscription by its ID -$subscription = \craft\commerce\elements\Subscription::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v3/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch subscriptions in reverse #} -{% set subscriptions = craft.subscriptions() - .inReverse() - .all() %} -``` - -```php -// Fetch subscriptions in reverse -$subscriptions = \craft\commerce\elements\Subscription::find() - ->inReverse() - ->all(); -``` -::: - - -#### `isCanceled` - -Narrows the query results to only subscriptions that are canceled. - - - -::: code -```twig -{# Fetch canceled subscriptions #} -{% set subscriptions = craft.subscriptions() - .isCanceled() - .all() %} -``` - -```php -// Fetch canceled subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isCanceled() - ->all(); -``` -::: - - -#### `isExpired` - -Narrows the query results to only subscriptions that have expired. - - - -::: code -```twig -{# Fetch expired subscriptions #} -{% set subscriptions = craft.subscriptions() - .isExpired() - .all() %} -``` - -```php -// Fetch expired subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isExpired() - ->all(); -``` -::: - - -#### `isSuspended` - -Narrows the query results to only subscriptions that are suspended. - - - -::: code -```twig -{# Fetch suspended subscriptions #} -{% set subscriptions = craft.subscriptions() - .isSuspended() - .all() %} -``` - -```php -// Fetch suspended subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isSuspended() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of subscriptions that should be returned. - - - -::: code -```twig -{# Fetch up to 10 subscriptions #} -{% set subscriptions = craft.subscriptions() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->limit(10) - ->all(); -``` -::: - - -#### `nextPaymentDate` - -Narrows the query results based on the subscriptions’ next payment dates. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | with a next payment on or after 2018-04-01. -| `'< 2018-05-01'` | with a next payment before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | with a next payment between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions with a payment due soon #} -{% set aWeekFromNow = date('+7 days')|atom %} - -{% set subscriptions = craft.subscriptions() - .nextPaymentDate("< #{aWeekFromNow}") - .all() %} -``` - -```php -// Fetch subscriptions with a payment due soon -$aWeekFromNow = new \DateTime('+7 days')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->nextPaymentDate("< {$aWeekFromNow}") - ->all(); -``` -::: - - -#### `offset` - -Determines how many subscriptions should be skipped in the results. - - - -::: code -```twig -{# Fetch all subscriptions except for the first 3 #} -{% set subscriptions = craft.subscriptions() - .offset(3) - .all() %} -``` - -```php -// Fetch all subscriptions except for the first 3 -$subscriptions = \craft\commerce\elements\Subscription::find() - ->offset(3) - ->all(); -``` -::: - - -#### `onTrial` - -Narrows the query results to only subscriptions that are on trial. - - - -::: code -```twig -{# Fetch trialed subscriptions #} -{% set subscriptions = craft.subscriptions() - .onTrial() - .all() %} -``` - -```php -// Fetch trialed subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isPaid() - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the subscriptions should be returned in. (If empty, defaults to `dateCreated DESC`.) - - - -::: code -```twig -{# Fetch all subscriptions in order of date created #} -{% set subscriptions = craft.subscriptions() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all subscriptions in order of date created -$subscriptions = \craft\commerce\elements\Subscription::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `orderId` - -Narrows the query results based on the order, per its ID. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with an order with an ID of 1. -| `'not 1'` | not with an order with an ID of 1. -| `[1, 2]` | with an order with an ID of 1 or 2. -| `['not', 1, 2]` | not with an order with an ID of 1 or 2. - - - - -#### `plan` - -Narrows the query results based on the subscription plan. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'foo'` | for a plan with a handle of `foo`. -| `['foo', 'bar']` | for plans with a handle of `foo` or `bar`. -| a [Plan](commerce3:craft\commerce\base\Plan) object | for a plan represented by the object. - - - -::: code -```twig -{# Fetch Supporter plan subscriptions #} -{% set subscriptions = craft.subscriptions() - .plan('supporter') - .all() %} -``` - -```php -// Fetch Supporter plan subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->plan('supporter') - ->all(); -``` -::: - - -#### `planId` - -Narrows the query results based on the subscription plans’ IDs. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | for a plan with an ID of 1. -| `[1, 2]` | for plans with an ID of 1 or 2. -| `['not', 1, 2]` | for plans not with an ID of 1 or 2. - - - - -#### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v3/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site C, and Bar will be returned -for Site B. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A #} -{% set subscriptions = craft.subscriptions() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A -$subscriptions = \craft\commerce\elements\Subscription::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `reference` - -Narrows the query results based on the reference. - - - - - - -#### `relatedTo` - -Narrows the query results to only subscriptions that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/3.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all subscriptions that are related to myCategory #} -{% set subscriptions = craft.subscriptions() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all subscriptions that are related to $myCategory -$subscriptions = \craft\commerce\elements\Subscription::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only subscriptions that match a search query. - - - -See [Searching](https://craftcms.com/docs/3.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all subscriptions that match the search query #} -{% set subscriptions = craft.subscriptions() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all subscriptions that match the search query -$subscriptions = \craft\commerce\elements\Subscription::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the subscriptions’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the subscription by its ID in the elements_sites table #} -{% set subscription = craft.subscriptions() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the subscription by its ID in the elements_sites table -$subscription = \craft\commerce\elements\Subscription::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the subscriptions’ statuses. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'active'` _(default)_ | that are active. -| `'expired'` | that have expired. - - - -::: code -```twig -{# Fetch expired subscriptions #} -{% set subscriptions = craft.subscriptions() - .status('expired') - .all() %} -``` - -```php -// Fetch expired subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->status('expired') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only subscriptions that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed subscriptions #} -{% set subscriptions = craft.subscriptions() - .trashed() - .all() %} -``` - -```php -// Fetch trashed subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->trashed() - ->all(); -``` -::: - - -#### `trialDays` - -Narrows the query results based on the number of trial days. - - - - - - -#### `uid` - -Narrows the query results based on the subscriptions’ UIDs. - - - - - -::: code -```twig -{# Fetch the subscription by its UID #} -{% set subscription = craft.subscriptions() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the subscription by its UID -$subscription = \craft\commerce\elements\Subscription::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `user` - -Narrows the query results based on the subscriptions’ user accounts. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'foo'` | for a user account with a username of `foo` -| `['foo', 'bar']` | for user accounts with a username of `foo` or `bar`. -| a [User](https://docs.craftcms.com/api/v3/craft-elements-user.html) object | for a user account represented by the object. - - - -::: code -```twig -{# Fetch the current user's subscriptions #} -{% set subscriptions = craft.subscriptions() - .user(currentUser) - .all() %} -``` - -```php -// Fetch the current user's subscriptions -$user = Craft::$app->user->getIdentity(); -$subscriptions = \craft\commerce\elements\Subscription::find() - ->user($user) - ->all(); -``` -::: - - -#### `userId` - -Narrows the query results based on the subscriptions’ user accounts’ IDs. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | for a user account with an ID of 1. -| `[1, 2]` | for user accounts with an ID of 1 or 2. -| `['not', 1, 2]` | for user accounts not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the current user's subscriptions #} -{% set subscriptions = craft.subscriptions() - .userId(currentUser.id) - .all() %} -``` - -```php -// Fetch the current user's subscriptions -$user = Craft::$app->user->getIdentity(); -$subscriptions = \craft\commerce\elements\Subscription::find() - ->userId($user->id) - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching subscriptions eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/3.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch subscriptions eager-loaded with the "Related" field’s relations #} -{% set subscriptions = craft.subscriptions() - .with(['related']) - .all() %} -``` - -```php -// Fetch subscriptions eager-loaded with the "Related" field’s relations -$subscriptions = \craft\commerce\elements\Subscription::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/commerce/3.x/subscriptions.md)!!! diff --git a/docs/commerce/4.x/addresses.md b/docs/commerce/4.x/addresses.md index e866b9bdf..cb8ee45fe 100644 --- a/docs/commerce/4.x/addresses.md +++ b/docs/commerce/4.x/addresses.md @@ -56,7 +56,7 @@ That `getStore().getStore()` is not a typo! We’re getting the + +Your customers can save the billing and/or shipping addresses on their cart to their address book when they check out. These options are stored as `saveBillingAddressOnOrderComplete` and `saveShippingAddressOnOrderComplete` on the cart or object. You may send corresponding values any time you update the customer’s cart: + +```twig +{% set cart = craft.commerce.carts.cart %} + +
+ {{ csrfInput() }} + {{ actionInput('commerce/cart/update-cart') }} + + {# ... #} + + {% if currentUser %} + {% if cart.billingAddressId and not cart.sourceBillingAddressId %} + {{ input('checkbox', 'saveBillingAddressOnOrderComplete', 1, { checked: cart.saveBillingAddressOnOrderComplete }) }} + {% endif %} + + {% if cart.shippingAddressId and not cart.sourceShippingAddressId %} + {{ input('checkbox', 'saveShippingAddressOnOrderComplete', 1, { checked: cart.saveShippingAddressOnOrderComplete }) }} + {% endif %} + {% endif %} + + +
+``` + +This example guards against saving an existing address, indicated by the presence of a `cart.sourceBillingAddressId` or `cart.sourceShippingAddressId`. + +Both properties can be set at once with the `saveAddressesOnOrderComplete` parameter, but you are still responsible for deriving UI state from the underlying address-specific properties: + +```twig +{% set cart = craft.commerce.carts.cart %} + +
+ {{ csrfInput() }} + {{ actionInput('commerce/cart/update-cart') }} + + {% if currentUser and ((cart.billingAddressId and not cart.sourceBillingAddressId) or (cart.shippingAddressId and not cart.sourceShippingAddressId)) %} + {{ input('checkbox', 'saveAddressesOnOrderComplete', 1, {checked: cart.saveBillingAddressOnOrderComplete and cart.saveShippingAddressOnOrderComplete}) }} + {% endif %} + + {# ... #} + + +
+``` + +::: tip +The `saveAddress*` properties are only applicable to customers who created addresses directly on the cart. Setting these options to `true` if a _registered_ customer selected an address from their [address book](#auto-fill-from-address-book) has no effect. + +Guests’ addresses are automatically saved to their customer account when [registering at checkout](customers.md#registration-at-checkout). +::: + #### Auto-fill from Address Book -You can allow your customers to populate order addresses with a previously-saved one by sending a `shippingAddressId` and/or `billingAddressId` param when updating the cart. +You can let your customers populate their cart addresses with a previously-saved one by sending a `shippingAddressId` and/or `billingAddressId` param when updating the cart. ```twig {% set cart = craft.commerce.carts.cart %} @@ -199,7 +256,7 @@ You can allow your customers to populate order addresses with a previously-saved ``` -You may need to create custom routes to allow customers to [manage these addresses](/4.x/addresses.md#managing-addresses), or introduce logic in the browser to hide and show new address forms based on the type(s) of addresses you need. +You may need to create custom routes to allow logged-in customers to [manage these addresses](/4.x/addresses.md#managing-addresses), or introduce logic in the template or browser to hide and show new address forms based on the type(s) of addresses you need. #### Update an Existing Address @@ -222,8 +279,12 @@ An address on the cart may be updated in-place by passing individual address pro ``` +You may also send `firstName` and `lastName` properties, separately. + ::: warning -Any field(s) updated on an order address filled from the customer’s address book will _not_ propagate back to the source, and will break the association to it. Sending `shippingAddressId` and `billingAddressId` are only intended to populate an order address with existing information—not keep them synchronized. +Changes to an address in the customer’s address book (via the [`users/save-address` action](/4.x/dev/controller-actions.md#users-save-address)) are copied to any carts it is attached to. + +_However_, any field(s) updated on an order address that was originally populated from the customer’s address book will _not_ propagate back to the source, and will break the association to it. Sending `shippingAddressId` and `billingAddressId` are only intended to populate an order address with existing information, and to track where it originally came from—not bind them in both directions. ::: ### Estimate Cart Addresses @@ -295,6 +356,37 @@ A full example of this can be seen in the [example templates](example-templates. ## Address Book -When logged in, your customers can manage their addresses independently of the cart. Refer to the main [addresses documentation](/4.x/addresses.md) for more information and examples. +When logged in, your customers can manage their addresses independently of a cart. Refer to the main [addresses documentation](/4.x/addresses.md) and to this page’s section on [auto-filling addresses](#auto-fill-from-address-book) for more information and examples. + +### Primary Billing + Shipping Addresses In addition to the [natively supported](/4.x/dev/controller-actions.md#post-users-save-address) params, Commerce will look for `isPrimaryShipping` and `isPrimaryBilling`. These values determine which addresses get attached to a fresh cart when the [autoSetNewCartAddresses](./config-settings.md#autosetnewcartaddresses) option is enabled. + +To add support for setting default addresses, add this code to the [new address](/4.x/addresses.md#new-addresses) and/or [existing addresses](/4.x/addresses.md#existing-addresses) forms: + +```twig +{# Make primary shipping address? #} +{{ hiddenInput('isPrimaryShipping', 0) }} + + +{{ hiddenInput('isPrimaryBilling', 0) }} + +``` + +::: tip +`checkbox` inputs only send a value when checked. In order to support _un_-setting a primary billing or shipping address, you must include the hidden input _before_ the visible checkbox, in the DOM. This ensures that the falsy `0` value is sent when the checkbox is unchecked, differentiating it from simply not sending a value at all (omitting `isPrimaryShipping` or `isPrimaryBilling` entirely makes no changes to the user’s current settings). +::: + +Similarly, you can send `makePrimaryBillingAddress` or `makePrimaryShippingAddress` params along with any `cart/update-cart` request to set an address attached to the cart as the customer’s primary billing or shipping address. Only addresses that retain their `sourceBillingAddressId` or `sourceShippingAddressId` can be configured this way. + +### Address Synchronization diff --git a/docs/commerce/4.x/config-settings.md b/docs/commerce/4.x/config-settings.md index 1435b7a4a..810914a19 100644 --- a/docs/commerce/4.x/config-settings.md +++ b/docs/commerce/4.x/config-settings.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Config Settings In addition to the settings in **Commerce** → **Settings**, the config items below can be saved in a `config/commerce.php` file using the same format as [Craft’s general config settings](/4.x/config/config-settings.md). @@ -37,811 +41,5 @@ You can access the Commerce [general settings model](commerce4:craft\commerce\mo Here’s the full list of Commerce config settings: - - -## System - -### `defaultView` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'commerce/orders'` - -Defined by -: [Settings::$defaultView](commerce4:craft\commerce\models\Settings::$defaultView) - -Since -: 2.2 - -
- -Commerce’s default control panel view. (Defaults to order index.) - - - -### `emailSenderAddress` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [Settings::$emailSenderAddress](commerce4:craft\commerce\models\Settings::$emailSenderAddress) - -
- -Default email address Commerce system messages should be sent from. - -If `null` (default), Craft’s [MailSettings::$fromEmail](craft4:craft\models\MailSettings::$fromEmail) will be used. - - - -### `emailSenderAddressPlaceholder` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [Settings::$emailSenderAddressPlaceholder](commerce4:craft\commerce\models\Settings::$emailSenderAddressPlaceholder) - -
- -Placeholder value displayed for the sender address control panel settings field. - -If `null` (default), Craft’s [MailSettings::$fromEmail](craft4:craft\models\MailSettings::$fromEmail) will be used. - - - -### `emailSenderName` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [Settings::$emailSenderName](commerce4:craft\commerce\models\Settings::$emailSenderName) - -
- -Default from name used for Commerce system emails. - -If `null` (default), Craft’s [MailSettings::$fromName](craft4:craft\models\MailSettings::$fromName) will be used. - - - -### `emailSenderNamePlaceholder` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [Settings::$emailSenderNamePlaceholder](commerce4:craft\commerce\models\Settings::$emailSenderNamePlaceholder) - -
- -Placeholder value displayed for the sender name control panel settings field. - -If `null` (default), Craft’s [MailSettings::$fromName](craft4:craft\models\MailSettings::$fromName) will be used. - - - -### `showEditUserCommerceTab` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [Settings::$showEditUserCommerceTab](commerce4:craft\commerce\models\Settings::$showEditUserCommerceTab) - -Since -: 4.0 - -
- -Whether the [Commerce Tab](customers.md#user-customer-info-tab) should be shown when viewing users in the control panel. - - - -## Cart - -### `activeCartDuration` - -
- -Allowed types -: `mixed` - -Default value -: `3600` (1 hour) - -Defined by -: [Settings::$activeCartDuration](commerce4:craft\commerce\models\Settings::$activeCartDuration) - -Since -: 2.2 - -
- -How long a cart should go without being updated before it’s considered inactive. - -See [craft\helpers\ConfigHelper::durationInSeconds()](craft4:craft\helpers\ConfigHelper::durationInSeconds()) for a list of supported value types. - - - -### `allowCheckoutWithoutPayment` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$allowCheckoutWithoutPayment](commerce4:craft\commerce\models\Settings::$allowCheckoutWithoutPayment) - -Since -: 3.3 - -
- -Whether carts are can be marked as completed without a payment. - - - -### `allowEmptyCartOnCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$allowEmptyCartOnCheckout](commerce4:craft\commerce\models\Settings::$allowEmptyCartOnCheckout) - -Since -: 2.2 - -
- -Whether carts are allowed to be empty on checkout. - - - -### `autoSetCartShippingMethodOption` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$autoSetCartShippingMethodOption](commerce4:craft\commerce\models\Settings::$autoSetCartShippingMethodOption) - -
- -Whether the first available shipping method option should be set automatically on carts. - - - -### `autoSetNewCartAddresses` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [Settings::$autoSetNewCartAddresses](commerce4:craft\commerce\models\Settings::$autoSetNewCartAddresses) - -
- -Whether the user’s primary shipping and billing addresses should be set automatically on new carts. - - - -### `autoSetPaymentSource` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$autoSetPaymentSource](commerce4:craft\commerce\models\Settings::$autoSetPaymentSource) - -Since -: 4.2 - -
- -Whether the user’s primary payment source should be set automatically on new carts. - - - -### `cartVariable` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'cart'` - -Defined by -: [Settings::$cartVariable](commerce4:craft\commerce\models\Settings::$cartVariable) - -
- -Key to be used when returning cart information in a response. - - - -### `loadCartRedirectUrl` - -
- -Allowed types -: [string](https://php.net/language.types.string), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [Settings::$loadCartRedirectUrl](commerce4:craft\commerce\models\Settings::$loadCartRedirectUrl) - -Since -: 3.1 - -
- -Default URL to be loaded after using the [load cart controller action](orders-carts.md#loading-a-cart). - -If `null` (default), Craft’s default [`siteUrl`](config4:siteUrl) will be used. - - - -### `purgeInactiveCarts` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [Settings::$purgeInactiveCarts](commerce4:craft\commerce\models\Settings::$purgeInactiveCarts) - -
- -Whether inactive carts should automatically be deleted from the database during garbage collection. - -::: tip -You can control how long a cart should go without being updated before it gets deleted [`purgeInactiveCartsDuration`](#purgeinactivecartsduration) setting. -::: - - - -### `purgeInactiveCartsDuration` - -
- -Allowed types -: `mixed` - -Default value -: `7776000` (90 days) - -Defined by -: [Settings::$purgeInactiveCartsDuration](commerce4:craft\commerce\models\Settings::$purgeInactiveCartsDuration) - -
- -Default length of time before inactive carts are purged. (Defaults to 90 days.) - -See [craft\helpers\ConfigHelper::durationInSeconds()](craft4:craft\helpers\ConfigHelper::durationInSeconds()) for a list of supported value types. - - - -### `updateCartSearchIndexes` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `true` - -Defined by -: [Settings::$updateCartSearchIndexes](commerce4:craft\commerce\models\Settings::$updateCartSearchIndexes) - -Since -: 3.1.5 - -
- -Whether the search index for a cart should be updated when saving the cart via `commerce/cart/*` controller actions. - -May be set to `false` to reduce performance impact on high-traffic sites. - -::: warning -Setting this to `false` will result in fewer index update queue jobs, but you’ll need to manually re-index orders to ensure up-to-date cart search results in the control panel. -::: - - - -### `validateCartCustomFieldsOnSubmission` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$validateCartCustomFieldsOnSubmission](commerce4:craft\commerce\models\Settings::$validateCartCustomFieldsOnSubmission) - -Since -: 3.0.12 - -
- -Whether to validate custom fields when a cart is updated. - -Set to `true` to allow custom content fields to return validation errors when a cart is updated. - - - -## Orders - -### `freeOrderPaymentStrategy` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'complete'` - -Defined by -: [Settings::$freeOrderPaymentStrategy](commerce4:craft\commerce\models\Settings::$freeOrderPaymentStrategy) - -
- -How Commerce should handle free orders. - -The default `'complete'` setting automatically completes zero-balance orders without forwarding them to the payment gateway. - -The `'process'` setting forwards zero-balance orders to the payment gateway for processing. This can be useful if the customer’s balance -needs to be updated or otherwise adjusted by the payment gateway. - - - -### `minimumTotalPriceStrategy` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'default'` - -Defined by -: [Settings::$minimumTotalPriceStrategy](commerce4:craft\commerce\models\Settings::$minimumTotalPriceStrategy) - -
- -How Commerce should handle minimum total price for an order. - -Options: - -- `'default'` [rounds](commerce4:\craft\commerce\helpers\Currency::round()) the sum of the item subtotal and adjustments. -- `'zero'` returns `0` if the result from `'default'` would’ve been negative; minimum order total is `0`. -- `'shipping'` returns the total shipping cost if the `'default'` result would’ve been negative; minimum order total equals shipping amount. - - - -### `orderReferenceFormat` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'{{number[:7]}}'` - -Defined by -: [Settings::$orderReferenceFormat](commerce4:craft\commerce\models\Settings::$orderReferenceFormat) - -
- -Human-friendly reference number format for orders. Result must be unique. - -See [Order Numbers](orders-carts.md#order-numbers). - - - -### `pdfAllowRemoteImages` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$pdfAllowRemoteImages](commerce4:craft\commerce\models\Settings::$pdfAllowRemoteImages) - -
- -Whether to allow non-local images in generated order PDFs. - - - -### `pdfPaperOrientation` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'portrait'` - -Defined by -: [Settings::$pdfPaperOrientation](commerce4:craft\commerce\models\Settings::$pdfPaperOrientation) - -
- -The orientation of the paper to use for generated order PDF files. - -Options are `'portrait'` and `'landscape'`. - - - -### `pdfPaperSize` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'letter'` - -Defined by -: [Settings::$pdfPaperSize](commerce4:craft\commerce\models\Settings::$pdfPaperSize) - -
- -The size of the paper to use for generated order PDFs. - -The full list of supported paper sizes can be found [in the dompdf library](https://github.com/dompdf/dompdf/blob/master/src/Adapter/CPDF.php#L45). - - - -### `requireBillingAddressAtCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$requireBillingAddressAtCheckout](commerce4:craft\commerce\models\Settings::$requireBillingAddressAtCheckout) - -
- -Whether a billing address is required before making payment on an order. - - - -### `requireShippingAddressAtCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$requireShippingAddressAtCheckout](commerce4:craft\commerce\models\Settings::$requireShippingAddressAtCheckout) - -
- -Whether a shipping address is required before making payment on an order. - - - -### `requireShippingMethodSelectionAtCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$requireShippingMethodSelectionAtCheckout](commerce4:craft\commerce\models\Settings::$requireShippingMethodSelectionAtCheckout) - -
- -Whether shipping method selection is required before making payment on an order. - - - -### `updateBillingDetailsUrl` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [Settings::$updateBillingDetailsUrl](commerce4:craft\commerce\models\Settings::$updateBillingDetailsUrl) - -
- -URL for a user to resolve billing issues with their subscription. - -::: tip -The example templates include [a template for this page](https://github.com/craftcms/commerce/tree/main/example-templates/dist/shop/plans/update-billing-details.twig). -::: - - - -### `useBillingAddressForTax` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$useBillingAddressForTax](commerce4:craft\commerce\models\Settings::$useBillingAddressForTax) - -
- -Whether taxes should be calculated based on the billing address instead of the shipping address. - - - -### `validateBusinessTaxIdAsVatId` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$validateBusinessTaxIdAsVatId](commerce4:craft\commerce\models\Settings::$validateBusinessTaxIdAsVatId) - -
- -Whether to enable validation requiring the `businessTaxId` to be a valid VAT ID. - -When set to `false`, no validation is applied to `businessTaxId`. - -When set to `true`, `businessTaxId` must contain a valid VAT ID. - -::: tip -This setting strictly toggles input validation and has no impact on tax configuration or behavior elsewhere in the system. -::: - - - -## Payments - -### `allowPartialPaymentOnCheckout` - -
- -Allowed types -: [boolean](https://php.net/language.types.boolean) - -Default value -: `false` - -Defined by -: [Settings::$allowPartialPaymentOnCheckout](commerce4:craft\commerce\models\Settings::$allowPartialPaymentOnCheckout) - -
- -Whether [partial payment](making-payments.md#checkout-with-partial-payment) can be made from the front end when the gateway allows them. - -The `false` default does not allow partial payments on the front end. - - - -### `gatewayPostRedirectTemplate` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `''` - -Defined by -: [Settings::$gatewayPostRedirectTemplate](commerce4:craft\commerce\models\Settings::$gatewayPostRedirectTemplate) - -
- -The path to the template that should be used to perform POST requests to offsite payment gateways. - -The template must contain a form that posts to the URL supplied by the `actionUrl` variable and outputs all hidden inputs with -the `inputs` variable. - -```twig - - - - - Redirecting... - - -
-

Redirecting to payment page...

-

- {{ inputs|raw }} - -

-
- - -``` - -::: tip -Since this template is simply used for redirecting, it only appears for a few seconds, so we suggest making it load fast with minimal -images and inline styles to reduce HTTP requests. -::: - -If empty (default), each gateway will decide how to handle after-payment redirects. - - - -### `paymentCurrency` - -
- -Allowed types -: [array](https://php.net/language.types.array), [null](https://php.net/language.types.null) - -Default value -: `null` - -Defined by -: [Settings::$paymentCurrency](commerce4:craft\commerce\models\Settings::$paymentCurrency) - -
- -ISO codes for supported payment currencies. - -See [Payment Currencies](payment-currencies.md). - - - -## Units - -### `dimensionUnits` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'mm'` - -Defined by -: [Settings::$dimensionUnits](commerce4:craft\commerce\models\Settings::$dimensionUnits) - -
- -Unit type for dimension measurements. - -Options: - -- `'mm'` -- `'cm'` -- `'m'` -- `'ft'` -- `'in'` - - - -### `weightUnits` - -
- -Allowed types -: [string](https://php.net/language.types.string) - -Default value -: `'g'` - -Defined by -: [Settings::$weightUnits](commerce4:craft\commerce\models\Settings::$weightUnits) - -
- -Units to be used for weight measurements. - -Options: - -- `'g'` -- `'kg'` -- `'lb'` - - - - - + +!!!include(docs/.artifacts/commerce/4.x/config.md)!!! diff --git a/docs/commerce/4.x/console-commands.md b/docs/commerce/4.x/console-commands.md index ffd05c53a..4582ca756 100644 --- a/docs/commerce/4.x/console-commands.md +++ b/docs/commerce/4.x/console-commands.md @@ -3,41 +3,50 @@ keywords: cli --- # Console Commands -Commerce adds console commands that can be run in your terminal. +Commerce supplements Craft’s own [console commands](/4.x/console-commands.md) with a few utilities that can help you manage your storefront’s data. -See Craft’s [Console Commands](/4.x/console-commands.md) page for more about using console commands. +## `commerce/example-templates` -## example-templates - -Customizes and copies example templates into your project’s template folder. +Copies the example templates that Commerce ships with into your project’s template folder. ``` $ php craft commerce/example-templates A folder will be copied to your templates directory. Choose folder name: [shop] myshop -Use CDN link to resources (tailwind)? (yes|no) [yes]: yes -Base Tailwind CSS color: [gray,red,yellow,green,blue,indigo,purple,pink,?]: green -Attempting to copy example templates ... Copying ... Done! ``` -## reset-data +Pass the `--overwrite` flag if you’d like to squash an existing folder of the same name. + +## `commerce/reset-data` Cleanses Commerce data without uninstalling the plugin or removing store configuration. This can be useful for removing test data after finishing initial project development. Deletes all orders, subscriptions, payment sources, customers, addresses and resets discount usages. ``` -php craft commerce/reset-data +$ php craft commerce/reset-data +``` + +## `commerce/transfer-user-data` + +Transfers customer data from one user to another. You will be prompted for the username or email of the source and destination users. + +``` +$ php craft commerce/transfer-user-data ``` -## upgrade +::: warning +Updates are performed via low-level database queries, so element events are not emitted and plugins are not given an opportunity to alter this behavior. This also serves to speed up the process of saving large amounts of data. +::: + +## `commerce/upgrade` -Support command for the Commerce 3 → Commerce 4 upgrade process, meant to be run _after_ upgrading to Commerce 4. +Support command for the Commerce 3 → Commerce 4 upgrade process; meant to be run _after_ upgrading to Commerce 4. ``` -php craft commerce/upgrade +$ php craft commerce/upgrade ``` It goes through several steps to ensure the best-possible migration: diff --git a/docs/commerce/4.x/customers.md b/docs/commerce/4.x/customers.md index ed14a7f4f..a9b13ae82 100644 --- a/docs/commerce/4.x/customers.md +++ b/docs/commerce/4.x/customers.md @@ -27,10 +27,6 @@ If you’d like to be able to see and manage customer addresses from the control A customer with saved login information is considered a [credentialed](/4.x/users.md#active-and-inactive-users) user. Conversely, customers who check out as guests are set up as inactive users. -### Guest Checkout - -If someone visits the store and checks out as a guest, a new inactive user is created and related to the order—and any future orders using the same email address will be consolidated under that user. - ### User Checkout Pro Logged in customers are bound to their cart the moment it is created. @@ -42,12 +38,29 @@ Setting | Result | Only requires an email address to register; can be pre-filled if the customer already set an email on their cart (as this creates an inactive user, behind the scenes). | A password is set only after activating their account (typically only used in combination with [email verification](/4.x/user-management.md#public-registration)). +### Guest Checkout + +If someone visits the store and checks out as a guest, a new inactive user is created and related to the order—and any future orders using the same email address will be consolidated under that user. + #### Registration at Checkout You can also offer the option to initiate registration _at_ checkout by sending the `registerUserOnOrderComplete` param when [updating a cart](./dev/controller-actions.md#post-cart-update-cart) or [submitting payment](./dev/controller-actions.md#post-payments-pay). If a customer chooses to register an account upon order completion, an activation link is sent to the email on file. -::: tip -The Commerce [example templates](https://github.com/craftcms/commerce/blob/main/example-templates/dist/shop/checkout/payment.twig) display a “Create an account” checkbox at the payment stage. -::: +```twig +{% set cart = craft.commerce.carts.cart %} + +
+ {{ csrfInput() }} + {{ actionInput('commerce/cart/update-cart') }} + + {{ input('checbox', 'registerUserOnOrderComplete', 1, {checked: cart.registerUserOnOrderComplete}) }} + + {# ... #} + + +
+``` + +When registering at checkout, the order’s billing and shipping [addresses](addresses.md) are automatically saved to the new accounts for future use. diff --git a/docs/commerce/4.x/dev/controller-actions.md b/docs/commerce/4.x/dev/controller-actions.md index e55ff5d2c..856b7f667 100644 --- a/docs/commerce/4.x/dev/controller-actions.md +++ b/docs/commerce/4.x/dev/controller-actions.md @@ -12,17 +12,22 @@ We recommend reviewing the main Craft documentation on [working with controller ## Available Actions -Action | Description ------- | ----------- -POST [cart/complete](#post-cart-complete) | Completes an order without payment. -GET [cart/get-cart](#get-cart-get-cart) | Returns the current cart as JSON. -GET/POST [cart/load-cart](#get-post-cart-load-cart) | Loads a cookie for the given cart. -POST [cart/update-cart](#post-cart-update-cart) | Manage a customer’s current [cart](../orders-carts.md). -GET [downloads/pdf](#get-downloads-pdf) | Returns an order PDF as a file. -POST [payment-sources/add](#post-payment-sources-add) | Creates a new payment source. -POST [payment-sources/delete](#post-payment-sources-delete) | Deletes a payment source. -GET [payments/complete-payment](#get-payments-complete-payment) | Processes customer’s return from an off-site payment. -POST [payments/pay](#post-payments-pay) | Makes a payment on an order. +Methods | Action | Description +--- | --- | --- +POST | [cart/complete](#post-cart-complete) | Completes an order without payment. +GET | [cart/get-cart](#get-cart-get-cart) | Returns the current cart as JSON. +GET/POST | [cart/load-cart](#get-post-cart-load-cart) | Loads a cookie for the given cart. +POST | [cart/forget-cart](#get-post-cart-forget-cart) | Removes a cookie for the current cart. +POST | [cart/update-cart](#post-cart-update-cart) | Manage a customer’s current [cart](../orders-carts.md). +POST | [payment-sources/add](#post-payment-sources-add) | Creates a new payment source. +POST | [payment-sources/delete](#post-payment-sources-delete) | Deletes a payment source. +GET | [payments/complete-payment](#get-payments-complete-payment) | Processes customer’s return from an off-site payment. +POST | [payments/pay](#post-payments-pay) | Makes a payment on an order. +GET | [downloads/pdf](#get-downloads-pdf) | Returns an order PDF as a file. +POST | [subscriptions/subscribe](#post-subscriptions-subscribe) | Starts a new subscription. +POST | [subscriptions/cancel](#post-subscriptions-cancel) | Cancels an active subscription. +POST | [subscriptions/switch](#post-subscriptions-switch) | Switch an active subscription’s plan. +POST | [subscriptions/reactivate](#post-subscriptions-reactivate) | Reactivates a canceled subscription. [Address management](/4.x/addresses.md/#managing-addresses) actions are part of the main Craft documentation. Commerce also allows address information to be set directly on a cart via POST [cart/update-cart](#post-cart-update-cart). @@ -117,6 +122,9 @@ Param | Description `purchasableId` | Single purchasable ID to be added to the cart. If provided, will also use optional `note`, `options[]`, and `qty` parameters. `purchasables[]` | Array of one or more purchasables to be [added to the cart](../orders-carts.md#adding-a-multiple-items). Each must include an `id` key-value pair, and may include `options`, `note`, and `qty` key-value pairs. `registerUserOnOrderComplete` | Whether to create a user account for the customer when the cart is completed and turned into an order. +`saveBillingAddressOnOrderComplete` | Whether to save the billing address to the customer’s address book when the cart is completed and turned into an order. +`saveShippingAddressOnOrderComplete` | Whether to save the shipping address to the customer’s address book when the cart is completed and turned into an order. +`saveAddressesOnOrderComplete` | Whether to save both the shipping _and_ billing address to the customer’s address book when the cart is completed and turned into an order. Unlike `saveBillingAddressOnOrderComplete` and `saveShippingAddressOnOrderComplete`, this is _not_ stored on the order itself—it just allows customers to set both at the same time. `shippingAddress[]` | Shipping address attributes. (See [Addresses](../addresses.md)). `shippingAddressId` | ID of an existing address to use as the shipping address. `shippingAddressSameAsBilling` | Set to `true` to use billing address for shipping address and ignore `shippingAddress` and `shippingAddressId`. @@ -159,37 +167,57 @@ State | `text/html` | `application/json` -### GET `downloads/pdf` +### POST `cart/forget-cart` -Generates and sends an order [PDF](../pdfs.md) as a file. +Detaches a cart from the current customer’s session. Read more about [managing carts](../orders-carts.md#loading-and-forgetting-carts). + +This action has no arguments and responses are only sent as `text/html`. + +#### Response + + + +State | `text/html` +--- | --- + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). + + + +### GET `cart/get-cart` + +Returns the [current cart](../orders-carts.md#fetching-a-cart) as JSON. A new cart cookie will be generated if one doesn’t already exist. + +The request must include `Accept: application/json` in its headers. #### Supported Params Param | Description ----- | ----------- -`number` | Required order number. -`option` | Optional string value that’s passed to the PDF template. -`pdfHandle` | Handle of a configured PDF to be rendered. +`number` | Optional order number for a specific, existing cart. +`forceSave` | Optionally set to `true` to force saving the cart. #### Response -State | Output ------ | ------ - | File response with the rendered PDF and an `application/pdf` MIME type. - | Exceptions will be rendered with the normal [error template](/4.x/routing.md#error-templates). + + +State | `application/json` +----- | ------------------ + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request); cart data is available under a key determined by the [cartVariable](../config-settings.md#cartvariable) config setting. + ### POST `payment-sources/add` -Creates a new payment source. +Creates a new payment source for the current customer. #### Supported Params Param | Description ----- | ----------- -`*` | All body parameters will be provided directly to the gateway’s [payment form](../payment-form-models.md) model. +`*` | All body parameters will be provided directly to the gateway’s payment form model. `description` | Description for the payment source. `gatewayId` | ID of the new payment source’s gateway, which must support payment sources. +`isPrimaryPaymentSource` | Send a non-empty value to make this the customer’s primary payment source. #### Response @@ -205,7 +233,7 @@ State | `text/html` | `application/json` ::: warning -Note that successful requests will return the [payment _source_](../saving-payment-sources.md) that was created; failures will bounce back the [payment _form_](../payment-form-models.md) with errors. +Note that the models available in success and failure states are different! ::: ### POST `payment-sources/delete` @@ -244,11 +272,14 @@ Param | Description `email` | Email address of the person responsible for payment, which must match the email address on the order. Required if the order being paid is not the active cart. `gatewayId` | The payment gateway ID to be used for payment. `number` | The order number payment should be applied to. When ommitted, payment is applied to the current cart. -`paymentAmount` | Hashed payment amount, expressed in the cart’s `paymentCurrency`, available only if [partial payments](../making-payments.md#checkout-with-partial-payment) are allowed. +`paymentAmount` | Hashed payment amount, expressed in the cart’s `paymentCurrency`. Available only if [partial payments](../making-payments.md#checkout-with-partial-payment) are allowed. `paymentCurrency` | ISO code of a configured [payment currency](../payment-currencies.md) to be used for the payment. `paymentSourceId` | The ID for a payment source that should be used for payment. `registerUserOnOrderComplete` | Whether the customer should have an account created on order completion. `savePaymentSource` | Whether to save card information as a payment source. (Gateway must support payment sources.) +`saveBillingAddressOnOrderComplete` | Whether to save the billing address to the customer’s address book when the cart is completed and turned into an order. +`saveShippingAddressOnOrderComplete` | Whether to save the shipping address to the customer’s address book when the cart is completed and turned into an order. +`saveAddressesOnOrderComplete` | Whether to save both the shipping _and_ billing address to the customer’s address book when the cart is completed and turned into an order. #### Response @@ -283,8 +314,6 @@ Param | Description The action’s output depends on whether the payment completed successfully and the `Accept` header. -#### Standard Request - State | `text/html` | `application/json` @@ -293,3 +322,137 @@ State | `text/html` | `application/json` | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request); redirection defaults to the order’s `cancelUrl`. | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request); special `url` property set to the order’s `cancelUrl`. + +### GET `downloads/pdf` + +Generates and sends an order [PDF](../pdfs.md) as a file. + +#### Supported Params + +Param | Description +----- | ----------- +`number` | Required order number. +`option` | Optional string value that’s passed to the PDF template. +`pdfHandle` | Handle of a configured PDF to be rendered. + +#### Response + +State | Output +----- | ------ + | File response with the rendered PDF and an `application/pdf` MIME type. + | Exceptions will be rendered with the normal [error template](/4.x/routing.md#error-templates). + +### POST `subscriptions/subscribe` + +Starts a new subscription with the current customer’s default payment source. Learn more about supporting [Subscriptions](../subscriptions.md). + +::: warning +We recommend using normal HTML forms and a `text/html` content type for this action, as the gateway _may_ require redirection to resolve billing issues when a subscription cannot be started. This workflow can be problematic when using `application/json` over Ajax. +::: + +#### Supported Params + +Param | Description +----- | ----------- +`planUid` | **Required.** UID of the Commerce plan the customer wants to subscribe to. +`fields[...]` | Subscription custom field values, indexed by their handles. +`fieldsLocation` | Allows relocation of the default `fields` key for custom field data (see above). +`*` | **Conditionally required.** Each [gateway](../payment-gateways.md) that supports subscriptions may require additional properties on its subclass. + +::: warning +`planUid` and all gateway-specific properties must be [hashed](/4.x/dev/filters.md#hash) to prevent tampering. +::: + +#### Response + + + +State | `text/html` | `application/json` +----- | ----------- | ------------------ + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request); the Subscription model is available under the `subscription` key. + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). Most subscription failures will be presented as a succinct error message. Specific issues are logged, but may not be disclosed to the customer. The user may be redirected to the [`updateBillingDetailsUrl` setting](../config-settings.md#updatebillingdetailsurl) to resolve billing issues. | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). + + + +### POST `subscriptions/cancel` + +Cancels an active subscription. + +#### Supported Params + +Param | Description +----- | ----------- +`subscriptionUid` | **Required.** UID of the subscription to cancel. Must be [hashed](/4.x/dev/filters.md#hash). +`*` | **Conditionally required.** Each [gateway](../payment-gateways.md) that supports subscriptions may require additional properties on its subclass. + +#### Response + + + +State | `text/html` | `application/json` +----- | ----------- | ------------------ + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request); the Subscription model is available under the `subscription` key. + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). + + + +### POST `subscriptions/switch` + +Switch the plan on an active subscription. + +#### Supported Params + +Param | Description +----- | ----------- +`subscriptionUid` | **Required.** UID of the subscription getting updated. Must be [hashed](/4.x/dev/filters.md#hash). +`planUid` | **Required.** UID of the plan to switch to. Must be [hashed](/4.x/dev/filters.md#hash). +`*` | **Conditionally required.** Each [gateway](../payment-gateways.md) that supports subscriptions may require additional properties on its subclass. + +#### Response + +The request may fail if the new and old plans are not compatible. This is determined by the gateway, so be sure and consult its documentation and platform limitations. + +You can check whether two plans are compatible in Twig, to narrow the options displayed to your customers: + +```twig +{% set currentPlan = subscription.getPlan() %} +{% set gateway = currentPlan.getGateway() %} +{% set allPlans = craft.commerce.plans.getPlansByGatewayId(gateway.id) %} +{% set switchablePlans = allPlans|filter((p) => p.canSwitchFrom(currentPlan)) %} + + +``` + + + +State | `text/html` | `application/json` +----- | ----------- | ------------------ + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request); the Subscription model is available under the `subscription` key. + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). + + + +### POST `subscriptions/reactivate` + +Reactivates a canceled subscription. Only subscriptions that haven’t expired yet can be reactivated—a subscription may be canceled + +#### Supported Params + +Param | Description +----- | ----------- +`subscriptionUid` | **Required.** UID of the subscription to reactivate. Must be [hashed](/4.x/dev/filters.md#hash). + +#### Response + + + +State | `text/html` | `application/json` +----- | ----------- | ------------------ + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request); the Subscription model is available under the `subscription` key. + | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). | [Standard behavior](/4.x/dev/controller-actions.md#after-a-get-request). + + diff --git a/docs/commerce/4.x/discounts.md b/docs/commerce/4.x/discounts.md index 19df89691..3e6471001 100644 --- a/docs/commerce/4.x/discounts.md +++ b/docs/commerce/4.x/discounts.md @@ -24,32 +24,48 @@ For more on coupon code setup and templating, see the [coupon codes](coupon-code ## Discount Matching Items -Each discount’s **Matching Items** tab provides options for limiting what store items qualify for the discount. By default, all purchasables and categories may qualify for the discount. +Each discount’s **Matching Items** tab provides options for limiting what store items qualify for the discount. By default, _all purchasables_ qualify for the discount. ### Purchasables -The **All purchsables** lightswitch is on by default, but you can switch it off to select zero or more **Product Variant** relationships. Be careful with this, because switching off **All purchasables** and not selecting any variants will result in no variants qualifying for the discount! +You can restrict a discount to specific purchasables by enabling the **Only match certain purchasables…** option, and selecting one or more via the revealed element picker(s). Each registered purchasable type will display its own selection field—but by default, this is only variants. + +If this is enabled and no purchasables are selected, the discount will never match. ::: tip -Only _promotable_ purchasables may have discounts and sales applied. This means the **Promotable** switch must be enabled on the variant’s product in the control panel, which is the default for any new product. +Only variants belonging to _promotable_ products may have discounts and sales applied. This means the **Promotable** switch must be enabled on the variant’s product in the control panel, which is the default for any new product. ::: -### Categories +### Relationships + +Oftentimes, it makes more sense to make discounts available based on categories or other taxonomies than on specific products. + +Let’s assume your store is organized into departments that are defined by a [category group](/4.x/categories.md) or [entry section](/4.x/entries.md). On each product (or variant), administrators select one or more of those departments via a category or entry custom fields. -The **Categories** lightswitch is also on by default, but you can switch it off to select zero or more product categories that should qualify for the discount. Just like the purchasables switch above, you should be sure to designate categories if the **All categories** lightswitch is disabled—otherwise it won’t be possible for any items to match the discount. +In the **Matching Items** tab, enabling **Only match purchasables related to…** will reveal two element selection fields (one for categories and one for entries), as well as an [Advanced](#advanced) drawer, which allows you to specify the [direction](/4.x/relations.md#sources-and-targets) of the relationship. If you enable the relational criteria and don’t select any categories or entries -### Advanced +::: tip +The **Categories** field will only be displayed if you have a category group configured; similarly, the **Entries** field will only be displayed if you’ve configured a section. +::: -You can click the “Advanced” toggle to display a **Categories Relationship Type** field that determines how related purchasables and categories should behave matching items. Options: +#### Advanced -- **Either (Default)** – the relationship field is on the purchasable or the category -- **Source** – the category relationship field is on the purchasable -- **Target** – the purchasable relationship field is on the category +The “Advanced” drawer contains the **Relationship Type** field that determines how related purchasables should behave when matching items. + +- **Either way (Default)**: the relational field can be on the purchasable _or_ the category/entry (the purchasable may be the source _or_ target of the relationship); +- **The purchasable defines the relationship**: the relational field is defined on the _purchasable_, and you select categories or entries from it (the purchasable is the _source_ of the relationship); +- **The purchasable is related by another element**: the relational field is defined on the category/entry, and you select purchasables from it (the purchasable is the _target_ of the relationship); ::: tip -This behavior is consistent with all Craft’s relationships; see the [Terminology](/4.x/relations.html#terminology) section on the Relations page. +This behavior is consistent with all Craft’s relationships; see the [Terminology](/4.x/relations.html#terminology) section on the Relations page for more information on sources and targets. ::: +To illustrate, suppose the “departments” we mentioned earlier each represent a landing page. Those pages (managed as entries in Craft) are also be used to organize products, through an [entries field](/4.x/entries-field.md) in the product type’s field layout. As products are added and edited, administrators place them in departments by selecting those entries as relations. In this scenario, both the **Either way** and **The purchasable defines the relationship** settings would allow the discount to match a department entry selected in its purchasable-matching rules. + +Now, if you were to add a “Featured Products” field to the department landing pages and select a few products, the third **The purchasable is related by another element** relationship type setting would match. + +This combination of settings can provide powerful matching criteria all on their own. You can even define back-end-only taxonomies (without content or URLs) for the express purpose of managing pricing rules. + ## Discount Conditions Rules The **Conditions Rules** tab has flexible, rule-based condition fields for controlling which orders, customers, and/or addresses should qualify for the discount. diff --git a/docs/commerce/4.x/example-objects/order.php b/docs/commerce/4.x/example-objects/order.php index 9d3e5303a..49651fb4c 100644 --- a/docs/commerce/4.x/example-objects/order.php +++ b/docs/commerce/4.x/example-objects/order.php @@ -35,6 +35,8 @@ 'shippingMethodName' => 'Free Shipping', 'customerId' => '3', 'registerUserOnOrderComplete' => NULL, + 'saveBillingAddressOnOrderComplete' => NULL, + 'saveShippingAddressOnOrderComplete' => NULL, 'paymentSourceId' => NULL, 'storedTotalPrice' => '30.0000', 'storedTotalPaid' => '30.0000', diff --git a/docs/commerce/4.x/example-templates.md b/docs/commerce/4.x/example-templates.md index a6129a4c8..8ada6e81e 100644 --- a/docs/commerce/4.x/example-templates.md +++ b/docs/commerce/4.x/example-templates.md @@ -1,23 +1,29 @@ # Example Templates -Commerce includes example templates you can use for a reference or starting point building your store. +Commerce includes example templates you can use for a reference, or as a starting point when building your store. They are continually updated to support the full range of Commerce features, out-of-the-box, including: -The examples include a robust set of templates that do pretty much everything with Commerce. This includes a full checkout flow, address handling, order management, subscription management, and cart management. +- Cart management; +- Complete checkout flow; +- [Address management](/4.x/addresses.md#managing-addresses) +- Order history; +- Subscription management; -The [`commerce/example-templates` console command](console-commands.md#example-templates) offers a quick way to customize the templates and copy them into your project, but you can also browse the templates built with default options in `vendor/craftcms/commerce/example-templates/dist/`. +…and more! -You can copy these built templates directly to your project’s top level `templates/` folder: +Use the [`commerce/example-templates` console command](console-commands.md#example-templates) to install the example templates into your project. Those templates are always available for reference, in `vendor/craftcms/commerce/example-templates/dist/`. + +You can manually copy some or all of the templates into your project’s top level `templates/` folder: ```bash cp -r vendor/craftcms/commerce/example-templates/dist/* ./templates ``` -If your system supports it, you could also symlink these folders into your project’s `templates/` folder so you always have up-to-date examples _while in development_: +## Plugin Development and Reference + +If your system supports it, you can symlink these folders into your project’s `templates/` folder so you always have up-to-date examples: ```bash ln -s vendor/craftcms/commerce/example-templates/dist/shop ./templates/shop ``` -::: tip -You can also visit [craftcms.com/demo](https://craftcms.com/demo) to spin up the Spoke & Chain Craft Commerce demo. The source code is available at [github.com/craftcms/spoke-and-chain](https://github.com/craftcms/spoke-and-chain). -::: \ No newline at end of file +This is only recommended for active development—say, when frequently pulling in unreleased versions of Commerce to test a gateway plugin. diff --git a/docs/commerce/4.x/extend/events.md b/docs/commerce/4.x/extend/events.md index c739d76d6..ee338abf9 100644 --- a/docs/commerce/4.x/extend/events.md +++ b/docs/commerce/4.x/extend/events.md @@ -1,16 +1,26 @@ +--- +sidebarDepth: 2 +--- + # Events -Craft Commerce provides a multitude of events for extending its functionality. Modules and plugins can [register event listeners](https://craftcms.com/knowledge-base/custom-module-events), typically in their `init()` methods, to modify Commerce’s behavior. +Craft Commerce provides a multitude of events for extending its functionality. Modules and plugins can [register event listeners](/4.x/extend/events.md), typically in their `init()` methods, to modify Commerce’s behavior. ## Event Code Generator -Select an event for details and a code snippet. See Craft’s [Events](/4.x/extend/events.md) page for Craft and Yii events. +Select an event for details and a code snippet, or check out the sections below for some use cases. See Craft’s [Events](/4.x/extend/events.md) page for more information about working with events. -## Variant Events +## Common Events + Workflows + +The following sections highlight a few of the events emitted by Commerce classes. It is not exhaustive—meaning you may need to enlist the help of one or more [development tools](/4.x/extend/README.md#tools) to aid in [discovering the “right” event](/4.x/extend/events.md#discovering-events)! + +### Product + Variant Events + +[Products and variants](../products-variants.md) are [elements](/4.x/extend/element-types.md), so all the standard lifecycle events (for elements and their associated query classes) apply here. -### `beforeCaptureVariantSnapshot` +#### `beforeCaptureVariantSnapshot` The event that is triggered before a variant’s field data is captured, which makes it possible to customize which fields are included in the snapshot. Custom fields are not included by default. @@ -27,7 +37,7 @@ Event::on( function(CustomizeVariantSnapshotFieldsEvent $event) { // @var Variant $variant $variant = $event->variant; - // @var array|null $fields + // @var string[]|null $fields $fields = $event->fields; // Add every custom field to the snapshot @@ -46,7 +56,7 @@ Event::on( Add with care! A huge amount of custom fields/data will increase your database size. ::: -### `afterCaptureVariantSnapshot` +#### `afterCaptureVariantSnapshot` The event that is triggered after a variant’s field data is captured. This makes it possible to customize, extend, or redact the data to be persisted on the variant instance. @@ -70,7 +80,7 @@ Event::on( ); ``` -### `beforeCaptureProductSnapshot` +#### `beforeCaptureProductSnapshot` The event that is triggered before a product’s field data is captured. This makes it possible to customize which fields are included in the snapshot. Custom fields are not included by default. @@ -107,7 +117,7 @@ Event::on( Add with care! A huge amount of custom fields/data will increase your database size. ::: -### `afterCaptureProductSnapshot` +#### `afterCaptureProductSnapshot` The event that is triggered after a product’s field data is captured, which can be used to customize, extend, or redact the data to be persisted on the product instance. @@ -132,9 +142,9 @@ Event::on( ); ``` -## Sale Events +### Sale Events -### `beforeMatchPurchasableSale` +#### `beforeMatchPurchasableSale` The event that is triggered before Commerce attempts to match a sale to a purchasable. @@ -165,7 +175,7 @@ Event::on( ); ``` -### `beforeSaveSale` +#### `beforeSaveSale` The event that is triggered before a sale is saved. @@ -188,7 +198,7 @@ Event::on( ); ``` -### `afterSaveSale` +#### `afterSaveSale` The event that is triggered after a sale is saved. @@ -211,7 +221,7 @@ Event::on( ); ``` -### `afterDeleteSale` +#### `afterDeleteSale` The event that is triggered after a sale is deleted. @@ -235,9 +245,9 @@ Event::on( ``` -## Order Events +### Order Events -### `beforeAddLineItemToOrder` +#### `beforeAddLineItemToOrder` The event that is triggered before a new line item has been added to the order. @@ -262,7 +272,7 @@ Event::on( ); ``` -### `afterAddLineItemToOrder` +#### `afterAddLineItemToOrder` The event that is triggered after a line item has been added to an order. @@ -284,7 +294,7 @@ Event::on( } ); ``` -### `afterApplyAddLineItemToOrder` +#### `afterApplyAddLineItemToOrder` The event that is triggered after a line item has been added to an order. @@ -306,7 +316,7 @@ Event::on( ); ``` -### `afterRemoveLineItemToOrder` +#### `afterRemoveLineItemToOrder` The event that is triggered after a line item has been removed from an order. @@ -329,7 +339,7 @@ Event::on( ); ``` -### `afterApplyRemoveLineItemFromOrder` +#### `afterApplyRemoveLineItemFromOrder` The event that is triggered after a line item has been removed from an order. @@ -351,7 +361,7 @@ Event::on( ); ``` -### `beforeCompleteOrder` +#### `beforeCompleteOrder` The event that is triggered before an order is completed. @@ -370,7 +380,7 @@ Event::on( ); ``` -### `afterCompleteOrder` +#### `afterCompleteOrder` The event that is triggered after an order is completed. @@ -389,7 +399,7 @@ Event::on( ); ``` -### `afterOrderAuthorized` +#### `afterOrderAuthorized` This event is raised after an order is authorized in full and completed. @@ -410,7 +420,7 @@ Event::on( ); ``` -### `afterOrderPaid` +#### `afterOrderPaid` The event that is triggered after an order is paid and completed. @@ -429,43 +439,7 @@ Event::on( ); ``` -### `registerOrderAdjusters` - -The event that is triggered for registration of additional adjusters. - -```php -use craft\events\RegisterComponentTypesEvent; -use craft\commerce\services\OrderAdjustments; -use yii\base\Event; - -Event::on( - OrderAdjustments::class, - OrderAdjustments::EVENT_REGISTER_ORDER_ADJUSTERS, - function(RegisterComponentTypesEvent $event) { - $event->types[] = MyAdjuster::class; - } -); -``` - -### `registerDiscountAdjusters` - -The event that is triggered for registration of additional discount adjusters. - -```php -use craft\events\RegisterComponentTypesEvent; -use craft\commerce\services\OrderAdjustments; -use yii\base\Event; - -Event::on( - OrderAdjustments::class, - OrderAdjustments::EVENT_REGISTER_DISCOUNT_ADJUSTERS, - function(RegisterComponentTypesEvent $event) { - $event->types[] = MyAdjuster::class; - } -); -``` - -### `orderStatusChange` +#### `orderStatusChange` The event that is triggered when an order status is changed. @@ -491,7 +465,7 @@ Event::on( ); ``` -### `defaultOrderStatus` +#### `defaultOrderStatus` The event that is triggered when a default order status is being fetched. @@ -519,7 +493,25 @@ Event::on( ); ``` -### `modifyCartInfo` +#### `registerOrderAdjusters` + +The event that is triggered for registration of additional adjusters. + +```php +use craft\events\RegisterComponentTypesEvent; +use craft\commerce\services\OrderAdjustments; +use yii\base\Event; + +Event::on( + OrderAdjustments::class, + OrderAdjustments::EVENT_REGISTER_ORDER_ADJUSTERS, + function(RegisterComponentTypesEvent $event) { + $event->types[] = MyAdjuster::class; + } +); +``` + +#### `modifyCartInfo` The event that’s triggered when a cart is returned as an array for Ajax cart update requests. @@ -539,9 +531,9 @@ Event::on( ); ``` -## Discount Events +### Discount Events -### `afterDiscountAdjustmentsCreated` +#### `afterDiscountAdjustmentsCreated` The event that is triggered after a discount has matched the order and before it returns its adjustments. @@ -570,7 +562,7 @@ Event::on( ); ``` -### `beforeSaveDiscount` +#### `beforeSaveDiscount` The event that is triggered before a discount is saved. @@ -595,7 +587,7 @@ Event::on( ); ``` -### `afterSaveDiscount` +#### `afterSaveDiscount` The event that is triggered after a discount is saved. @@ -620,7 +612,7 @@ Event::on( ); ``` -### `afterDeleteDiscount` +#### `afterDeleteDiscount` The event that is triggered after a discount is deleted. @@ -643,7 +635,7 @@ Event::on( ); ``` -### `discountMatchesLineItem` +#### `discountMatchesLineItem` The event that is triggered when a line item is matched with a discount. @@ -673,7 +665,7 @@ Event::on( ); ``` -### `discountMatchesOrder` +#### `discountMatchesOrder` The event that is triggered when an order is matched with a discount. @@ -701,9 +693,9 @@ Event::on( ); ``` -## Line Item Events +### Line Item Events -### `beforeSaveLineItem` +#### `beforeSaveLineItem` The event that is triggered before a line item is saved. @@ -728,7 +720,7 @@ Event::on( ); ``` -### `afterSaveLineItem` +#### `afterSaveLineItem` The event that is triggeredd after a line item is saved. @@ -753,7 +745,7 @@ Event::on( ); ``` -### `populateLineItem` +#### `populateLineItem` The event that is triggered as a line item is being populated from a purchasable. @@ -784,7 +776,7 @@ Event::on( Don’t forget to set `salePrice` accordingly since it’s the amount that gets added to the cart. ::: -### `createLineItem` +#### `createLineItem` The event that is triggered after a line item has been created from a purchasable. @@ -809,7 +801,7 @@ Event::on( ); ``` -### `defaultLineItemStatus` +#### `defaultLineItemStatus` The event that is triggered when getting a default status for a line item. @@ -839,9 +831,9 @@ Event::on( ); ``` -## Payment Events +### Payment Events -### `registerGatewayTypes` +#### `registerGatewayTypes` The event that is triggered for the registration of additional gateways. @@ -861,7 +853,7 @@ Event::on( ); ``` -### `afterPaymentTransaction` +#### `afterPaymentTransaction` The event that is triggered after a payment transaction is made. @@ -885,7 +877,7 @@ Event::on( ); ``` -### `beforeCaptureTransaction` +#### `beforeCaptureTransaction` The event that is triggered before a payment transaction is captured. @@ -908,7 +900,7 @@ Event::on( ); ``` -### `afterCaptureTransaction` +#### `afterCaptureTransaction` The event that is triggered after a payment transaction is captured. @@ -931,7 +923,7 @@ Event::on( ); ``` -### `beforeRefundTransaction` +#### `beforeRefundTransaction` The event that is triggered before a transaction is refunded. @@ -953,7 +945,7 @@ Event::on( ); ``` -### `afterRefundTransaction` +#### `afterRefundTransaction` The event that is triggered after a transaction is refunded. @@ -975,7 +967,7 @@ Event::on( ); ``` -### `beforeProcessPaymentEvent` +#### `beforeProcessPaymentEvent` The event that is triggered before a payment is processed. @@ -1009,7 +1001,7 @@ Event::on( ); ``` -### `afterProcessPaymentEvent` +#### `afterProcessPaymentEvent` The event that is triggered after a payment is processed. @@ -1041,7 +1033,7 @@ Event::on( ); ``` -### `deletePaymentSource` +#### `deletePaymentSource` The event that is triggered when a payment source is deleted. @@ -1064,7 +1056,7 @@ Event::on( ); ``` -### `beforeSavePaymentSource` +#### `beforeSavePaymentSource` The event that is triggered before a payment source is added. @@ -1086,7 +1078,7 @@ Event::on( ); ``` -### `afterSavePaymentSource` +#### `afterSavePaymentSource` The event that is triggered after a payment source is added. @@ -1109,7 +1101,7 @@ Event::on( ); ``` -### `afterSaveTransaction` +#### `afterSaveTransaction` The event that is triggered after a transaction has been saved. @@ -1132,7 +1124,7 @@ Event::on( ); ``` -### `afterCreateTransaction` +#### `afterCreateTransaction` The event that is triggered after a transaction has been created. @@ -1155,9 +1147,9 @@ Event::on( ); ``` -## Subscription Events +### Subscription Events -### `afterExpireSubscription` +#### `afterExpireSubscription` The event that is triggered after a subscription has expired. @@ -1180,7 +1172,7 @@ Event::on( ); ``` -### `beforeCreateSubscription` +#### `beforeCreateSubscription` The event that is triggered before a subscription is created. @@ -1211,7 +1203,7 @@ Event::on( ); ``` -### `afterCreateSubscription` +#### `afterCreateSubscription` The event that is triggered after a subscription is created. @@ -1243,7 +1235,7 @@ Event::on( Since a subscription may be suspended at creation due to payment issues, you may want to check subscription properties like `hasStarted` or `isSuspended` before taking further action. ::: -### `beforeReactivateSubscription` +#### `beforeReactivateSubscription` The event that is triggered before a subscription gets reactivated. @@ -1268,7 +1260,7 @@ Event::on( ); ``` -### `afterReactivateSubscription` +#### `afterReactivateSubscription` The event that is triggered after a subscription gets reactivated. @@ -1291,7 +1283,7 @@ Event::on( ); ``` -### `beforeSwitchSubscriptionPlan` +#### `beforeSwitchSubscriptionPlan` The event that is triggered before a subscription is switched to a different plan. @@ -1324,7 +1316,7 @@ Event::on( ); ``` -### `afterSwitchSubscriptionPlan` +#### `afterSwitchSubscriptionPlan` The event that is triggered after a subscription gets switched to a different plan. @@ -1355,7 +1347,7 @@ Event::on( ); ``` -### `beforeCancelSubscription` +#### `beforeCancelSubscription` The event that is triggered before a subscription is canceled. @@ -1383,7 +1375,7 @@ Event::on( ); ``` -### `afterCancelSubscription` +#### `afterCancelSubscription` The event that is triggered after a subscription gets canceled. @@ -1409,7 +1401,7 @@ Event::on( ); ``` -### `beforeUpdateSubscription` +#### `beforeUpdateSubscription` The event that is triggered before a subscription gets updated. Typically this event is fired when subscription data is updated on the gateway. @@ -1431,7 +1423,7 @@ Event::on( ); ``` -### `receiveSubscriptionPayment` +#### `receiveSubscriptionPayment` The event that is triggered when a subscription payment is received. @@ -1460,9 +1452,9 @@ Event::on( ); ``` -## Other Events +### Mail Events -### `beforeSendEmail` +#### `beforeSendEmail` The event that is triggered before an email is sent out. @@ -1497,7 +1489,7 @@ Event::on( ); ``` -### `afterSendEmail` +#### `afterSendEmail` The event that is triggered after an email has been sent out. @@ -1529,7 +1521,7 @@ Event::on( ); ``` -### `beforeSaveEmail` +#### `beforeSaveEmail` The event that is triggered before an email is saved. @@ -1553,7 +1545,7 @@ Event::on( ); ``` -### `afterSaveEmail` +#### `afterSaveEmail` The event that is triggered after an email is saved. @@ -1577,7 +1569,7 @@ Event::on( ); ``` -### `beforeDeleteEmail` +#### `beforeDeleteEmail` The event that is triggered before an email is deleted. @@ -1599,7 +1591,7 @@ Event::on( ); ``` -### `afterDeleteEmail` +#### `afterDeleteEmail` The event that is triggered after an email is deleted. @@ -1621,7 +1613,9 @@ Event::on( ); ``` -### `beforeRenderPdf` +### PDF Events + +#### `beforeRenderPdf` The event that is triggered before an order’s PDF is rendered. @@ -1636,14 +1630,14 @@ Event handlers can customize PDF rendering by modifying several properties on th | `pdf` | `null` by default, can optionally be used to supply your own PDF string rather than the one Commerce would generate | ```php -use craft\commerce\events\PdfEvent; +use craft\commerce\events\PdfRenderEvent; use craft\commerce\services\Pdfs; use yii\base\Event; Event::on( Pdfs::class, Pdfs::EVENT_BEFORE_RENDER_PDF, - function(PdfEvent $event) { + function(PdfRenderEvent $event) { // Modify `$event->order`, `$event->option`, `$event->template`, // and `$event->variables` to customize what gets rendered into a PDF; // or render your own PDF and set its string on `$event->pdf` @@ -1656,32 +1650,32 @@ Event::on( If you provide your own PDF string, Commerce will skip its own rendering and [`afterRenderPdf`](#afterrenderpdf) will not be triggered. ::: -### `afterRenderPdf` +#### `afterRenderPdf` The event that is triggered after an order’s PDF has been rendered by Commerce. Event handlers can override Commerce’s PDF generation by setting the `pdf` property on the event to a custom-rendered PDF string. The event properties will be the same as those from `beforeRenderPdf`, but `pdf` will contain a rendered PDF string and is the only one for which setting a value will make any difference for the resulting PDF output. ```php -use craft\commerce\events\PdfEvent; +use craft\commerce\events\PdfRenderEvent; use craft\commerce\services\Pdfs; use yii\base\Event; Event::on( Pdfs::class, Pdfs::EVENT_AFTER_RENDER_PDF, - function(PdfEvent $event) { + function(PdfRenderEvent $event) { // Add a watermark to the PDF or forward it to the accounting department // ... } ); ``` -### `beforeSavePdf` +#### `beforeSavePdf` -The event that is triggered before a PDF is saved. +The event that is triggered before a PDF’s configuration is saved. ```php -use craft\commerce\events\PdfSaveEvent; +use craft\commerce\events\PdfEvent; use craft\commerce\services\Pdfs; use craft\commerce\models\Pdf; use yii\base\Event; @@ -1689,7 +1683,7 @@ use yii\base\Event; Event::on( Pdfs::class, Pdfs::EVENT_BEFORE_SAVE_PDF, - function(PdfSaveEvent $event) { + function(PdfEvent $event) { // @var Pdf $pdf $pdf = $event->pdf; // @var bool $isNew @@ -1699,12 +1693,12 @@ Event::on( ); ``` -### `afterSavePdf` +#### `afterSavePdf` -The event that is triggered after a PDF is saved. +The event that is triggered after a PDF’s configuration is saved. ```php -use craft\commerce\events\PdfSaveEvent; +use craft\commerce\events\PdfEvent; use craft\commerce\services\Pdfs; use craft\commerce\models\Pdf; use yii\base\Event; @@ -1712,7 +1706,7 @@ use yii\base\Event; Event::on( Pdfs::class, Pdfs::EVENT_AFTER_SAVE_PDF, - function(PdfSaveEvent $event) { + function(PdfEvent $event) { // @var Pdf $pdf $pdf = $event->pdf; // @var bool $isNew @@ -1722,7 +1716,9 @@ Event::on( ); ``` -### `beforeSaveProductType` +### Product Types + +#### `beforeSaveProductType` The event that is triggered before a product type is saved. @@ -1745,7 +1741,7 @@ Event::on( ); ``` -### `afterSaveProductType` +#### `afterSaveProductType` The event that is triggered after a product type has been saved. @@ -1768,7 +1764,9 @@ Event::on( ); ``` -### `registerPurchasableElementTypes` +### Purchasables + +#### `registerPurchasableElementTypes` The event that is triggered for registration of additional purchasables. @@ -1788,27 +1786,7 @@ Event::on( ); ``` -### `registerAvailableShippingMethods` - -The event that is triggered for registration of additional shipping methods. - -This example adds an instance of `MyShippingMethod` to the event object’s `shippingMethods` array: - -```php -use craft\commerce\events\RegisterAvailableShippingMethodsEvent; -use craft\commerce\services\ShippingMethods; -use yii\base\Event; - -Event::on( - ShippingMethods::class, - ShippingMethods::EVENT_REGISTER_AVAILABLE_SHIPPING_METHODS, - function(RegisterAvailableShippingMethodsEvent $event) { - $event->shippingMethods[] = MyShippingMethod::class; - } -); -``` - -### `purchasableAvailable` +#### `purchasableAvailable` The event that’s triggered when determining whether a purchasable should be available for a given current user and cart. @@ -1832,7 +1810,27 @@ Event::on( If the purchasable becomes unavailable after being added to the cart, an [order notice](../orders-carts.md#order-notices) will be added to the order informing the customer. ::: -### `purchasableShippable` +#### `modifyPurchasablesTableQuery` + +The event that is triggered retrieving the list of purchasables for the add a line item feature on the order edit page. + +This example adds a condition to the query to only return purchasables with a SKU that contains `foo`: + +```php +use craft\commerce\controllers\OrdersController; +use craft\commerce\events\ModifyPurchasablesTableQueryEvent; + +Event::on( + OrdersController::class, + OrdersController::EVENT_MODIFY_PURCHASABLES_TABLE_QUERY, + function(ModifyPurchasablesTableQueryEvent $event) { + $likeOperator = Craft::$app->getDb()->getIsPgsql() ? 'ILIKE' : 'LIKE'; + $event->query->andWhere([$likeOperator, 'sku', 'foo']); + } +); +``` + +#### `purchasableShippable` The event that is triggered when determining whether a purchasable may be shipped. @@ -1854,3 +1852,25 @@ Event::on( } ); ``` + +### Shipping + +#### `registerAvailableShippingMethods` + +The event that is triggered for registration of additional shipping methods. + +This example adds an instance of `MyShippingMethod` to the event object’s `shippingMethods` array: + +```php +use craft\commerce\events\RegisterAvailableShippingMethodsEvent; +use craft\commerce\services\ShippingMethods; +use yii\base\Event; + +Event::on( + ShippingMethods::class, + ShippingMethods::EVENT_REGISTER_AVAILABLE_SHIPPING_METHODS, + function(RegisterAvailableShippingMethodsEvent $event) { + $event->shippingMethods[] = MyShippingMethod::class; + } +); +``` diff --git a/docs/commerce/4.x/making-payments.md b/docs/commerce/4.x/making-payments.md index 6d4d56075..7b514abaf 100644 --- a/docs/commerce/4.x/making-payments.md +++ b/docs/commerce/4.x/making-payments.md @@ -1,24 +1,26 @@ # Making Payments -Once you’ve set up [the store](configuration.md) and [payment gateways](payment-gateways.md), you can start accepting payments. - -Commerce supports taking payments from the customer at checkout and from the store manager via the Craft control panel. Payments can be required for order completion, deferred until later, or made in parts depending on your store’s configuration and gateway support. +Commerce supports taking payments from the customer at checkout and by a store manager via the Craft control panel. Payments can be [required](#full-payment-at-checkout) for order completion, [deferred](#checkout-without-payment) until later, or made [in parts](#checkout-with-partial-payment), depending on your store’s configuration and [gateway](payment-gateways.md) support. ## Full Payment at Checkout -It’s most common to have a customer provide information for the payment gateway and pay in full to complete an order. +The most common checkout process involves a customer paying in full by furnishing payment method details to a gateway. + +In this example, we’ll assume a customer has finished shopping, and that we know what payment gateway they intend to use—it could be that the store only uses one gateway, or that they were given an opportunity to select a gateway in a previous step. -In this example, we’ll assume a customer has finished shopping and building a cart and that we know what payment gateway they intend to use. (It could be that the store only uses one gateway, or they explicitly chose a gateway in a previous step.) +::: tip +Send a `gatewayId` param to the [`commerce/cart/update-cart` action](dev/controller-actions.md#post-cart-update-cart) to select a gateway ahead of time. +::: -The payment gateway is set on the cart, and any forms meant for it must be namespaced. This template uses `cart.gateway.getPaymentFormHtml()` to render the form fields required by the payment gateway, posting them to the [`commerce/payments/pay`](./dev/controller-actions.html#post-payments-pay) controller action: +This template uses `cart.gateway.getPaymentFormHtml()` to render the form fields required by the payment gateway, posting them to the [`commerce/payments/pay`](./dev/controller-actions.html#post-payments-pay) controller action: ```twig {# @var cart craft\commerce\elements\Order #}
{{ csrfInput() }} {{ actionInput('commerce/payments/pay') }} - {{ redirectInput('/commerce/customer/order?number={number}') }} - {{ hiddenInput('cancelUrl', '/commerce/checkout/payment'|hash) }} + {{ redirectInput('commerce/customer/order?number={number}') }} + {{ hiddenInput('cancelUrl', 'commerce/checkout/payment'|hash) }} {% namespace cart.gateway.handle|commercePaymentFormNamespace %} {{ cart.gateway.getPaymentFormHtml({})|raw }} @@ -29,116 +31,34 @@ The payment gateway is set on the cart, and any forms meant for it must be names ``` ::: tip -Using `gateway.getPaymentFormHtml()` is the quick way to get form elements from the gateway plugin; often you’ll want to render and style these form fields based on the needs of your site and gateway. -::: - -This manual form example assumes the availability of a `paymentForm` variable, as discussed in [Payment Form Models](payment-form-models.md), and might be what a simple credit card payment form would look like: - - - -```twig -{% import '_includes/forms.twig' as forms %} - - {{ csrfInput() }} - {{ actionInput('commerce/payments/pay') }} - {{ redirectInput('/commerce/customer/order?number={number}') }} - {{ hiddenInput('cancelUrl', '/commerce/checkout/payment'|hash) }} +Using `gateway.getPaymentFormHtml()` is the quickest way to get form elements from the gateway; often, you’ll want to render and style these form fields based on the needs of your site and gateway. - {% namespace cart.gateway.handle|commercePaymentFormNamespace %} - {# First and last name #} -
- Card Holder - - {{ forms.text({ - name: 'firstName', - maxlength: 70, - placeholder: 'First Name', - autocomplete: false, - class: 'card-holder-first-name'~(paymentForm.getErrors('firstName') ? ' error'), - value: paymentForm.firstName, - required: true, - }) }} - - {{ forms.text({ - name: 'lastName', - maxlength: 70, - placeholder: 'Last Name', - autocomplete: false, - class: 'card-holder-last-name'~(paymentForm.getErrors('lastName') ? ' error'), - value: paymentForm.lastName, - required: true, - }) }} - - {% set errors = [] %} - {% for attributeKey in ['firstName', 'lastName'] %} - {% set errors = errors|merge(paymentForm.getErrors(attributeKey)) %} - {% endfor %} - - {{ forms.errorList(errors) }} -
- - {# Card number #} -
- Card - - {{ forms.text({ - name: 'number', - maxlength: 19, - placeholder: 'Card Number', - autocomplete: false, - class: 'card-number'~(paymentForm.getErrors('number') ? ' error'), - value: paymentForm.number - }) }} - - {{ forms.text({ - name: 'expiry', - class: 'card-expiry'~(paymentForm.getErrors('month') or paymentForm.getErrors('year') ? ' error'), - type: 'tel', - placeholder: 'MM / YYYY', - value: paymentForm.expiry - }) }} - - {{ forms.text({ - name: 'cvv', - type: 'tel', - placeholder: 'CVV', - class: 'card-cvc'~(paymentForm.getErrors('cvv') ? ' error'), - value: paymentForm.cvv - }) }} - - {% set errors = [] %} - {% for attributeKey in ['number', 'month', 'year', 'cvv'] %} - {% set errors = errors|merge(paymentForm.getErrors(attributeKey)) %} - {% endfor %} - - {{ forms.errorList(errors) }} -
- - - {% endnamespace %} - -``` - -
+Each gateway will have unique requirements for the data you submit when making a payment—consult its documentation for more information. +::: ## Deferred Payment at Checkout -Commerce provides two options if you don’t want to require full payment from a customer to complete an order: +Commerce provides a couple options if you don’t want to require full payment from a customer to complete an order: -1. Require full payment with an authorize transaction to be captured later by the store manager. (Requires a gateway that supports authorize transactions.) -2. Enable the [allowCheckoutWithoutPayment](config-settings.md#allowcheckoutwithoutpayment) setting and have the customer complete checkout—without payment—via the [`commerce/cart/complete`](./dev/controller-actions.md#post-cart-complete) controller action. +1. Authorize a payment to be captured later by the store manager (not all gateways support authorize-only transactions); +1. Configure your store to allow [checkout without payment](#checkout-without-payment); +1. Use the built-in [Manual gateway](payment-gateways.md#manual-gateway) to track an offsite payment process; + +::: tip +The first-party Stripe gateway supports additional payment plans via third-party services, but their availability varies by region, customer creditworthiness, and other factors. +::: ### Checkout Without Payment -Once the [allowCheckoutWithoutPayment](config-settings.md#allowcheckoutwithoutpayment) setting is enabled, the customer can submit a post request to the [`commerce/cart/complete`](./dev/controller-actions.md#post-cart-complete) controller action to complete the order without any payment. +Once the [allowCheckoutWithoutPayment](config-settings.md#allowcheckoutwithoutpayment) setting is enabled, the customer can submit a POST request to the [`commerce/cart/complete`](./dev/controller-actions.md#post-cart-complete) controller action to complete the order without any payment. ```twig
{{ csrfInput() }} {{ actionInput('commerce/cart/complete') }} - {{ redirectInput('/shop/customer/order?number='~cart.number~'&success=true') }} + {{ redirectInput('/shop/customer/order?number={number}&success=true') }} - +
``` @@ -151,13 +71,15 @@ Like the [`commerce/payments/pay`](./dev/controller-actions.html#post-payments-p ::: warning If you enable order completion without payment, completed orders will have the same status as any others. Don’t forget to make sure store managers are aware of the change and prepared to confirm payment before fulfilling orders! + +If you use these workflows, consider adding columns to the main Order [element indexes](/4.x/elements.md#indexes) for _Date Paid_ or _Amount Paid_ so that it is clear which orders need attention. ::: ### Checkout with Partial Payment A _partial_ payment is one that’s less than an order’s outstanding balance at any point in time. -If you’d like to permit customers to check out with partial payments and the gateway supports them, you can enable the [allowPartialPaymentOnCheckout](config-settings.md#allowpartialpaymentoncheckout) setting to allow an additional `paymentAmount` field when posting to the [`commerce/payments/pay`](./dev/controller-actions.html#post-payments-pay) controller action. (If no `paymentAmount` field is submitted, the order’s oustanding balance amount will be applied.) +If you’d like to permit customers to check out with partial payments and the gateway supports them, you can enable the [allowPartialPaymentOnCheckout](config-settings.md#allowpartialpaymentoncheckout) setting to allow an additional hashed `paymentAmount` field when posting to the [`commerce/payments/pay`](./dev/controller-actions.html#post-payments-pay) controller action. If no `paymentAmount` field is submitted, the order’s outstanding balance will be used. ::: tip Multiple payments can still be made on an order when `allowPartialPaymentOnCheckout` is `false`, as long as each payment is equal to the outstanding balance at the time it was made. @@ -189,11 +111,11 @@ This example provides a dropdown menu that allows the customer to choose half or %} @@ -206,6 +128,8 @@ A customer may return to make additional payments similarly to the [outstanding You can use the [`paidInFull`](extend/events.md#paidinfull) event if you need to add any custom functionality when an order is paid in full. ::: +An order is considered “paid in full” as long as the total amount paid did at one point reach the order’s total—even if a payment is refunded. + ### Paying an Outstanding Balance You can allow a customer to pay the outstanding balance on a cart or order using the [`commerce/payments/pay`](./dev/controller-actions.html#post-payments-pay) controller action similarly to taking full payment at checkout, taking care to explicitly provide the order number whose outstanding balance should be paid. @@ -214,7 +138,7 @@ You can allow a customer to pay the outstanding balance on a cart or order using There’s a full example of this in the [example templates](example-templates.md) at [shop/checkout/pay-static.twig](https://github.com/craftcms/commerce/tree/main/example-templates/dist/shop/checkout/pay-static.twig). ::: -Here we’re pretending the relevant order number is 12345, the customer’s email address is email@address.foo, and the gateway is already set on the order: +Here, we’re pretending the relevant order number is `12345`, the customer’s email address is `email@address.foo`, and the gateway is already set on the order: ```twig {% set number = '12345' %} @@ -225,7 +149,7 @@ Here we’re pretending the relevant order number is 12345, the customer’s ema
{{ csrfInput() }} {{ actionInput('commerce/payments/pay') }} - {{ redirectInput('/shop/customer/order?number='~cart.number~'&success=true') }} + {{ redirectInput('/shop/customer/order?number={number}&success=true') }} {{ hiddenInput('cancelUrl', cancelUrl) }} {{ hiddenInput('email', email) }} {{ hiddenInput('orderNumber', cart.number) }} @@ -238,7 +162,7 @@ Here we’re pretending the relevant order number is 12345, the customer’s ema
``` -If you’d like to have the customer pay with a different gateway than whatever’s specified on the cart/order, pass the `gatewayId` in the form: +If you’d like to have the customer pay with a different gateway than whatever was specified on the cart/order, pass the `gatewayId` in the form: ```twig {# ... #} diff --git a/docs/commerce/4.x/orders-carts.md b/docs/commerce/4.x/orders-carts.md index 020e03916..349217c33 100644 --- a/docs/commerce/4.x/orders-carts.md +++ b/docs/commerce/4.x/orders-carts.md @@ -1,5 +1,6 @@ --- sidebarDepth: 2 +containsGeneratedContent: yes --- # Orders & Carts @@ -7,6 +8,8 @@ Variants are added to a _cart_ that can be completed to become an _order_. Carts When we use the terms “cart” and “order”, we’re always referring to an [Order](commerce4:craft\commerce\elements\Order) element; a cart is simply an order that hasn’t been completed—meaning its `isCompleted` property is `false` and its `dateCompleted` is `null`. +Typically, a cart is completed in response to a customer [making a payment](./making-payments.md)—or by satisfying other requirements you’ve defined through [configuration](./config-settings.md) or an [extension](./extend/README.md). + ## Carts As a customer or store manager is building a cart, the goal is to maintain an up-to-date list of items with their relevant costs, discounts, and promotions. For this reason, the cart will be recalculated each time a change is made. @@ -24,7 +27,7 @@ Let’s go over a few common actions you may want to perform on a cart: - [Working with Line Items](#working-with-line-items) - [Loading a Cart](#loading-a-cart) - [Using Custom Fields](#storing-data-in-custom-fields) -- [Forgetting a Cart](#forgetting-a-cart) +- [Forgetting](#forget-a-cart) and [loading](#load-a-cart) carts More topics are covered in separate pages: @@ -269,9 +272,13 @@ Each line item includes several totals: - **lineItem.adjustmentsTotal** is the sum of each of the line item’s adjustment `amount` values. - **lineItem.total** is the sum of the line item’s `subtotal` and `adjustmentsTotal`. -### Loading a Cart +### Loading and Forgetting Carts + +“Loading” and “forgetting” are a pair of actions that affect what cart is associated with the customer’s session. -Commerce provides a `commerce/cart/load-cart` endpoint for loading an existing cart into a cookie for the current customer. +#### Load a Cart + +Commerce provides a [`commerce/cart/load-cart`](dev/controller-actions.md#get-post-cart-load-cart) endpoint for loading an existing cart into a cookie for the current customer. You can have the user interact with the endpoint by either [navigating to a URL](#loading-a-cart-with-a-url) or by [submitting a form](#loading-a-cart-with-a-form). Either way, the cart number is required. @@ -281,7 +288,7 @@ Each method will store any errors in the session’s error flash data (`craft.ap If the desired cart belongs to a user, that user must be logged in to load it into a browser cookie. ::: -The [`loadCartRedirectUrl`](config-settings.md#loadcartredirecturl) setting determines where the customer will be sent by default after the cart’s loaded. +The [`loadCartRedirectUrl`](config-settings.md#loadcartredirecturl) setting determines where the customer will be sent by default after the cart has been loaded. #### Loading a Cart with a URL @@ -336,13 +343,13 @@ This is a simplified version of [`shop/cart/load.twig`](https://github.com/craft #### Restoring Previous Cart Contents -If the customer’s a registered user they may want to continue shopping from another browser or computer. If that customer has an empty cart—as they would by default—and they log into the site, any previous cart will automatically be loaded. +If the customer is a registered user, they may want to continue shopping from another browser or computer. If they have an empty cart on the second device (as they would by default) and they log in, their most recently-created cart will automatically be loaded. ::: tip -If a customer is a guest with a cart and they create an account, that cart will be maintained after logging in. +When a guest with an active cart creates an account, that cart will be remain active after logging in. ::: -You can allow a customer to see previously-loaded carts: +You can allow a logged-in customer to see their previously used carts: ::: code ```twig @@ -386,7 +393,7 @@ if ($currentUser) { ``` ::: -You could then loop over the line items in those older carts and allow the customer to add them to the current order: +You could then loop over the line items in those older carts and allow the customer to add them to their current cart: ```twig

Previous Cart Items

@@ -399,16 +406,41 @@ You could then loop over the line items in those older carts and allow the custo {% for lineItem in oldCart.lineItems %} {{ lineItem.description }} {% endfor %} {% endfor %} - + ``` +### Forgetting a Cart + +A logged-in customer’s cart is stored in a cookie that persists across sessions, so they can close their browser and return to the store without losing their cart. If the customer logs out, their cart will automatically be forgotten. + +Removing all the items from a cart doesn’t mean that the cart is forgotten, though—sometimes, fully detaching a cart from the session is preferable to emptying it. To remove a cart from the customer’s session (without logging out or clearing the items), make a `POST` request to the [`cart/forget-cart` action](dev/controller-actions.md#post-cart-forget-cart). A cart number is _not_ required—Commerce can only detach the customer’s current cart. + +The next time the customer makes a request to the [`update-cart` action](dev/controller-actions.md#post-cart-update-cart), they will be given a new cart + +::: tip +In previous versions, you can call the `forgetCart()` method manually to remove the current cart cookie. The cart itself will not be deleted—just disassociated with the customer’s session until it’s loaded again by some other means. + +::: code +```twig +{# Forget the cart in the current session. #} +{{ craft.commerce.carts.forgetCart() }} +``` +```php +use craft\commerce\Plugin as Commerce; + +// Forget the cart in the current session. +Commerce::getInstance()->getCarts()->forgetCart(); +``` +::: +::: + ### Storing Data in Custom Fields Like any other type of [element](/4.x/elements.md), orders can have custom fields associated with them via a field layout. To customize the fields available on carts and orders, visit **Commerce** → **System Settings** → **Order Fields**. @@ -436,27 +468,6 @@ You can update custom fields on a cart by posting data to the [`commerce/cart/up ``` -### Forgetting a Cart - -A logged-in customer’s cart is stored in a cookie that persists across sessions, so they can close their browser and return to the store without losing their cart. - -If the customer logs out, their cart will automatically be forgotten. - -You can call the `forgetCart()` method manually to remove the current cart cookie. The cart itself will not be deleted, but disassociated with any sessions until it’s loaded again. - -::: code -```twig -{# Forget the cart in the current session. #} -{{ craft.commerce.carts.forgetCart() }} -``` -```php -use craft\commerce\Plugin as Commerce; - -// Forget the cart in the current session. -Commerce::getInstance()->getCarts()->forgetCart(); -``` -::: - ## Orders Orders are [Element Types](/4.x/extend/element-types.md) and can have custom fields associated with them. You can browse orders in the control panel by navigating to **Commerce** → **Orders**. @@ -769,1489 +780,5 @@ We can display an order with a given order number by doing the following: Order queries support the following parameters: - - - - - - -| Param | Description -| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only orders that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching orders as arrays of data, rather than [Order](commerce4:craft\commerce\elements\Order) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [customer](#customer) | Narrows the query results based on the customer’s user account. -| [customerId](#customerid) | Narrows the query results based on the customer, per their user ID. -| [dateAuthorized](#dateauthorized) | Narrows the query results based on the orders’ authorized dates. -| [dateCreated](#datecreated) | Narrows the query results based on the orders’ creation dates. -| [dateOrdered](#dateordered) | Narrows the query results based on the orders’ completion dates. -| [datePaid](#datepaid) | Narrows the query results based on the orders’ paid dates. -| [dateUpdated](#dateupdated) | Narrows the query results based on the orders’ last-updated dates. -| [email](#email) | Narrows the query results based on the customers’ email addresses. -| [expiryDate](#expirydate) | Narrows the query results based on the orders’ expiry dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [gateway](#gateway) | Narrows the query results based on the gateway. -| [gatewayId](#gatewayid) | Narrows the query results based on the gateway, per its ID. -| [hasLineItems](#haslineitems) | Narrows the query results to only orders that have line items. -| [hasPurchasables](#haspurchasables) | Narrows the query results to only orders that have certain purchasables. -| [hasTransactions](#hastransactions) | Narrows the query results to only carts that have at least one transaction. -| [id](#id) | -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [isCompleted](#iscompleted) | Narrows the query results to only orders that are completed. -| [isPaid](#ispaid) | Narrows the query results to only orders that are paid. -| [isUnpaid](#isunpaid) | Narrows the query results to only orders that are not paid. -| [itemSubtotal](#itemsubtotal) | Narrows the query results based on the order’s item subtotal. -| [itemTotal](#itemtotal) | Narrows the query results based on the order’s item total. -| [limit](#limit) | Determines the number of orders that should be returned. -| [number](#number) | Narrows the query results based on the order number. -| [offset](#offset) | Determines how many orders should be skipped in the results. -| [orderBy](#orderby) | Determines the order that the orders should be returned in. (If empty, defaults to `id ASC`.) -| [orderLanguage](#orderlanguage) | Narrows the query results based on the order language, per the language string provided. -| [orderSiteId](#ordersiteid) | Narrows the query results based on the order language, per the language string provided. -| [orderStatus](#orderstatus) | Narrows the query results based on the order statuses. -| [orderStatusId](#orderstatusid) | Narrows the query results based on the order statuses, per their IDs. -| [origin](#origin) | Narrows the query results based on the origin. -| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v4/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [reference](#reference) | Narrows the query results based on the order reference. -| [relatedTo](#relatedto) | Narrows the query results to only orders that are related to certain other elements. -| [search](#search) | Narrows the query results to only orders that match a search query. -| [shippingMethodHandle](#shippingmethodhandle) | Narrows the query results based on the shipping method handle. -| [shortNumber](#shortnumber) | Narrows the query results based on the order short number. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the orders’ IDs in the `elements_sites` table. -| [total](#total) | Narrows the query results based on the total. -| [totalDiscount](#totaldiscount) | Narrows the query results based on the total discount. -| [totalPaid](#totalpaid) | Narrows the query results based on the total paid amount. -| [totalPrice](#totalprice) | Narrows the query results based on the total price. -| [totalQty](#totalqty) | Narrows the query results based on the total qty of items. -| [totalTax](#totaltax) | Narrows the query results based on the total tax. -| [trashed](#trashed) | Narrows the query results to only orders that have been soft-deleted. -| [uid](#uid) | Narrows the query results based on the orders’ UIDs. -| [with](#with) | Causes the query to return matching orders eager-loaded with related elements. -| [withAddresses](#withaddresses) | Eager loads the the shipping and billing addressees on the resulting orders. -| [withAdjustments](#withadjustments) | Eager loads the order adjustments on the resulting orders. -| [withAll](#withall) | Eager loads all relational data (addresses, adjustents, customers, line items, transactions) for the resulting orders. -| [withCustomer](#withcustomer) | Eager loads the user on the resulting orders. -| [withLineItems](#withlineitems) | Eager loads the line items on the resulting orders. -| [withTransactions](#withtransactions) | Eager loads the transactions on the resulting orders. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only orders that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all orders that are related to myCategoryA and myCategoryB #} -{% set orders = craft.orders() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all orders that are related to $myCategoryA and $myCategoryB -$orders = \craft\commerce\elements\Order::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching orders as arrays of data, rather than [Order](commerce4:craft\commerce\elements\Order) objects. - - - - - -::: code -```twig -{# Fetch orders as arrays #} -{% set orders = craft.orders() - .asArray() - .all() %} -``` - -```php -// Fetch orders as arrays -$orders = \craft\commerce\elements\Order::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `customer` - -Narrows the query results based on the customer’s user account. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a customer with a user account ID of 1. -| a [User](https://docs.craftcms.com/api/v4/craft-elements-user.html) object | with a customer with a user account represented by the object. -| `'not 1'` | not the user account with an ID 1. -| `[1, 2]` | with an user account ID of 1 or 2. -| `['not', 1, 2]` | not with a user account ID of 1 or 2. - - - -::: code -```twig -{# Fetch the current user's orders #} -{% set orders = craft.orders() - .customer(currentUser) - .all() %} -``` - -```php -// Fetch the current user's orders -$user = Craft::$app->user->getIdentity(); -$orders = \craft\commerce\elements\Order::find() - ->customer($user) - ->all(); -``` -::: - - -#### `customerId` - -Narrows the query results based on the customer, per their user ID. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a user with an ID of 1. -| `'not 1'` | not with a user with an ID of 1. -| `[1, 2]` | with a user with an ID of 1 or 2. -| `['not', 1, 2]` | not with a user with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the current user's orders #} -{% set orders = craft.orders() - .customerId(currentUser.id) - .all() %} -``` - -```php -// Fetch the current user's orders -$user = Craft::$app->user->getIdentity(); -$orders = \craft\commerce\elements\Order::find() - ->customerId($user->id) - ->all(); -``` -::: - - -#### `dateAuthorized` - -Narrows the query results based on the orders’ authorized dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were authorized on or after 2018-04-01. -| `'< 2018-05-01'` | that were authorized before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders that were authorized recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set orders = craft.orders() - .dateAuthorized(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch orders that were authorized recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateAuthorized(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateCreated` - -Narrows the query results based on the orders’ creation dates. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch orders created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set orders = craft.orders() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch orders created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateOrdered` - -Narrows the query results based on the orders’ completion dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were completed on or after 2018-04-01. -| `'< 2018-05-01'` | that were completed before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders that were completed recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set orders = craft.orders() - .dateOrdered(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch orders that were completed recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateOrdered(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `datePaid` - -Narrows the query results based on the orders’ paid dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were paid on or after 2018-04-01. -| `'< 2018-05-01'` | that were paid before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were completed between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch orders that were paid for recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set orders = craft.orders() - .datePaid(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch orders that were paid for recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->datePaid(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the orders’ last-updated dates. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch orders updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set orders = craft.orders() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch orders updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `email` - -Narrows the query results based on the customers’ email addresses. - -Possible values include: - -| Value | Fetches orders with customers… -| - | - -| `'foo@bar.baz'` | with an email of `foo@bar.baz`. -| `'not foo@bar.baz'` | not with an email of `foo@bar.baz`. -| `'*@bar.baz'` | with an email that ends with `@bar.baz`. - - - -::: code -```twig -{# Fetch orders from customers with a .co.uk domain on their email address #} -{% set orders = craft.orders() - .email('*.co.uk') - .all() %} -``` - -```php -// Fetch orders from customers with a .co.uk domain on their email address -$orders = \craft\commerce\elements\Order::find() - ->email('*.co.uk') - ->all(); -``` -::: - - -#### `expiryDate` - -Narrows the query results based on the orders’ expiry dates. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. -| `'< 2020-05-01'` | that will expire before 2020-05-01 -| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. - - - -::: code -```twig -{# Fetch orders expiring this month #} -{% set nextMonth = date('first day of next month')|atom %} - -{% set orders = craft.orders() - .expiryDate("< #{nextMonth}") - .all() %} -``` - -```php -// Fetch orders expiring this month -$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); - -$orders = \craft\commerce\elements\Order::find() - ->expiryDate("< {$nextMonth}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch orders in a specific order #} -{% set orders = craft.orders() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch orders in a specific order -$orders = \craft\commerce\elements\Order::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `gateway` - -Narrows the query results based on the gateway. - -Possible values include: - -| Value | Fetches orders… -| - | - -| a [Gateway](commerce4:craft\commerce\base\Gateway) object | with a gateway represented by the object. - - - - -#### `gatewayId` - -Narrows the query results based on the gateway, per its ID. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with a gateway with an ID of 1. -| `'not 1'` | not with a gateway with an ID of 1. -| `[1, 2]` | with a gateway with an ID of 1 or 2. -| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. - - - - -#### `hasLineItems` - -Narrows the query results to only orders that have line items. - - - -::: code -```twig -{# Fetch orders that do or do not have line items #} -{% set orders = craft.orders() - .hasLineItems() - .all() %} -``` - -```php -// Fetch unpaid orders -$orders = \craft\commerce\elements\Order::find() - ->hasLineItems() - ->all(); -``` -::: - - -#### `hasPurchasables` - -Narrows the query results to only orders that have certain purchasables. - -Possible values include: - -| Value | Fetches orders… -| - | - -| a [PurchasableInterface](commerce4:craft\commerce\base\PurchasableInterface) object | with a purchasable represented by the object. -| an array of [PurchasableInterface](commerce4:craft\commerce\base\PurchasableInterface) objects | with all the purchasables represented by the objects. - - - - -#### `hasTransactions` - -Narrows the query results to only carts that have at least one transaction. - - - -::: code -```twig -{# Fetch carts that have attempted payments #} -{% set orders = craft.orders() - .hasTransactions() - .all() %} -``` - -```php -// Fetch carts that have attempted payments -$orders = \craft\commerce\elements\Order::find() - ->hasTransactions() - ->all(); -``` -::: - - -#### `id` - - - - - - - - -#### `ignorePlaceholders` - -Causes the query to return matching orders as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch orders in reverse #} -{% set orders = craft.orders() - .inReverse() - .all() %} -``` - -```php -// Fetch orders in reverse -$orders = \craft\commerce\elements\Order::find() - ->inReverse() - ->all(); -``` -::: - - -#### `isCompleted` - -Narrows the query results to only orders that are completed. - - - -::: code -```twig -{# Fetch completed orders #} -{% set orders = craft.orders() - .isCompleted() - .all() %} -``` - -```php -// Fetch completed orders -$orders = \craft\commerce\elements\Order::find() - ->isCompleted() - ->all(); -``` -::: - - -#### `isPaid` - -Narrows the query results to only orders that are paid. - - - -::: code -```twig -{# Fetch paid orders #} -{% set orders = craft.orders() - .isPaid() - .all() %} -``` - -```php -// Fetch paid orders -$orders = \craft\commerce\elements\Order::find() - ->isPaid() - ->all(); -``` -::: - - -#### `isUnpaid` - -Narrows the query results to only orders that are not paid. - - - -::: code -```twig -{# Fetch unpaid orders #} -{% set orders = craft.orders() - .isUnpaid() - .all() %} -``` - -```php -// Fetch unpaid orders -$orders = \craft\commerce\elements\Order::find() - ->isUnpaid() - ->all(); -``` -::: - - -#### `itemSubtotal` - -Narrows the query results based on the order’s item subtotal. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `100` | with an item subtotal of 0. -| `'< 1000000'` | with an item subtotal of less than ,000,000. -| `['>= 10', '< 100']` | with an item subtotal of between and 0. - - - - -#### `itemTotal` - -Narrows the query results based on the order’s item total. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `100` | with an item total of 0. -| `'< 1000000'` | with an item total of less than ,000,000. -| `['>= 10', '< 100']` | with an item total of between and 0. - - - - -#### `limit` - -Determines the number of orders that should be returned. - - - -::: code -```twig -{# Fetch up to 10 orders #} -{% set orders = craft.orders() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 orders -$orders = \craft\commerce\elements\Order::find() - ->limit(10) - ->all(); -``` -::: - - -#### `number` - -Narrows the query results based on the order number. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'` | with a matching order number - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderNumber = craft.app.request.getQueryParam('number') %} -{% set order = craft.orders() - .number(orderNumber) - .one() %} -``` - -```php -// Fetch the requested order -$orderNumber = Craft::$app->request->getQueryParam('number'); -$order = \craft\commerce\elements\Order::find() - ->number($orderNumber) - ->one(); -``` -::: - - -#### `offset` - -Determines how many orders should be skipped in the results. - - - -::: code -```twig -{# Fetch all orders except for the first 3 #} -{% set orders = craft.orders() - .offset(3) - .all() %} -``` - -```php -// Fetch all orders except for the first 3 -$orders = \craft\commerce\elements\Order::find() - ->offset(3) - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the orders should be returned in. (If empty, defaults to `id ASC`.) - - - -::: code -```twig -{# Fetch all orders in order of date created #} -{% set orders = craft.orders() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all orders in order of date created -$orders = \craft\commerce\elements\Order::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `orderLanguage` - -Narrows the query results based on the order language, per the language string provided. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'en'` | with an order language that is `'en'`. -| `'not en'` | not with an order language that is not `'en'`. -| `['en', 'en-us']` | with an order language that is `'en'` or `'en-us'`. -| `['not', 'en']` | not with an order language that is not `'en'`. - - - -::: code -```twig -{# Fetch orders with an order language that is `'en'` #} -{% set orders = craft.orders() - .orderLanguage('en') - .all() %} -``` - -```php -// Fetch orders with an order language that is `'en'` -$orders = \craft\commerce\elements\Order::find() - ->orderLanguage('en') - ->all(); -``` -::: - - -#### `orderSiteId` - -Narrows the query results based on the order language, per the language string provided. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an order site ID of 1. -| `'not 1'` | not with an order site ID that is no 1. -| `[1, 2]` | with an order site ID of 1 or 2. -| `['not', 1, 2]` | not with an order site ID of 1 or 2. - - - -::: code -```twig -{# Fetch orders with an order site ID of 1 #} -{% set orders = craft.orders() - .orderSiteId(1) - .all() %} -``` - -```php -// Fetch orders with an order site ID of 1 -$orders = \craft\commerce\elements\Order::find() - ->orderSiteId(1) - ->all(); -``` -::: - - -#### `orderStatus` - -Narrows the query results based on the order statuses. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'foo'` | with an order status with a handle of `foo`. -| `'not foo'` | not with an order status with a handle of `foo`. -| `['foo', 'bar']` | with an order status with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not with an order status with a handle of `foo` or `bar`. -| a [OrderStatus](commerce4:craft\commerce\models\OrderStatus) object | with an order status represented by the object. - - - -::: code -```twig -{# Fetch shipped orders #} -{% set orders = craft.orders() - .orderStatus('shipped') - .all() %} -``` - -```php -// Fetch shipped orders -$orders = \craft\commerce\elements\Order::find() - ->orderStatus('shipped') - ->all(); -``` -::: - - -#### `orderStatusId` - -Narrows the query results based on the order statuses, per their IDs. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an order status with an ID of 1. -| `'not 1'` | not with an order status with an ID of 1. -| `[1, 2]` | with an order status with an ID of 1 or 2. -| `['not', 1, 2]` | not with an order status with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch orders with an order status with an ID of 1 #} -{% set orders = craft.orders() - .orderStatusId(1) - .all() %} -``` - -```php -// Fetch orders with an order status with an ID of 1 -$orders = \craft\commerce\elements\Order::find() - ->orderStatusId(1) - ->all(); -``` -::: - - -#### `origin` - -Narrows the query results based on the origin. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'web'` | with an origin of `web`. -| `'not remote'` | not with an origin of `remote`. -| `['web', 'cp']` | with an order origin of `web` or `cp`. -| `['not', 'remote', 'cp']` | not with an origin of `web` or `cp`. - - - -::: code -```twig -{# Fetch shipped orders #} -{% set orders = craft.orders() - .origin('web') - .all() %} -``` - -```php -// Fetch shipped orders -$orders = \craft\commerce\elements\Order::find() - ->origin('web') - ->all(); -``` -::: - - -#### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v4/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique orders from Site A, or Site B if they don’t exist in Site A #} -{% set orders = craft.orders() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique orders from Site A, or Site B if they don’t exist in Site A -$orders = \craft\commerce\elements\Order::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `reference` - -Narrows the query results based on the order reference. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'Foo'` | with a reference of `Foo`. -| `'Foo*'` | with a reference that begins with `Foo`. -| `'*Foo'` | with a reference that ends with `Foo`. -| `'*Foo*'` | with a reference that contains `Foo`. -| `'not *Foo*'` | with a reference that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a reference that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a reference that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderReference = craft.app.request.getQueryParam('ref') %} -{% set order = craft.orders() - .reference(orderReference) - .one() %} -``` - -```php -// Fetch the requested order -$orderReference = Craft::$app->request->getQueryParam('ref'); -$order = \craft\commerce\elements\Order::find() - ->reference($orderReference) - ->one(); -``` -::: - - -#### `relatedTo` - -Narrows the query results to only orders that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all orders that are related to myCategory #} -{% set orders = craft.orders() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all orders that are related to $myCategory -$orders = \craft\commerce\elements\Order::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only orders that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all orders that match the search query #} -{% set orders = craft.orders() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all orders that match the search query -$orders = \craft\commerce\elements\Order::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `shippingMethodHandle` - -Narrows the query results based on the shipping method handle. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'foo'` | with a shipping method with a handle of `foo`. -| `'not foo'` | not with a shipping method with a handle of `foo`. -| `['foo', 'bar']` | with a shipping method with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not with a shipping method with a handle of `foo` or `bar`. -| a `\craft\commerce\elements\db\ShippingMethod` object | with a shipping method represented by the object. - - - -::: code -```twig -{# Fetch collection shipping method orders #} -{% set orders = craft.orders() - .shippingMethodHandle('collection') - .all() %} -``` - -```php -// Fetch collection shipping method orders -$orders = \craft\commerce\elements\Order::find() - ->shippingMethodHandle('collection') - ->all(); -``` -::: - - -#### `shortNumber` - -Narrows the query results based on the order short number. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `'xxxxxxx'` | with a matching order number - - - -::: code -```twig -{# Fetch the requested order #} -{% set orderNumber = craft.app.request.getQueryParam('shortNumber') %} -{% set order = craft.orders() - .shortNumber(orderNumber) - .one() %} -``` - -```php -// Fetch the requested order -$orderNumber = Craft::$app->request->getQueryParam('shortNumber'); -$order = \craft\commerce\elements\Order::find() - ->shortNumber($orderNumber) - ->one(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the orders’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches orders… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the order by its ID in the elements_sites table #} -{% set order = craft.orders() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the order by its ID in the elements_sites table -$order = \craft\commerce\elements\Order::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `total` - -Narrows the query results based on the total. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `10` | with a total price of . -| `['and', 10, 20]` | an order with a total of or . - - - - -#### `totalDiscount` - -Narrows the query results based on the total discount. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `10` | with a total discount of 10. -| `[10, 20]` | an order with a total discount of 10 or 20. - - - - -#### `totalPaid` - -Narrows the query results based on the total paid amount. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `10` | with a total paid amount of . -| `['and', 10, 20]` | an order with a total paid amount of or . - - - - -#### `totalPrice` - -Narrows the query results based on the total price. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `10` | with a total price of . -| `['and', 10, 20]` | an order with a total price of or . - - - - -#### `totalQty` - -Narrows the query results based on the total qty of items. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `10` | with a total qty of 10. -| `[10, 20]` | an order with a total qty of 10 or 20. - - - - -#### `totalTax` - -Narrows the query results based on the total tax. - -Possible values include: - -| Value | Fetches orders… -| - | - -| `10` | with a total tax of 10. -| `[10, 20]` | an order with a total tax of 10 or 20. - - - - -#### `trashed` - -Narrows the query results to only orders that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed orders #} -{% set orders = craft.orders() - .trashed() - .all() %} -``` - -```php -// Fetch trashed orders -$orders = \craft\commerce\elements\Order::find() - ->trashed() - ->all(); -``` -::: - - -#### `uid` - -Narrows the query results based on the orders’ UIDs. - - - - - -::: code -```twig -{# Fetch the order by its UID #} -{% set order = craft.orders() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the order by its UID -$order = \craft\commerce\elements\Order::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `with` - -Causes the query to return matching orders eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch orders eager-loaded with the "Related" field’s relations #} -{% set orders = craft.orders() - .with(['related']) - .all() %} -``` - -```php -// Fetch orders eager-loaded with the "Related" field’s relations -$orders = \craft\commerce\elements\Order::find() - ->with(['related']) - ->all(); -``` -::: - - -#### `withAddresses` - -Eager loads the the shipping and billing addressees on the resulting orders. - -Possible values include: - -| Value | Fetches addresses -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withAdjustments` - -Eager loads the order adjustments on the resulting orders. - -Possible values include: - -| Value | Fetches adjustments -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withAll` - -Eager loads all relational data (addresses, adjustents, customers, line items, transactions) for the resulting orders. - -Possible values include: - -| Value | Fetches addresses, adjustents, customers, line items, transactions -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withCustomer` - -Eager loads the user on the resulting orders. - -Possible values include: - -| Value | Fetches adjustments -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withLineItems` - -Eager loads the line items on the resulting orders. - -Possible values include: - -| Value | Fetches line items -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - -#### `withTransactions` - -Eager loads the transactions on the resulting orders. - -Possible values include: - -| Value | Fetches transactions… -| - | - -| bool | `true` to eager-load, `false` to not eager load. - - - - - - + +!!!include(docs/.artifacts/commerce/4.x/orders-carts.md)!!! diff --git a/docs/commerce/4.x/payment-form-models.md b/docs/commerce/4.x/payment-form-models.md index 46efb8961..006d4837a 100644 --- a/docs/commerce/4.x/payment-form-models.md +++ b/docs/commerce/4.x/payment-form-models.md @@ -12,13 +12,21 @@ Generally, you shouldn’t be concerned with the specific type of payment form m The following payment form model attributes exist for gateways handling credit card information: -| Attribute | Validation | Description | -| -------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `token` | not validated | If a token is found on the payment form, no validation of other fields is performed and the data is ignored.

The token represents a pre-validated credit card and is provided by a gateway’s client-side JavaScript library. One example of this is [Stripe.js](https://stripe.com/docs/stripe-js). | -| `firstName` | required | The first name on the customer’s credit card. | -| `lastName` | required | The last name of the customer’s credit card. | -| `month` | required, min: `1`, max: `12` | Integer representing the month of credit card expiry. | -| `year` | required, min: current year, max: current year + 12 | Integer representing the year of credit card expiry. | -| `CVV` | minLength: 3, maxLength: 4 | Integer found on the back of the card for security. | -| `number` | [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) | The credit card number itself. | -| `threeDSecure` | not validated | A flag indicating whether 3D Secure authentication is being performed for the transaction. | +::: danger +**We highly discourage creating gateways that directly capture credit card information. Instead, the `token` attribute can be used to transport a one-time use identifier for a payment method that is [tokenized](#tokenization) by a client-side script.** +::: + +| Attribute | Validation | Description | +| --- | --- | --- | +| `token` | not validated | If a token is present on the payment form, no validation of other fields is performed and the data is ignored. | +| `firstName` | required | The first name on the customer’s credit card. | +| `lastName` | required | The last name of the customer’s credit card. | +| `month` | required, min: `1`, max: `12` | Integer representing the month of credit card expiry. | +| `year` | required, min: current year, max: current year + 12 | Integer representing the year of credit card expiry. | +| `CVV` | minLength: 3, maxLength: 4 | Integer found on the back of the card for security. | +| `number` | [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) | The credit card number itself. | +| `threeDSecure` | not validated | A flag indicating whether 3D Secure authentication is being performed for the transaction. | + +## Tokenization + +Whenever possible, gateways should pre-validate credit card information using the processor’s client-side JavaScript library. The [Stripe](https://plugins.craftcms.com/commerce-stripe) plugin does exactly this—many other payment processors have equivalent tokenization systems that avoid sending sensitive information to your server. diff --git a/docs/commerce/4.x/payment-gateways.md b/docs/commerce/4.x/payment-gateways.md index 902ef77c0..20470a38b 100644 --- a/docs/commerce/4.x/payment-gateways.md +++ b/docs/commerce/4.x/payment-gateways.md @@ -1,84 +1,103 @@ # Payment Gateways -Craft Commerce payments gateways are provided by Craft CMS plugins. +As a self-hosted ecommerce solution, Commerce handles payments differently from popular software-as-a-service products—instead of providing a fixed list of payment processors, we designed flexible gateway and transaction APIs that let -To create a payment gateway you must install the appropriate plugin, navigate to **Commerce** → **Settings** → **Gateways**, and add configuration for that gateway. For more detailed instructions, see each plugin’s `README.md` file. +To capture live payments, you must install a [payment gateway plugin](#first-party-gateway-plugins). Commerce comes with two [built-in gateways](#built-in-gateways), but they are intended primarily for testing. -Payment gateways generally fit in one of two categories: +In the control panel, navigate to **Commerce** → **Settings** → **Gateways**, and click **+ New gateway**. Each gateway requires different settings—for more detailed instructions, see the plugin’s documentation. Many payment processors require third-party accounts, and provide credentials for communicating with their infrastructure that must be added to the gateway’s configuration. -- External or _offsite_ gateways. -- Merchant-hosted or _onsite_ gateways. +::: tip +When providing secrets in the control panel, we recommend using the special [environment variable syntax](/4.x/config/README.md#control-panel-settings) to prevent them leaking into project config. +::: -Merchant-hosted gateways collect the customer’s credit card details directly on your site, but have much stricter requirements such as an SSL certificate for your server. You will also be subject to much more rigorous security requirements under the PCI DSS (Payment Card Industry Data Security Standard). These security requirements are your responsibility, but some gateways allow payment card tokenization. +Payment gateways (and the specific methods they support) generally use one of two payment flows: + +- **External or _offsite_ gateways:** The customer is redirected to a payment portal hosted by the processor, and is returned to your site once a payment is completed. Your site never sees information about the customer’s payment method—instead, the gateway receives and validates a temporary token, and signals to Commerce that the transaction was successful. +- **Merchant-hosted or _onsite_ gateways:** Payment details are sent directly to your store, and the gateway forwards them to the payment processor. These implementations have _much_ higher risk profiles and are subject to rigorous security requirements under the PCI DSS (Payment Card Industry Data Security Standard). + +Most gateways available for Commerce use a [tokenization](https://squareup.com/us/en/the-bottom-line/managing-your-finances/what-does-tokenization-actually-mean) process in the customer’s browser that (at a technical level) has a great deal in common with an _offsite_ gateway, while preserving the smooth checkout experience of an _onsite_ gateway. ## First-Party Gateway Plugins -| Plugin | Gateways | Remarks | 3D Secure Support | -| ------------------------------------------------------------------------ | --------------------------------------- | ------------------------------------------------------------------ | ------------------- | -| [Stripe](https://plugins.craftcms.com/commerce-stripe) | Stripe | Uses Stripe SDK; only first-party gateway to support subscriptions | Yes | -| [PayPal Checkout](https://plugins.craftcms.com/commerce-paypal-checkout) | PayPal Checkout | | Yes | -| [Sage Pay](https://plugins.craftcms.com/commerce-sagepay) | SagePay Direct; SagePay Server | | Yes | -| [MultiSafepay](https://plugins.craftcms.com/commerce-multisafepay) | MultiSafePay REST | Does not support authorize charges | Yes | -| [Worldpay](https://plugins.craftcms.com/commerce-worldpay) | Worldpay JSON | | No | -| [eWay](https://plugins.craftcms.com/commerce-eway) | eWAY Rapid | Supports storing payment information | Yes | -| [Mollie](https://plugins.craftcms.com/commerce-mollie) | Mollie | Does not support authorize charges | Yes | -| [PayPal](https://plugins.craftcms.com/commerce-paypal) _deprecated_ | PayPal Pro; PayPal REST; PayPal Express | PayPal REST supports storing payment information | Only PayPal Express | +| Plugin | Gateways | Remarks | 3D Secure Support | +| --- | --- | --- | --- | +| [Stripe](https://plugins.craftcms.com/commerce-stripe) | Stripe | Uses Stripe’s Payment Intents API; only first-party gateway to support subscriptions | Yes | +| [PayPal Checkout](https://plugins.craftcms.com/commerce-paypal-checkout) | PayPal Checkout | | Yes | +| [Sage Pay](https://plugins.craftcms.com/commerce-sagepay) | SagePay Direct; SagePay Server | | Yes | +| [MultiSafepay](https://plugins.craftcms.com/commerce-multisafepay) | MultiSafePay REST | Does not support authorize charges | Yes | +| [Worldpay](https://plugins.craftcms.com/commerce-worldpay) | Worldpay JSON | | No | +| [eWay](https://plugins.craftcms.com/commerce-eway) | eWAY Rapid | Supports storing payment information | Yes | +| [Mollie](https://plugins.craftcms.com/commerce-mollie) | Mollie | Does not support authorize charges | Yes | +| [PayPal](https://plugins.craftcms.com/commerce-paypal) _deprecated_ | PayPal Pro; PayPal REST; PayPal Express | PayPal REST supports storing payment information | Only PayPal Express | + +Additional third-party gateways can be found in the [Plugin Store](https://plugins.craftcms.com/categories/ecommerce?craft4). + +Before using a plugin-provided gateway, consult the its readme for specifics. Gateways themselves do not implement the logic to process payments against financial institutions, and therefore have external dependencies and fees. -## Dummy Gateway +## Built-in Gateways -After installation, Craft Commerce will install some demo products and a basic config along with a Dummy payment gateway for testing. +### Dummy Gateway -This dummy gateway driver is only for testing with placeholder credit card numbers. A valid card number ending in an even digit will get a successful response. If the last digit is an odd number, the driver will return a generic failure response: +The _Dummy_ gateway is only for testing with placeholder credit card numbers. A “valid” card number (passing a simple [Luhn](https://en.wikipedia.org/wiki/Luhn_algorithm) check) ending in an _even_ digit will simulate a successful payment. If the last digit is _odd_, the gateway will treat it as a failed payment: Example Card Number | Dummy Gateway Response ------------------- | ---------------------- -4242424242424242 | Success -4444333322221111 | Failure +4242424242424242 | Success +4444333322221111 | Failure -## Manual Gateway +::: danger +**Do not** use real credit card information when testing, as it may be captured as plain text in logs or caches. +::: -The manual payment gateway is a special gateway that does not communicate with any third party. +### Manual Gateway -You should use the manual payment gateway to accept checks or bank deposits: it simply authorizes all payments allowing the order to proceed. Once the payment is received, the payment can be manually marked as captured in the control panel. +The _Manual_ payment gateway does not communicate with any third party, nor accept any additional data during checkout. -## Other Gateway Specifics +You should use the Manual payment gateway to accept checks, bank deposits, or other offline payment: it “authorizes” all payments, allowing the order to be submitted into the default order status. Once the payment is received, the payment can be manually marked as “captured” in the control panel by an administrator. -Before using a plugin-provided gateway, consult the plugin’s readme for specifics pertaining to the gateway. +Multiple manual gateways can be created to track different kinds of offline payments, like _Cash_ or _Check_. Each gateway can also be made available to customers only when their order total is zero—perfect for things like free sample packs or event tickets. ## Adding Gateways -Additional payment gateways can be added to Commerce with relatively little work. The [first-party gateway plugins](#first-party-gateway-plugins), with the exception of Stripe, use the [Omnipay payment library](https://github.com/craftcms/commerce-omnipay) and can be used as point of reference when creating your own. +Additional payment gateways can be added to Commerce with relatively little work. All our [first-party gateway plugins](#first-party-gateway-plugins) (with the exception of Stripe) use the [Omnipay library](https://github.com/craftcms/commerce-omnipay) and can be used as a point of reference when creating your own. -See the _Extending Commerce_ section’s [Payment Gateway Types](extend/payment-gateway-types.md) page to learn about building your own gateway plugin or module. +See the _Extending Commerce_ section’s [Payment Gateway Types](extend/payment-gateway-types.md) page to learn about building your own gateway in a plugin or module. ## Storing Config Outside of the Database When you’re configuring gateways in the Craft control panel, we recommend using [environment variables](/4.x/config/#control-panel-settings) so environment-specific settings and sensitive API keys don’t end up in the database or project config. -If you must override gateway settings, you can still do that using a standard config file for your gateway plugin (i.e. `config/commerce-stripe.php`)—but be aware that you’ll only be able to provide one set of settings for that gateway. +Gateways may expose options via their plugin settings file (i.e. `config/commerce-stripe.php`), but they will apply to _all_ instances of that gateway. ## Payment Sources -Craft Commerce supports storing payment sources for select gateways. Storing a payment source allows for a more streamlined shopping experience for your customers. +Some gateways support storing and reusing payment sources for a more streamlined customer experience. This is typically a limitation of the payment processor’s API—Commerce itself makes the functionality available to all gateway plugins. The following [first-party provided gateways](#first-party-gateway-plugins) support payment sources: - Stripe -- PayPal REST +- PayPal REST (Deprecated) - eWAY Rapid ## 3D Secure Payments -3D Secure payments add another authentication step for payments. If a payment has been completed using 3D Secure authentication, the liability for fraudulent charges is shifted from the merchant to the card issuer. -Support for this feature depends on the gateway used and its settings. +3D Secure is an important authentication step for customers in many markets. If a payment has been completed using 3D Secure authentication, the liability for fraudulent charges is shifted from the merchant to the card issuer. Support for this feature depends on the gateway used and its settings. + +Transactions that require additional offsite authorization (indicated by the processor) are typically marked as a “Redirect,” and get completed or captured after the customer is returned to the store. Each gateway handles this in a way that is specific to the payment processor’s + +::: tip +If you see payments stuck in “Redirect” status, it may be because the customer never completed an authorization challenge. Gateways can report completed-but-failed challenges back to Commerce, so that the customer may retry. +::: + +Gateways that support 3D Secure (or other asynchronous verification processes, like installment plans) may require webhooks to be configured for payments to work as expected. ## Partial Refunds -All [first-party provided gateways](#first-party-gateway-plugins) support partial refunds as of Commerce 2.0. +All [first-party provided gateways](#first-party-gateway-plugins) support partial refunds. You may only issue refunds to the original payment method used in a transaction, and up to the amount paid in that transaction. If [multiple payments](making-payments.md#checkout-with-partial-payment) were made, you must refund them separately. ## Templating -### craft.commerce.gateways.getAllCustomerEnabledGateways +### craft.commerce.gateways.getAllCustomerEnabledGateways() Returns all payment gateways available to the customer. diff --git a/docs/commerce/4.x/products-variants.md b/docs/commerce/4.x/products-variants.md index b4757db6a..7ed1aa397 100644 --- a/docs/commerce/4.x/products-variants.md +++ b/docs/commerce/4.x/products-variants.md @@ -1,6 +1,8 @@ --- sidebarDepth: 2 +containsGeneratedContent: yes --- + # Products & Variants A _product_ is an [element](/4.x/elements.md) that describes what’s for sale. A _variant_ is the [purchasable](purchasables.md) the customer ultimately orders. @@ -209,2507 +211,5 @@ To fetch the same information with GraphQL, we could write a query like this: } ``` -## Product Query Parameters - -Product queries support the following parameters: - - - - - - - -| Param | Description -| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [after](#product-after) | Narrows the query results to only products that were posted on or after a certain date. -| [afterPopulate](#product-afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#product-andrelatedto) | Narrows the query results to only products that are related to certain other elements. -| [asArray](#product-asarray) | Causes the query to return matching products as arrays of data, rather than [Product](commerce4:craft\commerce\elements\Product) objects. -| [availableForPurchase](#product-availableforpurchase) | Narrows the query results to only products that are available for purchase. -| [before](#product-before) | Narrows the query results to only products that were posted before a certain date. -| [cache](#product-cache) | Enables query cache for this Query. -| [clearCachedResult](#product-clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [dateCreated](#product-datecreated) | Narrows the query results based on the products’ creation dates. -| [dateUpdated](#product-dateupdated) | Narrows the query results based on the products’ last-updated dates. -| [defaultHeight](#product-defaultheight) | Narrows the query results based on the products’ default variant height dimension IDs. -| [defaultLength](#product-defaultlength) | Narrows the query results based on the products’ default variant length dimension IDs. -| [defaultPrice](#product-defaultprice) | Narrows the query results based on the products’ default variant price. -| [defaultSku](#product-defaultsku) | Narrows the query results based on the default productvariants defaultSku -| [defaultWeight](#product-defaultweight) | Narrows the query results based on the products’ default variant weight dimension IDs. -| [defaultWidth](#product-defaultwidth) | Narrows the query results based on the products’ default variant width dimension IDs. -| [expiryDate](#product-expirydate) | Narrows the query results based on the products’ expiry dates. -| [fixedOrder](#product-fixedorder) | Causes the query results to be returned in the order specified by [id](#product-id). -| [hasVariant](#product-hasvariant) | Narrows the query results to only products that have certain variants. -| [id](#product-id) | Narrows the query results based on the products’ IDs. -| [ignorePlaceholders](#product-ignoreplaceholders) | Causes the query to return matching products as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#product-inreverse) | Causes the query results to be returned in reverse order. -| [limit](#product-limit) | Determines the number of products that should be returned. -| [offset](#product-offset) | Determines how many products should be skipped in the results. -| [orderBy](#product-orderby) | Determines the order that the products should be returned in. (If empty, defaults to `postDate DESC`.) -| [postDate](#product-postdate) | Narrows the query results based on the products’ post dates. -| [preferSites](#product-prefersites) | If [unique](#product-unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#product-preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [relatedTo](#product-relatedto) | Narrows the query results to only products that are related to certain other elements. -| [search](#product-search) | Narrows the query results to only products that match a search query. -| [site](#product-site) | Determines which site(s) the products should be queried in. -| [siteId](#product-siteid) | Determines which site(s) the products should be queried in, per the site’s ID. -| [siteSettingsId](#product-sitesettingsid) | Narrows the query results based on the products’ IDs in the `elements_sites` table. -| [slug](#product-slug) | Narrows the query results based on the products’ slugs. -| [status](#product-status) | Narrows the query results based on the products’ statuses. -| [title](#product-title) | Narrows the query results based on the products’ titles. -| [trashed](#product-trashed) | Narrows the query results to only products that have been soft-deleted. -| [type](#product-type) | Narrows the query results based on the products’ types. -| [typeId](#product-typeid) | Narrows the query results based on the products’ types, per the types’ IDs. -| [uid](#product-uid) | Narrows the query results based on the products’ UIDs. -| [unique](#product-unique) | Determines whether only elements with unique IDs should be returned by the query. -| [uri](#product-uri) | Narrows the query results based on the products’ URIs. -| [with](#product-with) | Causes the query to return matching products eager-loaded with related elements. - - - - - -

# after

- -Narrows the query results to only products that were posted on or after a certain date. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'2018-04-01'` | that were posted after 2018-04-01. -| a [DateTime](https://php.net/class.datetime) object | that were posted after the date represented by the object. - - - -::: code -```twig -{# Fetch products posted this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set products = craft.products() - .after(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch products posted this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$products = \craft\commerce\elements\Product::find() - ->after($firstDayOfMonth) - ->all(); -``` -::: - - -

# afterPopulate

- -Performs any post-population processing on elements. - - - - - - - - - - -

# andRelatedTo

- -Narrows the query results to only products that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all products that are related to myCategoryA and myCategoryB #} -{% set products = craft.products() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all products that are related to $myCategoryA and $myCategoryB -$products = \craft\commerce\elements\Product::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -

# asArray

- -Causes the query to return matching products as arrays of data, rather than [Product](commerce4:craft\commerce\elements\Product) objects. - - - - - -::: code -```twig -{# Fetch products as arrays #} -{% set products = craft.products() - .asArray() - .all() %} -``` - -```php -// Fetch products as arrays -$products = \craft\commerce\elements\Product::find() - ->asArray() - ->all(); -``` -::: - - -

# availableForPurchase

- -Narrows the query results to only products that are available for purchase. - - - -::: code -```twig -{# Fetch products that are available for purchase #} -{% set products = craft.products() - .availableForPurchase() - .all() %} -``` - -```php -// Fetch products that are available for purchase -$products = \craft\commerce\elements\Product::find() - ->availableForPurchase() - ->all(); -``` -::: - - -

# before

- -Narrows the query results to only products that were posted before a certain date. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'2018-04-01'` | that were posted before 2018-04-01. -| a [DateTime](https://php.net/class.datetime) object | that were posted before the date represented by the object. - - - -::: code -```twig -{# Fetch products posted before this month #} -{% set firstDayOfMonth = date('first day of this month') %} - -{% set products = craft.products() - .before(firstDayOfMonth) - .all() %} -``` - -```php -// Fetch products posted before this month -$firstDayOfMonth = new \DateTime('first day of this month'); - -$products = \craft\commerce\elements\Product::find() - ->before($firstDayOfMonth) - ->all(); -``` -::: - - -

# cache

- -Enables query cache for this Query. - - - - - - - - - - -

# clearCachedResult

- -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -

# dateCreated

- -Narrows the query results based on the products’ creation dates. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch products created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set products = craft.products() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch products created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -

# dateUpdated

- -Narrows the query results based on the products’ last-updated dates. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch products updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set products = craft.products() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch products updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -

# defaultHeight

- -Narrows the query results based on the products’ default variant height dimension IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with a dimension of 1. -| `'not 1'` | not a dimension of 1. -| `[1, 2]` | of a a dimension 1 or 2. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product default dimension of 1 #} -{% set products = craft.products() - .defaultHeight(1) - .all() %} -``` - -```php -// Fetch products of the product default dimension of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultHeight(1) - ->all(); -``` -::: - - -

# defaultLength

- -Narrows the query results based on the products’ default variant length dimension IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with a dimension of 1. -| `'not 1'` | not a dimension of 1. -| `[1, 2]` | of a a dimension 1 or 2. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product default dimension of 1 #} -{% set products = craft.products() - .defaultLength(1) - .all() %} -``` - -```php -// Fetch products of the product default dimension of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultLength(1) - ->all(); -``` -::: - - -

# defaultPrice

- -Narrows the query results based on the products’ default variant price. - -Possible values include: - -| Value | Fetches products… -| - | - -| `10` | of a price of 10. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a default variant price between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product type with an ID of 1 #} -{% set products = craft.products() - .defaultPrice(1) - .all() %} -``` - -```php -// Fetch products of the product type with an ID of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultPrice(1) - ->all(); -``` -::: - - -

# defaultSku

- -Narrows the query results based on the default productvariants defaultSku - -Possible values include: - -| Value | Fetches products… -| - | - -| `xxx-001` | of products default SKU of `xxx-001`. -| `'not xxx-001'` | not a default SKU of `xxx-001`. -| `['not xxx-001', 'not xxx-002']` | of a default SKU of xxx-001 or xxx-002. -| `['not', `xxx-001`, `xxx-002`]` | not a product default SKU of `xxx-001` or `xxx-001`. - - - -::: code -```twig -{# Fetch products of the product default SKU of `xxx-001` #} -{% set products = craft.products() - .defaultSku('xxx-001') - .all() %} -``` - -```php -// Fetch products of the product default SKU of `xxx-001` -$products = \craft\commerce\elements\Product::find() - ->defaultSku('xxx-001') - ->all(); -``` -::: - - -

# defaultWeight

- -Narrows the query results based on the products’ default variant weight dimension IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with a dimension of 1. -| `'not 1'` | not a dimension of 1. -| `[1, 2]` | of a a dimension 1 or 2. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product default dimension of 1 #} -{% set products = craft.products() - .defaultWeight(1) - .all() %} -``` - -```php -// Fetch products of the product default dimension of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultWeight(1) - ->all(); -``` -::: - - -

# defaultWidth

- -Narrows the query results based on the products’ default variant width dimension IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with a dimension of 1. -| `'not 1'` | not a dimension of 1. -| `[1, 2]` | of a a dimension 1 or 2. -| `['and', '>= ' ~ 100, '<= ' ~ 2000]` | of a dimension between 100 and 2000 - - - -::: code -```twig -{# Fetch products of the product default dimension of 1 #} -{% set products = craft.products() - .defaultWidth(1) - .all() %} -``` - -```php -// Fetch products of the product default dimension of 1 -$products = \craft\commerce\elements\Product::find() - ->defaultWidth(1) - ->all(); -``` -::: - - -

# expiryDate

- -Narrows the query results based on the products’ expiry dates. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2020-04-01'` | that will expire on or after 2020-04-01. -| `'< 2020-05-01'` | that will expire before 2020-05-01 -| `['and', '>= 2020-04-04', '< 2020-05-01']` | that will expire between 2020-04-01 and 2020-05-01. - - - -::: code -```twig -{# Fetch products expiring this month #} -{% set nextMonth = date('first day of next month')|atom %} - -{% set products = craft.products() - .expiryDate("< #{nextMonth}") - .all() %} -``` - -```php -// Fetch products expiring this month -$nextMonth = new \DateTime('first day of next month')->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->expiryDate("< {$nextMonth}") - ->all(); -``` -::: - - -

# fixedOrder

- -Causes the query results to be returned in the order specified by [id](#product-id). - - - -::: tip -If no IDs were passed to [id](#product-id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch products in a specific order #} -{% set products = craft.products() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch products in a specific order -$products = \craft\commerce\elements\Product::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -

# hasVariant

- -Narrows the query results to only products that have certain variants. - -Possible values include: - -| Value | Fetches products… -| - | - -| a [VariantQuery](commerce4:craft\commerce\elements\db\VariantQuery) object | with variants that match the query. - - - - -

# id

- -Narrows the query results based on the products’ IDs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the product by its ID #} -{% set product = craft.products() - .id(1) - .one() %} -``` - -```php -// Fetch the product by its ID -$product = \craft\commerce\elements\Product::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#product-fixedorder) if you want the results to be returned in a specific order. -::: - - -

# ignorePlaceholders

- -Causes the query to return matching products as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -

# inReverse

- -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch products in reverse #} -{% set products = craft.products() - .inReverse() - .all() %} -``` - -```php -// Fetch products in reverse -$products = \craft\commerce\elements\Product::find() - ->inReverse() - ->all(); -``` -::: - - -

# limit

- -Determines the number of products that should be returned. - - - -::: code -```twig -{# Fetch up to 10 products #} -{% set products = craft.products() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 products -$products = \craft\commerce\elements\Product::find() - ->limit(10) - ->all(); -``` -::: - - -

# offset

- -Determines how many products should be skipped in the results. - - - -::: code -```twig -{# Fetch all products except for the first 3 #} -{% set products = craft.products() - .offset(3) - .all() %} -``` - -```php -// Fetch all products except for the first 3 -$products = \craft\commerce\elements\Product::find() - ->offset(3) - ->all(); -``` -::: - - -

# orderBy

- -Determines the order that the products should be returned in. (If empty, defaults to `postDate DESC`.) - - - -::: code -```twig -{# Fetch all products in order of date created #} -{% set products = craft.products() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all products in order of date created -$products = \craft\commerce\elements\Product::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -

# postDate

- -Narrows the query results based on the products’ post dates. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'>= 2018-04-01'` | that were posted on or after 2018-04-01. -| `'< 2018-05-01'` | that were posted before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were posted between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch products posted last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set products = craft.products() - .postDate(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch products posted last month -$start = new \DateTime('first day of next month')->format(\DateTime::ATOM); -$end = new \DateTime('first day of this month')->format(\DateTime::ATOM); - -$products = \craft\commerce\elements\Product::find() - ->postDate(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -

# preferSites

- -If [unique](#product-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique products from Site A, or Site B if they don’t exist in Site A #} -{% set products = craft.products() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique products from Site A, or Site B if they don’t exist in Site A -$products = \craft\commerce\elements\Product::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -

# prepareSubquery

- -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -

# relatedTo

- -Narrows the query results to only products that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all products that are related to myCategory #} -{% set products = craft.products() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all products that are related to $myCategory -$products = \craft\commerce\elements\Product::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - - - -Narrows the query results to only products that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all products that match the search query #} -{% set products = craft.products() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all products that match the search query -$products = \craft\commerce\elements\Product::find() - ->search($searchQuery) - ->all(); -``` -::: - - -

# site

- -Determines which site(s) the products should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](https://docs.craftcms.com/api/v4/craft-models-site.html) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#product-unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch products from the Foo site #} -{% set products = craft.products() - .site('foo') - .all() %} -``` - -```php -// Fetch products from the Foo site -$products = \craft\commerce\elements\Product::find() - ->site('foo') - ->all(); -``` -::: - - -

# siteId

- -Determines which site(s) the products should be queried in, per the site’s ID. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | from the site with an ID of `1`. -| `[1, 2]` | from a site with an ID of `1` or `2`. -| `['not', 1, 2]` | not in a site with an ID of `1` or `2`. -| `'*'` | from any site. - - - -::: code -```twig -{# Fetch products from the site with an ID of 1 #} -{% set products = craft.products() - .siteId(1) - .all() %} -``` - -```php -// Fetch products from the site with an ID of 1 -$products = \craft\commerce\elements\Product::find() - ->siteId(1) - ->all(); -``` -::: - - -

# siteSettingsId

- -Narrows the query results based on the products’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the product by its ID in the elements_sites table #} -{% set product = craft.products() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the product by its ID in the elements_sites table -$product = \craft\commerce\elements\Product::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -

# slug

- -Narrows the query results based on the products’ slugs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | with a slug of `foo`. -| `'foo*'` | with a slug that begins with `foo`. -| `'*foo'` | with a slug that ends with `foo`. -| `'*foo*'` | with a slug that contains `foo`. -| `'not *foo*'` | with a slug that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a slug that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a slug that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested product slug from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the product with that slug #} -{% set product = craft.products() - .slug(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested product slug from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the product with that slug -$product = \craft\commerce\elements\Product::find() - ->slug(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -

# status

- -Narrows the query results based on the products’ statuses. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'live'` _(default)_ | that are live. -| `'pending'` | that are pending (enabled with a Post Date in the future). -| `'expired'` | that are expired (enabled with an Expiry Date in the past). -| `'disabled'` | that are disabled. -| `['live', 'pending']` | that are live or pending. - - - -::: code -```twig -{# Fetch disabled products #} -{% set products = craft.products() - .status('disabled') - .all() %} -``` - -```php -// Fetch disabled products -$products = \craft\commerce\elements\Product::find() - ->status('disabled') - ->all(); -``` -::: - - -

# title

- -Narrows the query results based on the products’ titles. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch products with a title that contains "Foo" #} -{% set products = craft.products() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch products with a title that contains "Foo" -$products = \craft\commerce\elements\Product::find() - ->title('*Foo*') - ->all(); -``` -::: - - -

# trashed

- -Narrows the query results to only products that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed products #} -{% set products = craft.products() - .trashed() - .all() %} -``` - -```php -// Fetch trashed products -$products = \craft\commerce\elements\Product::find() - ->trashed() - ->all(); -``` -::: - - -

# type

- -Narrows the query results based on the products’ types. - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | of a type with a handle of `foo`. -| `'not foo'` | not of a type with a handle of `foo`. -| `['foo', 'bar']` | of a type with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not of a type with a handle of `foo` or `bar`. -| an [ProductType](commerce4:craft\commerce\models\ProductType) object | of a type represented by the object. - - - -::: code -```twig -{# Fetch products with a Foo product type #} -{% set products = craft.products() - .type('foo') - .all() %} -``` - -```php -// Fetch products with a Foo product type -$products = \craft\commerce\elements\Product::find() - ->type('foo') - ->all(); -``` -::: - - -

# typeId

- -Narrows the query results based on the products’ types, per the types’ IDs. - -Possible values include: - -| Value | Fetches products… -| - | - -| `1` | of a type with an ID of 1. -| `'not 1'` | not of a type with an ID of 1. -| `[1, 2]` | of a type with an ID of 1 or 2. -| `['not', 1, 2]` | not of a type with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch products of the product type with an ID of 1 #} -{% set products = craft.products() - .typeId(1) - .all() %} -``` - -```php -// Fetch products of the product type with an ID of 1 -$products = \craft\commerce\elements\Product::find() - ->typeId(1) - ->all(); -``` -::: - - -

# uid

- -Narrows the query results based on the products’ UIDs. - - - - - -::: code -```twig -{# Fetch the product by its UID #} -{% set product = craft.products() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the product by its UID -$product = \craft\commerce\elements\Product::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -

# unique

- -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique products across all sites #} -{% set products = craft.products() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique products across all sites -$products = \craft\commerce\elements\Product::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -

# uri

- -Narrows the query results based on the products’ URIs. - - - -Possible values include: - -| Value | Fetches products… -| - | - -| `'foo'` | with a URI of `foo`. -| `'foo*'` | with a URI that begins with `foo`. -| `'*foo'` | with a URI that ends with `foo`. -| `'*foo*'` | with a URI that contains `foo`. -| `'not *foo*'` | with a URI that doesn’t contain `foo`. -| `['*foo*', '*bar*']` | with a URI that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a URI that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested URI #} -{% set requestedUri = craft.app.request.getPathInfo() %} - -{# Fetch the product with that URI #} -{% set product = craft.products() - .uri(requestedUri|literal) - .one() %} -``` - -```php -// Get the requested URI -$requestedUri = \Craft::$app->request->getPathInfo(); - -// Fetch the product with that URI -$product = \craft\commerce\elements\Product::find() - ->uri(\craft\helpers\Db::escapeParam($requestedUri)) - ->one(); -``` -::: - - -

# with

- -Causes the query to return matching products eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch products eager-loaded with the "Related" field’s relations #} -{% set products = craft.products() - .with(['related']) - .all() %} -``` - -```php -// Fetch products eager-loaded with the "Related" field’s relations -$products = \craft\commerce\elements\Product::find() - ->with(['related']) - ->all(); -``` -::: - - - - - -## Variants - -A variant describes the individual properties of a product as an item that may be purchased. - -Those properties inclue a SKU, price, and dimensions. Even if a product doesn’t appear to have any variants in the control panel, it still uses one *default variant* behind the scenes. - -Let’s compare examples of a single-variant an multi-variant product: a paperback book and a t-shirt. - -A book sold in only one format does not have meaningful variations for the customer to choose, but it would still have a specific SKU, price, weight, and dimensions. A single, implicit default variant needs to exist and that’s what would be added to the cart. - -A t-shirt, on the other hand, would have at least one variant for each available color and size combination. You wouldn’t sell the t-shirt without a specific color and size, so multiple variants would be necessary. If the shirt came in “small” and “large” sizes and “red” or “blue” colors, four unique variants could exist: - -- small, red -- small, blue -- large, red -- large, blue - -### Variant Properties - -Each variant includes the following unique properties: - -| Property | Type | Required? | -| ------------- | ------------------- | -------------- | -| SKU | string | | -| Price | number | | -| Stock | number or unlimited | | -| Allowed Qty | range | | -| Dimensions | number (l × w × h) | | -| Weight | number | | -| Related Sales | relationship (Sale) | | - -Each variant may also have any number of custom fields to allow other distinguishing traits. - -Commerce does not automatically create every possible unique variant for you—that’s up to the store manager. - -### Default Variant - -Every product has a default variant. Whenever a product is created, a default variant will be created as well. - -If a product type has multiple variants enabled, the author can choose which one should be used by default. Products that do not have multiple variants still have a default variant, but the author can’t add additional variants. - -For a single-variant product, variant details are shown in a unified view with custom product fields: - -![Stylized illustration of a single-variant product edit page, with custom product fields in a single content pane and fields like SKU in the sidebar details](./images/single-variant.png) - -When a product supports multiple variants, the default variant will be identified in a **Variants** field where more variants can be added: - -![Stylized illustration of a multi-variant product edit page, with an additional “Variants” tab that has a Matrix-like editor for multiple variants each having their own fields like SKU](./images/multi-variant.png) - -### Variant Stock - -Variants can have unlimited stock or a specific quantity. - -A finite stock amount will automatically be reduced whenever someone completes an order, until the stock amount reaches zero. At that point the variant’s “Available for purchase” setting won’t be changed, but zero-stock variants cannot be added to a cart. - -For returns or refunds that aren’t ultimately delivered to the customer, you’ll need to either manually update product stock or use [the `orderStatusChange` event](extend/events.md#orderstatuschange) to automate further stock adjustments. - -## Querying Variants - -You can fetch variants using **variant queries**. - -::: code -```twig -{# Create a new variant query #} -{% set myVariantQuery = craft.variants() %} -``` -```php -// Create a new variant query -$myVariantQuery = \craft\commerce\elements\Variant::find(); -``` -```graphql -# Create a new variant query -{ - variants { - # ... - } -} -``` -::: - -Once you’ve created a variant query, you can set [parameters](#variant-query-parameters) on it to narrow down the results, and then [execute it](https://craftcms.com/docs/4.x/element-queries.html#executing-element-queries) by calling `.all()`. An array of [Variant](commerce4:craft\commerce\elements\Variant) objects will be returned. - -You can also fetch only the number of items a query might return, which is better for performance when you don’t need the variant data. - -::: code -```twig -{# Count all enabled variants #} -{% set myVariantCount = craft.variants() - .status('enabled') - .count() %} -``` -```php -use craft\commerce\elements\Variant; - -// Count all enabled variants -$myVariantCount = Variant::find() - ->status(Variant::STATUS_ENABLED) - ->count(); -``` -```graphql -# Count all enabled variants -{ - variantCount(status: "enabled") -} -``` -::: - -::: tip -See [Element Queries](https://craftcms.com/docs/4.x/element-queries.html) in the Craft docs to learn about how element queries work. -::: - -### Example - -We can display a specific variant by its ID in Twig by doing the following: - -1. Create a variant query with `craft.variants()`. -2. Set the [`id`](#id) parameter on it. -3. Fetch the variant with `.one()`. -4. Output information about the variant as HTML. - -```twig -{# Get the requested variant ID from the query string #} -{% set variantId = craft.app.request.getQueryParam('id') %} - -{# Create a variant query with the 'id' parameter #} -{% set myVariantQuery = craft.variants() - .id(variantId) %} - -{# Fetch the variant #} -{% set variant = myVariantQuery.one() %} - -{# Make sure it exists #} -{% if not variant %} - {% exit 404 %} -{% endif %} - -{# Display the variant #} -

{{ variant.title }}

- -``` - -Fetching the equivalent with GraphQL could look like this: - -```graphql -# Fetch variant having ID = 46 -{ - variants(id: 46) { - title - } -} -``` - -## Variant Query Parameters - -Variant queries support the following parameters: - - - - - - - -| Param | Description -| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#variant-afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#variant-andrelatedto) | Narrows the query results to only variants that are related to certain other elements. -| [asArray](#variant-asarray) | Causes the query to return matching variants as arrays of data, rather than [Variant](commerce4:craft\commerce\elements\Variant) objects. -| [cache](#variant-cache) | Enables query cache for this Query. -| [clearCachedResult](#variant-clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [dateCreated](#variant-datecreated) | Narrows the query results based on the variants’ creation dates. -| [dateUpdated](#variant-dateupdated) | Narrows the query results based on the variants’ last-updated dates. -| [fixedOrder](#variant-fixedorder) | Causes the query results to be returned in the order specified by [id](#variant-id). -| [hasProduct](#variant-hasproduct) | Narrows the query results to only variants for certain products. -| [hasSales](#variant-hassales) | Narrows the query results to only variants that are on sale. -| [hasStock](#variant-hasstock) | Narrows the query results to only variants that have stock. -| [hasUnlimitedStock](#variant-hasunlimitedstock) | Narrows the query results to only variants that have been set to unlimited stock. -| [height](#variant-height) | Narrows the query results based on the variants’ height dimension. -| [id](#variant-id) | Narrows the query results based on the variants’ IDs. -| [ignorePlaceholders](#variant-ignoreplaceholders) | Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#variant-inreverse) | Causes the query results to be returned in reverse order. -| [isDefault](#variant-isdefault) | Narrows the query results to only default variants. -| [length](#variant-length) | Narrows the query results based on the variants’ length dimension. -| [limit](#variant-limit) | Determines the number of variants that should be returned. -| [maxQty](#variant-maxqty) | Narrows the query results based on the variants’ max quantity. -| [minQty](#variant-minqty) | Narrows the query results based on the variants’ min quantity. -| [offset](#variant-offset) | Determines how many variants should be skipped in the results. -| [orderBy](#variant-orderby) | Determines the order that the variants should be returned in. (If empty, defaults to `sortOrder ASC`.) -| [preferSites](#variant-prefersites) | If [unique](#variant-unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#variant-preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [price](#variant-price) | Narrows the query results based on the variants’ price. -| [product](#variant-product) | Narrows the query results based on the variants’ product. -| [productId](#variant-productid) | Narrows the query results based on the variants’ products’ IDs. -| [relatedTo](#variant-relatedto) | Narrows the query results to only variants that are related to certain other elements. -| [search](#variant-search) | Narrows the query results to only variants that match a search query. -| [site](#variant-site) | Determines which site(s) the variants should be queried in. -| [siteId](#variant-siteid) | -| [siteSettingsId](#variant-sitesettingsid) | Narrows the query results based on the variants’ IDs in the `elements_sites` table. -| [sku](#variant-sku) | Narrows the query results based on the variants’ SKUs. -| [status](#variant-status) | -| [stock](#variant-stock) | Narrows the query results based on the variants’ stock. -| [title](#variant-title) | Narrows the query results based on the variants’ titles. -| [trashed](#variant-trashed) | Narrows the query results to only variants that have been soft-deleted. -| [typeId](#variant-typeid) | Narrows the query results based on the variants’ product types, per their IDs. -| [uid](#variant-uid) | Narrows the query results based on the variants’ UIDs. -| [unique](#variant-unique) | Determines whether only elements with unique IDs should be returned by the query. -| [weight](#variant-weight) | Narrows the query results based on the variants’ weight dimension. -| [width](#variant-width) | Narrows the query results based on the variants’ width dimension. -| [with](#variant-with) | Causes the query to return matching variants eager-loaded with related elements. - - - - - -

# afterPopulate

- -Performs any post-population processing on elements. - - - - - - - - - - -

# andRelatedTo

- -Narrows the query results to only variants that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all variants that are related to myCategoryA and myCategoryB #} -{% set variants = craft.variants() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all variants that are related to $myCategoryA and $myCategoryB -$variants = \craft\commerce\elements\Variant::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -

# asArray

- -Causes the query to return matching variants as arrays of data, rather than [Variant](commerce4:craft\commerce\elements\Variant) objects. - - - - - -::: code -```twig -{# Fetch variants as arrays #} -{% set variants = craft.variants() - .asArray() - .all() %} -``` - -```php -// Fetch variants as arrays -$variants = \craft\commerce\elements\Variant::find() - ->asArray() - ->all(); -``` -::: - - -

# cache

- -Enables query cache for this Query. - - - - - - - - - - -

# clearCachedResult

- -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -

# dateCreated

- -Narrows the query results based on the variants’ creation dates. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch variants created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set variants = craft.variants() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch variants created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$variants = \craft\commerce\elements\Variant::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -

# dateUpdated

- -Narrows the query results based on the variants’ last-updated dates. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch variants updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set variants = craft.variants() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch variants updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$variants = \craft\commerce\elements\Variant::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -

# fixedOrder

- -Causes the query results to be returned in the order specified by [id](#variant-id). - - - -::: tip -If no IDs were passed to [id](#variant-id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch variants in a specific order #} -{% set variants = craft.variants() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch variants in a specific order -$variants = \craft\commerce\elements\Variant::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -

# hasProduct

- -Narrows the query results to only variants for certain products. - -Possible values include: - -| Value | Fetches variants… -| - | - -| a [ProductQuery](commerce4:craft\commerce\elements\db\ProductQuery) object | for products that match the query. - - - - -

# hasSales

- -Narrows the query results to only variants that are on sale. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `true` | on sale -| `false` | not on sale - - - - -

# hasStock

- -Narrows the query results to only variants that have stock. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `true` | with stock. -| `false` | with no stock. - - - - -

# hasUnlimitedStock

- -Narrows the query results to only variants that have been set to unlimited stock. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `true` | with unlimited stock checked. -| `false` | with unlimited stock not checked. - - - - -

# height

- -Narrows the query results based on the variants’ height dimension. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a height of 100. -| `'>= 100'` | with a height of at least 100. -| `'< 100'` | with a height of less than 100. - - - - -

# id

- -Narrows the query results based on the variants’ IDs. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the variant by its ID #} -{% set variant = craft.variants() - .id(1) - .one() %} -``` - -```php -// Fetch the variant by its ID -$variant = \craft\commerce\elements\Variant::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#variant-fixedorder) if you want the results to be returned in a specific order. -::: - - -

# ignorePlaceholders

- -Causes the query to return matching variants as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -

# inReverse

- -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch variants in reverse #} -{% set variants = craft.variants() - .inReverse() - .all() %} -``` - -```php -// Fetch variants in reverse -$variants = \craft\commerce\elements\Variant::find() - ->inReverse() - ->all(); -``` -::: - - -

# isDefault

- -Narrows the query results to only default variants. - - - -::: code -```twig -{# Fetch default variants #} -{% set variants = craft.variants() - .isDefault() - .all() %} -``` - -```php -// Fetch default variants -$variants = \craft\commerce\elements\Variant::find() - ->isDefault() - ->all(); -``` -::: - - -

# length

- -Narrows the query results based on the variants’ length dimension. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a length of 100. -| `'>= 100'` | with a length of at least 100. -| `'< 100'` | with a length of less than 100. - - - - -

# limit

- -Determines the number of variants that should be returned. - - - -::: code -```twig -{# Fetch up to 10 variants #} -{% set variants = craft.variants() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 variants -$variants = \craft\commerce\elements\Variant::find() - ->limit(10) - ->all(); -``` -::: - - -

# maxQty

- -Narrows the query results based on the variants’ max quantity. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a maxQty of 100. -| `'>= 100'` | with a maxQty of at least 100. -| `'< 100'` | with a maxQty of less than 100. - - - - -

# minQty

- -Narrows the query results based on the variants’ min quantity. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a minQty of 100. -| `'>= 100'` | with a minQty of at least 100. -| `'< 100'` | with a minQty of less than 100. - - - - -

# offset

- -Determines how many variants should be skipped in the results. - - - -::: code -```twig -{# Fetch all variants except for the first 3 #} -{% set variants = craft.variants() - .offset(3) - .all() %} -``` - -```php -// Fetch all variants except for the first 3 -$variants = \craft\commerce\elements\Variant::find() - ->offset(3) - ->all(); -``` -::: - - -

# orderBy

- -Determines the order that the variants should be returned in. (If empty, defaults to `sortOrder ASC`.) - - - -::: code -```twig -{# Fetch all variants in order of date created #} -{% set variants = craft.variants() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all variants in order of date created -$variants = \craft\commerce\elements\Variant::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -

# preferSites

- -If [unique](#variant-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique variants from Site A, or Site B if they don’t exist in Site A #} -{% set variants = craft.variants() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique variants from Site A, or Site B if they don’t exist in Site A -$variants = \craft\commerce\elements\Variant::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -

# prepareSubquery

- -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -

# price

- -Narrows the query results based on the variants’ price. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a price of 100. -| `'>= 100'` | with a price of at least 100. -| `'< 100'` | with a price of less than 100. - - - - -

# product

- -Narrows the query results based on the variants’ product. - -Possible values include: - -| Value | Fetches variants… -| - | - -| a [Product](commerce4:craft\commerce\elements\Product) object | for a product represented by the object. - - - - -

# productId

- -Narrows the query results based on the variants’ products’ IDs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | for a product with an ID of 1. -| `[1, 2]` | for product with an ID of 1 or 2. -| `['not', 1, 2]` | for product not with an ID of 1 or 2. - - - - -

# relatedTo

- -Narrows the query results to only variants that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all variants that are related to myCategory #} -{% set variants = craft.variants() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all variants that are related to $myCategory -$variants = \craft\commerce\elements\Variant::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - - - -Narrows the query results to only variants that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all variants that match the search query #} -{% set variants = craft.variants() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all variants that match the search query -$variants = \craft\commerce\elements\Variant::find() - ->search($searchQuery) - ->all(); -``` -::: - - -

# site

- -Determines which site(s) the variants should be queried in. - - - -The current site will be used by default. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'foo'` | from the site with a handle of `foo`. -| `['foo', 'bar']` | from a site with a handle of `foo` or `bar`. -| `['not', 'foo', 'bar']` | not in a site with a handle of `foo` or `bar`. -| a [craft\models\Site](https://docs.craftcms.com/api/v4/craft-models-site.html) object | from the site represented by the object. -| `'*'` | from any site. - -::: tip -If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you -only want unique elements to be returned, use [unique](#variant-unique) in conjunction with this. -::: - - - -::: code -```twig -{# Fetch variants from the Foo site #} -{% set variants = craft.variants() - .site('foo') - .all() %} -``` - -```php -// Fetch variants from the Foo site -$variants = \craft\commerce\elements\Variant::find() - ->site('foo') - ->all(); -``` -::: - - -

# siteId

- - - - - - - - -

# siteSettingsId

- -Narrows the query results based on the variants’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the variant by its ID in the elements_sites table #} -{% set variant = craft.variants() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the variant by its ID in the elements_sites table -$variant = \craft\commerce\elements\Variant::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -

# sku

- -Narrows the query results based on the variants’ SKUs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'foo'` | with a SKU of `foo`. -| `'foo*'` | with a SKU that begins with `foo`. -| `'*foo'` | with a SKU that ends with `foo`. -| `'*foo*'` | with a SKU that contains `foo`. -| `'not *foo*'` | with a SKU that doesn’t contain `foo`. -| `['*foo*', '*bar*'` | with a SKU that contains `foo` or `bar`. -| `['not', '*foo*', '*bar*']` | with a SKU that doesn’t contain `foo` or `bar`. - - - -::: code -```twig -{# Get the requested variant SKU from the URL #} -{% set requestedSlug = craft.app.request.getSegment(3) %} - -{# Fetch the variant with that slug #} -{% set variant = craft.variants() - .sku(requestedSlug|literal) - .one() %} -``` - -```php -// Get the requested variant SKU from the URL -$requestedSlug = \Craft::$app->request->getSegment(3); - -// Fetch the variant with that slug -$variant = \craft\commerce\elements\Variant::find() - ->sku(\craft\helpers\Db::escapeParam($requestedSlug)) - ->one(); -``` -::: - - -

# status

- - - - - - - - -

# stock

- -Narrows the query results based on the variants’ stock. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `0` | with no stock. -| `'>= 5'` | with a stock of at least 5. -| `'< 10'` | with a stock of less than 10. - - - - -

# title

- -Narrows the query results based on the variants’ titles. - - - -Possible values include: - -| Value | Fetches variants… -| - | - -| `'Foo'` | with a title of `Foo`. -| `'Foo*'` | with a title that begins with `Foo`. -| `'*Foo'` | with a title that ends with `Foo`. -| `'*Foo*'` | with a title that contains `Foo`. -| `'not *Foo*'` | with a title that doesn’t contain `Foo`. -| `['*Foo*', '*Bar*']` | with a title that contains `Foo` or `Bar`. -| `['not', '*Foo*', '*Bar*']` | with a title that doesn’t contain `Foo` or `Bar`. - - - -::: code -```twig -{# Fetch variants with a title that contains "Foo" #} -{% set variants = craft.variants() - .title('*Foo*') - .all() %} -``` - -```php -// Fetch variants with a title that contains "Foo" -$variants = \craft\commerce\elements\Variant::find() - ->title('*Foo*') - ->all(); -``` -::: - - -

# trashed

- -Narrows the query results to only variants that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed variants #} -{% set variants = craft.variants() - .trashed() - .all() %} -``` - -```php -// Fetch trashed variants -$variants = \craft\commerce\elements\Variant::find() - ->trashed() - ->all(); -``` -::: - - -

# typeId

- -Narrows the query results based on the variants’ product types, per their IDs. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `1` | for a product of a type with an ID of 1. -| `[1, 2]` | for product of a type with an ID of 1 or 2. -| `['not', 1, 2]` | for product of a type not with an ID of 1 or 2. - - - - -

# uid

- -Narrows the query results based on the variants’ UIDs. - - - - - -::: code -```twig -{# Fetch the variant by its UID #} -{% set variant = craft.variants() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the variant by its UID -$variant = \craft\commerce\elements\Variant::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -

# unique

- -Determines whether only elements with unique IDs should be returned by the query. - - - -This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not -desired. - - - -::: code -```twig -{# Fetch unique variants across all sites #} -{% set variants = craft.variants() - .site('*') - .unique() - .all() %} -``` - -```php -// Fetch unique variants across all sites -$variants = \craft\commerce\elements\Variant::find() - ->site('*') - ->unique() - ->all(); -``` -::: - - -

# weight

- -Narrows the query results based on the variants’ weight dimension. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a weight of 100. -| `'>= 100'` | with a weight of at least 100. -| `'< 100'` | with a weight of less than 100. - - - - -

# width

- -Narrows the query results based on the variants’ width dimension. - -Possible values include: - -| Value | Fetches variants… -| - | - -| `100` | with a width of 100. -| `'>= 100'` | with a width of at least 100. -| `'< 100'` | with a width of less than 100. - - - - -

# with

- -Causes the query to return matching variants eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch variants eager-loaded with the "Related" field’s relations #} -{% set variants = craft.variants() - .with(['related']) - .all() %} -``` - -```php -// Fetch variants eager-loaded with the "Related" field’s relations -$variants = \craft\commerce\elements\Variant::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/commerce/4.x/products-variants.md)!!! diff --git a/docs/commerce/4.x/sales.md b/docs/commerce/4.x/sales.md index 09a13b1cd..78fb23fc1 100644 --- a/docs/commerce/4.x/sales.md +++ b/docs/commerce/4.x/sales.md @@ -8,6 +8,12 @@ An item in the store would typically be listed by its sale price. If no sales ap Sales are ordered in the control panel, and the system always runs through each sale in order when determining the `salePrice` of the purchasable. +## Matching Items + +Controls that determine what purchasables match a sale are identical to those for [discounts](discounts.md). + + + ## Conditions When creating a sale, you can set a number of conditions to be evaluated when determining if the sale should be applied to the purchasable. All conditions must match to have the sale applied. Leaving a condition empty ignores that condition. @@ -28,30 +34,6 @@ When the sale stops being applied to matching products. Whether the cart’s customer belongs to one of the matching user groups. -### Variant - -Whether the purchasable being matched is one of the selected variants. - -### Category - -Whether the purchasable being matched is related to the selected category. - -For example, you might have a category of products in the “Womens Sport” department category, and this allows you to put all products in that category on sale. - -For variants, the category can be related to either the product or the variant to match this condition. - -Each custom purchasable can decide to determine how it considers the selected category. - -### Category Relationship Type - -This field specifies the type of relationship must exist between the purchasable and category in order for the condition to be met. There are three options available “Source”, “Target” and “Both”: - -- **Source**: the relational field exists on the product/purchasable. -- **Target**: the category has a product/variant relational field. -- **Both**: the relationship can be either **Source** or **Target** - -For more information on how this works, see [Relations Terminology](/4.x/relations.md#terminology). - ### Other Purchasables Any other custom purchasable a third party system adds to Commerce can show up here as a condition. diff --git a/docs/commerce/4.x/subscriptions.md b/docs/commerce/4.x/subscriptions.md index b723d28f9..afbcdf184 100644 --- a/docs/commerce/4.x/subscriptions.md +++ b/docs/commerce/4.x/subscriptions.md @@ -1,3 +1,7 @@ +--- +containsGeneratedContent: yes +--- + # Subscriptions Subscriptions are handled by gateways. A payment gateway must handle subscription plan support in order to establish a Commerce subscription for a user. @@ -98,1063 +102,5 @@ We can display all of the current user’s subscriptions by doing the following: Subscription queries support the following parameters: - - - - - - -| Param | Description -| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -| [afterPopulate](#afterpopulate) | Performs any post-population processing on elements. -| [andRelatedTo](#andrelatedto) | Narrows the query results to only subscriptions that are related to certain other elements. -| [asArray](#asarray) | Causes the query to return matching subscriptions as arrays of data, rather than [Subscription](commerce4:craft\commerce\elements\Subscription) objects. -| [cache](#cache) | Enables query cache for this Query. -| [clearCachedResult](#clearcachedresult) | Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). -| [dateCanceled](#datecanceled) | Narrows the query results based on the subscriptions’ cancellation date. -| [dateCreated](#datecreated) | Narrows the query results based on the subscriptions’ creation dates. -| [dateExpired](#dateexpired) | Narrows the query results based on the subscriptions’ expiration date. -| [dateSuspended](#datesuspended) | Narrows the query results based on the subscriptions’ suspension date. -| [dateUpdated](#dateupdated) | Narrows the query results based on the subscriptions’ last-updated dates. -| [fixedOrder](#fixedorder) | Causes the query results to be returned in the order specified by [id](#id). -| [gatewayId](#gatewayid) | Narrows the query results based on the gateway, per its ID. -| [hasStarted](#hasstarted) | Narrows the query results to only subscriptions that have started. -| [id](#id) | Narrows the query results based on the subscriptions’ IDs. -| [ignorePlaceholders](#ignoreplaceholders) | Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). -| [inReverse](#inreverse) | Causes the query results to be returned in reverse order. -| [isCanceled](#iscanceled) | Narrows the query results to only subscriptions that are canceled. -| [isExpired](#isexpired) | Narrows the query results to only subscriptions that have expired. -| [isSuspended](#issuspended) | Narrows the query results to only subscriptions that are suspended. -| [limit](#limit) | Determines the number of subscriptions that should be returned. -| [nextPaymentDate](#nextpaymentdate) | Narrows the query results based on the subscriptions’ next payment dates. -| [offset](#offset) | Determines how many subscriptions should be skipped in the results. -| [onTrial](#ontrial) | Narrows the query results to only subscriptions that are on trial. -| [orderBy](#orderby) | Determines the order that the subscriptions should be returned in. (If empty, defaults to `dateCreated DESC`.) -| [orderId](#orderid) | Narrows the query results based on the order, per its ID. -| [plan](#plan) | Narrows the query results based on the subscription plan. -| [planId](#planid) | Narrows the query results based on the subscription plans’ IDs. -| [preferSites](#prefersites) | If [unique()](https://docs.craftcms.com/api/v4/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. -| [prepareSubquery](#preparesubquery) | Prepares the element query and returns its subquery (which determines what elements will be returned). -| [reference](#reference) | Narrows the query results based on the reference. -| [relatedTo](#relatedto) | Narrows the query results to only subscriptions that are related to certain other elements. -| [search](#search) | Narrows the query results to only subscriptions that match a search query. -| [siteSettingsId](#sitesettingsid) | Narrows the query results based on the subscriptions’ IDs in the `elements_sites` table. -| [status](#status) | Narrows the query results based on the subscriptions’ statuses. -| [trashed](#trashed) | Narrows the query results to only subscriptions that have been soft-deleted. -| [trialDays](#trialdays) | Narrows the query results based on the number of trial days. -| [uid](#uid) | Narrows the query results based on the subscriptions’ UIDs. -| [user](#user) | Narrows the query results based on the subscriptions’ user accounts. -| [userId](#userid) | Narrows the query results based on the subscriptions’ user accounts’ IDs. -| [with](#with) | Causes the query to return matching subscriptions eager-loaded with related elements. - - - - - -#### `afterPopulate` - -Performs any post-population processing on elements. - - - - - - - - - - -#### `andRelatedTo` - -Narrows the query results to only subscriptions that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all subscriptions that are related to myCategoryA and myCategoryB #} -{% set subscriptions = craft.subscriptions() - .relatedTo(myCategoryA) - .andRelatedTo(myCategoryB) - .all() %} -``` - -```php -// Fetch all subscriptions that are related to $myCategoryA and $myCategoryB -$subscriptions = \craft\commerce\elements\Subscription::find() - ->relatedTo($myCategoryA) - ->andRelatedTo($myCategoryB) - ->all(); -``` -::: - - -#### `asArray` - -Causes the query to return matching subscriptions as arrays of data, rather than [Subscription](commerce4:craft\commerce\elements\Subscription) objects. - - - - - -::: code -```twig -{# Fetch subscriptions as arrays #} -{% set subscriptions = craft.subscriptions() - .asArray() - .all() %} -``` - -```php -// Fetch subscriptions as arrays -$subscriptions = \craft\commerce\elements\Subscription::find() - ->asArray() - ->all(); -``` -::: - - -#### `cache` - -Enables query cache for this Query. - - - - - - - - - - -#### `clearCachedResult` - -Clears the [cached result](https://craftcms.com/docs/4.x/element-queries.html#cache). - - - - - - -#### `dateCanceled` - -Narrows the query results based on the subscriptions’ cancellation date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were canceled on or after 2018-04-01. -| `'< 2018-05-01'` | that were canceled before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were canceled between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions that were canceled recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateCanceled(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that were canceled recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateCanceled(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateCreated` - -Narrows the query results based on the subscriptions’ creation dates. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were created on or after 2018-04-01. -| `'< 2018-05-01'` | that were created before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were created between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were created at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch subscriptions created last month #} -{% set start = date('first day of last month')|atom %} -{% set end = date('first day of this month')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateCreated(['and', ">= #{start}", "< #{end}"]) - .all() %} -``` - -```php -// Fetch subscriptions created last month -$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM); -$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateCreated(['and', ">= {$start}", "< {$end}"]) - ->all(); -``` -::: - - -#### `dateExpired` - -Narrows the query results based on the subscriptions’ expiration date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that expired on or after 2018-04-01. -| `'< 2018-05-01'` | that expired before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that expired between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions that expired recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateExpired(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that expired recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateExpired(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateSuspended` - -Narrows the query results based on the subscriptions’ suspension date. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were suspended on or after 2018-04-01. -| `'< 2018-05-01'` | that were suspended before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were suspended between 2018-04-01 and 2018-05-01. - - -::: code -```twig -{# Fetch subscriptions that were suspended recently #} -{% set aWeekAgo = date('7 days ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateSuspended(">= #{aWeekAgo}") - .all() %} -``` - -```php -// Fetch subscriptions that were suspended recently -$aWeekAgo = new \DateTime('7 days ago')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateSuspended(">= {$aWeekAgo}") - ->all(); -``` -::: - - -#### `dateUpdated` - -Narrows the query results based on the subscriptions’ last-updated dates. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | that were updated on or after 2018-04-01. -| `'< 2018-05-01'` | that were updated before 2018-05-01. -| `['and', '>= 2018-04-04', '< 2018-05-01']` | that were updated between 2018-04-01 and 2018-05-01. -| `now`/`today`/`tomorrow`/`yesterday` | that were updated at midnight of the specified relative date. - - - -::: code -```twig -{# Fetch subscriptions updated in the last week #} -{% set lastWeek = date('1 week ago')|atom %} - -{% set subscriptions = craft.subscriptions() - .dateUpdated(">= #{lastWeek}") - .all() %} -``` - -```php -// Fetch subscriptions updated in the last week -$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->dateUpdated(">= {$lastWeek}") - ->all(); -``` -::: - - -#### `fixedOrder` - -Causes the query results to be returned in the order specified by [id](#id). - - - -::: tip -If no IDs were passed to [id](#id), setting this to `true` will result in an empty result set. -::: - - - -::: code -```twig -{# Fetch subscriptions in a specific order #} -{% set subscriptions = craft.subscriptions() - .id([1, 2, 3, 4, 5]) - .fixedOrder() - .all() %} -``` - -```php -// Fetch subscriptions in a specific order -$subscriptions = \craft\commerce\elements\Subscription::find() - ->id([1, 2, 3, 4, 5]) - ->fixedOrder() - ->all(); -``` -::: - - -#### `gatewayId` - -Narrows the query results based on the gateway, per its ID. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with a gateway with an ID of 1. -| `'not 1'` | not with a gateway with an ID of 1. -| `[1, 2]` | with a gateway with an ID of 1 or 2. -| `['not', 1, 2]` | not with a gateway with an ID of 1 or 2. - - - - -#### `hasStarted` - -Narrows the query results to only subscriptions that have started. - - - -::: code -```twig -{# Fetch started subscriptions #} -{% set subscriptions = craft.subscriptions() - .hasStarted() - .all() %} -``` - -```php -// Fetch started subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->hasStarted() - ->all(); -``` -::: - - -#### `id` - -Narrows the query results based on the subscriptions’ IDs. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with an ID of 1. -| `'not 1'` | not with an ID of 1. -| `[1, 2]` | with an ID of 1 or 2. -| `['not', 1, 2]` | not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the subscription by its ID #} -{% set subscription = craft.subscriptions() - .id(1) - .one() %} -``` - -```php -// Fetch the subscription by its ID -$subscription = \craft\commerce\elements\Subscription::find() - ->id(1) - ->one(); -``` -::: - - - -::: tip -This can be combined with [fixedOrder](#fixedorder) if you want the results to be returned in a specific order. -::: - - -#### `ignorePlaceholders` - -Causes the query to return matching subscriptions as they are stored in the database, ignoring matching placeholder -elements that were set by [craft\services\Elements::setPlaceholderElement()](https://docs.craftcms.com/api/v4/craft-services-elements.html#method-setplaceholderelement). - - - - - - - - - - -#### `inReverse` - -Causes the query results to be returned in reverse order. - - - - - -::: code -```twig -{# Fetch subscriptions in reverse #} -{% set subscriptions = craft.subscriptions() - .inReverse() - .all() %} -``` - -```php -// Fetch subscriptions in reverse -$subscriptions = \craft\commerce\elements\Subscription::find() - ->inReverse() - ->all(); -``` -::: - - -#### `isCanceled` - -Narrows the query results to only subscriptions that are canceled. - - - -::: code -```twig -{# Fetch canceled subscriptions #} -{% set subscriptions = craft.subscriptions() - .isCanceled() - .all() %} -``` - -```php -// Fetch canceled subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isCanceled() - ->all(); -``` -::: - - -#### `isExpired` - -Narrows the query results to only subscriptions that have expired. - - - -::: code -```twig -{# Fetch expired subscriptions #} -{% set subscriptions = craft.subscriptions() - .isExpired() - .all() %} -``` - -```php -// Fetch expired subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isExpired() - ->all(); -``` -::: - - -#### `isSuspended` - -Narrows the query results to only subscriptions that are suspended. - - - -::: code -```twig -{# Fetch suspended subscriptions #} -{% set subscriptions = craft.subscriptions() - .isSuspended() - .all() %} -``` - -```php -// Fetch suspended subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isSuspended() - ->all(); -``` -::: - - -#### `limit` - -Determines the number of subscriptions that should be returned. - - - -::: code -```twig -{# Fetch up to 10 subscriptions #} -{% set subscriptions = craft.subscriptions() - .limit(10) - .all() %} -``` - -```php -// Fetch up to 10 subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->limit(10) - ->all(); -``` -::: - - -#### `nextPaymentDate` - -Narrows the query results based on the subscriptions’ next payment dates. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'>= 2018-04-01'` | with a next payment on or after 2018-04-01. -| `'< 2018-05-01'` | with a next payment before 2018-05-01 -| `['and', '>= 2018-04-04', '< 2018-05-01']` | with a next payment between 2018-04-01 and 2018-05-01. - - - -::: code -```twig -{# Fetch subscriptions with a payment due soon #} -{% set aWeekFromNow = date('+7 days')|atom %} - -{% set subscriptions = craft.subscriptions() - .nextPaymentDate("< #{aWeekFromNow}") - .all() %} -``` - -```php -// Fetch subscriptions with a payment due soon -$aWeekFromNow = new \DateTime('+7 days')->format(\DateTime::ATOM); - -$subscriptions = \craft\commerce\elements\Subscription::find() - ->nextPaymentDate("< {$aWeekFromNow}") - ->all(); -``` -::: - - -#### `offset` - -Determines how many subscriptions should be skipped in the results. - - - -::: code -```twig -{# Fetch all subscriptions except for the first 3 #} -{% set subscriptions = craft.subscriptions() - .offset(3) - .all() %} -``` - -```php -// Fetch all subscriptions except for the first 3 -$subscriptions = \craft\commerce\elements\Subscription::find() - ->offset(3) - ->all(); -``` -::: - - -#### `onTrial` - -Narrows the query results to only subscriptions that are on trial. - - - -::: code -```twig -{# Fetch trialed subscriptions #} -{% set subscriptions = craft.subscriptions() - .onTrial() - .all() %} -``` - -```php -// Fetch trialed subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->isPaid() - ->all(); -``` -::: - - -#### `orderBy` - -Determines the order that the subscriptions should be returned in. (If empty, defaults to `dateCreated DESC`.) - - - -::: code -```twig -{# Fetch all subscriptions in order of date created #} -{% set subscriptions = craft.subscriptions() - .orderBy('dateCreated ASC') - .all() %} -``` - -```php -// Fetch all subscriptions in order of date created -$subscriptions = \craft\commerce\elements\Subscription::find() - ->orderBy('dateCreated ASC') - ->all(); -``` -::: - - -#### `orderId` - -Narrows the query results based on the order, per its ID. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with an order with an ID of 1. -| `'not 1'` | not with an order with an ID of 1. -| `[1, 2]` | with an order with an ID of 1 or 2. -| `['not', 1, 2]` | not with an order with an ID of 1 or 2. - - - - -#### `plan` - -Narrows the query results based on the subscription plan. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'foo'` | for a plan with a handle of `foo`. -| `['foo', 'bar']` | for plans with a handle of `foo` or `bar`. -| a [Plan](commerce4:craft\commerce\base\Plan) object | for a plan represented by the object. - - - -::: code -```twig -{# Fetch Supporter plan subscriptions #} -{% set subscriptions = craft.subscriptions() - .plan('supporter') - .all() %} -``` - -```php -// Fetch Supporter plan subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->plan('supporter') - ->all(); -``` -::: - - -#### `planId` - -Narrows the query results based on the subscription plans’ IDs. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | for a plan with an ID of 1. -| `[1, 2]` | for plans with an ID of 1 or 2. -| `['not', 1, 2]` | for plans not with an ID of 1 or 2. - - - - -#### `preferSites` - -If [unique()](https://docs.craftcms.com/api/v4/craft-elements-db-elementquery.html#method-unique) is set, this determines which site should be selected when querying multi-site elements. - - - -For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, -and this is set to `['c', 'b', 'a']`, then Foo will be returned for Site B, and Bar will be returned -for Site C. - -If this isn’t set, then preference goes to the current site. - - - -::: code -```twig -{# Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A #} -{% set subscriptions = craft.subscriptions() - .site('*') - .unique() - .preferSites(['a', 'b']) - .all() %} -``` - -```php -// Fetch unique subscriptions from Site A, or Site B if they don’t exist in Site A -$subscriptions = \craft\commerce\elements\Subscription::find() - ->site('*') - ->unique() - ->preferSites(['a', 'b']) - ->all(); -``` -::: - - -#### `prepareSubquery` - -Prepares the element query and returns its subquery (which determines what elements will be returned). - - - - - - -#### `reference` - -Narrows the query results based on the reference. - - - - - - -#### `relatedTo` - -Narrows the query results to only subscriptions that are related to certain other elements. - - - -See [Relations](https://craftcms.com/docs/4.x/relations.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch all subscriptions that are related to myCategory #} -{% set subscriptions = craft.subscriptions() - .relatedTo(myCategory) - .all() %} -``` - -```php -// Fetch all subscriptions that are related to $myCategory -$subscriptions = \craft\commerce\elements\Subscription::find() - ->relatedTo($myCategory) - ->all(); -``` -::: - - -#### `search` - -Narrows the query results to only subscriptions that match a search query. - - - -See [Searching](https://craftcms.com/docs/4.x/searching.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Get the search query from the 'q' query string param #} -{% set searchQuery = craft.app.request.getQueryParam('q') %} - -{# Fetch all subscriptions that match the search query #} -{% set subscriptions = craft.subscriptions() - .search(searchQuery) - .all() %} -``` - -```php -// Get the search query from the 'q' query string param -$searchQuery = \Craft::$app->request->getQueryParam('q'); - -// Fetch all subscriptions that match the search query -$subscriptions = \craft\commerce\elements\Subscription::find() - ->search($searchQuery) - ->all(); -``` -::: - - -#### `siteSettingsId` - -Narrows the query results based on the subscriptions’ IDs in the `elements_sites` table. - - - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | with an `elements_sites` ID of 1. -| `'not 1'` | not with an `elements_sites` ID of 1. -| `[1, 2]` | with an `elements_sites` ID of 1 or 2. -| `['not', 1, 2]` | not with an `elements_sites` ID of 1 or 2. - - - -::: code -```twig -{# Fetch the subscription by its ID in the elements_sites table #} -{% set subscription = craft.subscriptions() - .siteSettingsId(1) - .one() %} -``` - -```php -// Fetch the subscription by its ID in the elements_sites table -$subscription = \craft\commerce\elements\Subscription::find() - ->siteSettingsId(1) - ->one(); -``` -::: - - -#### `status` - -Narrows the query results based on the subscriptions’ statuses. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'active'` _(default)_ | that are active. -| `'expired'` | that have expired. - - - -::: code -```twig -{# Fetch expired subscriptions #} -{% set subscriptions = craft.subscriptions() - .status('expired') - .all() %} -``` - -```php -// Fetch expired subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->status('expired') - ->all(); -``` -::: - - -#### `trashed` - -Narrows the query results to only subscriptions that have been soft-deleted. - - - - - -::: code -```twig -{# Fetch trashed subscriptions #} -{% set subscriptions = craft.subscriptions() - .trashed() - .all() %} -``` - -```php -// Fetch trashed subscriptions -$subscriptions = \craft\commerce\elements\Subscription::find() - ->trashed() - ->all(); -``` -::: - - -#### `trialDays` - -Narrows the query results based on the number of trial days. - - - - - - -#### `uid` - -Narrows the query results based on the subscriptions’ UIDs. - - - - - -::: code -```twig -{# Fetch the subscription by its UID #} -{% set subscription = craft.subscriptions() - .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - .one() %} -``` - -```php -// Fetch the subscription by its UID -$subscription = \craft\commerce\elements\Subscription::find() - ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') - ->one(); -``` -::: - - -#### `user` - -Narrows the query results based on the subscriptions’ user accounts. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `'foo'` | for a user account with a username of `foo` -| `['foo', 'bar']` | for user accounts with a username of `foo` or `bar`. -| a [User](https://docs.craftcms.com/api/v4/craft-elements-user.html) object | for a user account represented by the object. - - - -::: code -```twig -{# Fetch the current user's subscriptions #} -{% set subscriptions = craft.subscriptions() - .user(currentUser) - .all() %} -``` - -```php -// Fetch the current user's subscriptions -$user = Craft::$app->user->getIdentity(); -$subscriptions = \craft\commerce\elements\Subscription::find() - ->user($user) - ->all(); -``` -::: - - -#### `userId` - -Narrows the query results based on the subscriptions’ user accounts’ IDs. - -Possible values include: - -| Value | Fetches subscriptions… -| - | - -| `1` | for a user account with an ID of 1. -| `[1, 2]` | for user accounts with an ID of 1 or 2. -| `['not', 1, 2]` | for user accounts not with an ID of 1 or 2. - - - -::: code -```twig -{# Fetch the current user's subscriptions #} -{% set subscriptions = craft.subscriptions() - .userId(currentUser.id) - .all() %} -``` - -```php -// Fetch the current user's subscriptions -$user = Craft::$app->user->getIdentity(); -$subscriptions = \craft\commerce\elements\Subscription::find() - ->userId($user->id) - ->all(); -``` -::: - - -#### `with` - -Causes the query to return matching subscriptions eager-loaded with related elements. - - - -See [Eager-Loading Elements](https://craftcms.com/docs/4.x/dev/eager-loading-elements.html) for a full explanation of how to work with this parameter. - - - -::: code -```twig -{# Fetch subscriptions eager-loaded with the "Related" field’s relations #} -{% set subscriptions = craft.subscriptions() - .with(['related']) - .all() %} -``` - -```php -// Fetch subscriptions eager-loaded with the "Related" field’s relations -$subscriptions = \craft\commerce\elements\Subscription::find() - ->with(['related']) - ->all(); -``` -::: - - - - + +!!!include(docs/.artifacts/commerce/4.x/subscriptions.md)!!! diff --git a/docs/commerce/4.x/upgrading.md b/docs/commerce/4.x/upgrading.md index 7bfa196dd..8abe1e794 100644 --- a/docs/commerce/4.x/upgrading.md +++ b/docs/commerce/4.x/upgrading.md @@ -88,7 +88,7 @@ $countries = \craft\commerce\Plugin::getInstance() ::: ::: tip -You can get the _entire_ list of countries, and not just those you’ve chosen, with `craft.getAddresses().countryRepository.getAll()`. +You can get the _entire_ list of countries, and not just those you’ve chosen, with `craft.app.getAddresses().countryRepository.getAll()`. ::: States can no longer be enabled or disabled for selection in dropdown lists, but you can use the new **Order Address Condition** to limit them instead. This example is configured to only allow orders from Western Australia: diff --git a/docs/getting-started-tutorial/build/blog-templates.md b/docs/getting-started-tutorial/build/blog-templates.md index 580798acf..967a4faf6 100644 --- a/docs/getting-started-tutorial/build/blog-templates.md +++ b/docs/getting-started-tutorial/build/blog-templates.md @@ -120,7 +120,7 @@ If you were to go back into the control panel and create some more posts, you co #### Feature Image -Let’s output the image we attached via the “Feature Image” asset field. That field had a handle of `featureImage`, so it will be available on the `entry` variable as `entry.featureImage`, just like the title was: +Let’s output the image we attached via [the “Feature Image” asset field](../configure/resources.md#feature-image). That field had a handle of `featureImage`, so it will be available on the `entry` variable as `entry.featureImage`, just like the title was: ```twig{4,15-19} {% extends '_layout' %} @@ -187,7 +187,7 @@ If the lack of styles makes it difficult to evaluate whether you are staying on #### Topics -Let’s add some more metadata to the top of our post. Our content model included a category field called **Topics**, which we can access in a really similar way to the feature image! +Let’s add some more metadata to the top of our post. Our content model included a [category field](../configure/resources.md#categoriestopics) called **Topics**, which we can access in a really similar way to the feature image! Just below the existing `set` tag, add another one to fetch the attached categories: @@ -195,7 +195,7 @@ Just below the existing `set` tag, add another one to fetch the attached categor {% set featureImage = entry.featureImage.one() %} {# Load attached topics: #} -{% set topics = entry.topics.all() %} +{% set topics = entry.postCategories.all() %} ``` Because we’re allowing authors to attach multiple topics to a post, we’ve used `.all()` to fetch _all_ of them, instead of just _one_. This is important, because we will treat `topics` (plural) a little bit differently from `featureImage` (singular). @@ -239,7 +239,7 @@ If you pasted this into `templates/blog/_entry.twig` and the indentation got mes #### Post Content -Let’s output the post content stored in our Matrix field. This process starts in a familiar way: +Let’s output the [post content](../configure/resources.md#post-content) stored in our Matrix field. This process starts in a familiar way: 1. Load matrix blocks via the `postContent` field handle and store them in a variable; 1. Loop over those blocks with a `{% for %}` tag; diff --git a/docs/getting-started-tutorial/build/optimization.md b/docs/getting-started-tutorial/build/optimization.md index de83b373a..5b491366a 100644 --- a/docs/getting-started-tutorial/build/optimization.md +++ b/docs/getting-started-tutorial/build/optimization.md @@ -10,7 +10,7 @@ We have a host of other ideas for [next steps](../more/README.md) if you would p When building the blog and topic index pages, there was a lot of repeated code involved with outputting the post previews. Twig’s `include` tag can help us reduce that repetition by extracting it into a separate template, and referencing it in both places. -We’ll start by taking the entire `for` loop from `templates/blog/_index.twig` and moving it to a new file, `templates/blog/_feed.twig`: +We’ll start by taking the entire `for` loop from `templates/blog/index.twig` and moving it to a new file, `templates/blog/_feed.twig`: ```twig {% for post in posts %} @@ -34,7 +34,7 @@ We’ll start by taking the entire `for` loop from `templates/blog/_index.twig` {% endfor %} ``` -In place of that block of code in `templates/blog/_index.twig`, `include` the new template (then make the same change to `templates/blog/_topic.twig`): +In place of that block of code in `templates/blog/index.twig`, `include` the new template (then make the same change to `templates/blog/_topic.twig`): ```twig {% include 'blog/_feed' %} diff --git a/docs/getting-started-tutorial/configure/resources.md b/docs/getting-started-tutorial/configure/resources.md index 57445ce11..dd5c33870 100644 --- a/docs/getting-started-tutorial/configure/resources.md +++ b/docs/getting-started-tutorial/configure/resources.md @@ -76,10 +76,10 @@ Assets are organized into _volumes_, which sit on top of a _filesystem_. Filesys We’ll create a local Asset Volume within the web root for blog post images: -1. In the control panel, navigate to **Settings** → **Assets**. -1. Click **+ New volume**. -1. Enter “Images” in the **Name** field . -1. Click the **Asset Filesystem** menu and select **Create a new filesystem…** +1. In the control panel, navigate to **Settings** → **Assets**; +1. Click **+ New volume**; +1. Enter “Images” in the **Name** field ; +1. Click the **Asset Filesystem** menu and select **Create a new filesystem…**; Within the slideout that opens, provide these settings: @@ -116,12 +116,12 @@ The second resource we need to create is a group for our blog’s _categories_. Screenshot of new category group fields -1. Navigate to **Settings** and choose **Categories**. -1. Choose **+ New category group**. -1. In the **Name** field, enter “Topics”. -1. In the **Max Levels** field, enter `1`. -1. Set the **Category URI Format** to `blog/topic/{slug}`. -1. Set the **Template** to `blog/_topic`. +1. Navigate to **Settings** and choose **Categories**; +1. Choose **+ New category group**; +1. In the **Name** field, enter “Topics”; +1. In the **Max Levels** field, enter `1`; +1. Set the **Category URI Format** to `blog/topic/{slug}`; +1. Set the **Template** to `blog/_topic`; 1. **Save** the category group. ## Custom Fields @@ -143,7 +143,7 @@ The post summary will be entered in a _plain text_ field. 1. Click **+ New Field**; 1. Enter “Summary” into the **Name** field; -1. Enter “Summaries should be one or two sentences.” in the **Default Instructions** field to give authors a hint about the field’s intended usage. +1. Enter “Summaries should be one or two sentences.” in the **Default Instructions** field to give authors a hint about the field’s intended usage; 1. Enable **Allow line breaks**; 1. Set the revealed **Initial Rows** field to `1`; 1. Save the field. @@ -173,7 +173,7 @@ Posts’ primary images will be added to an _asset_ field. 1. Click **+ New Field**; -1. Enter “Feature Image” into the **Name** field; +1. Enter “Feature Image” into the **Name** field (and note that Craft automatically generates a **Handle** of `featureImage`); 1. Select **Assets** from the **Field Type** menu—the rest of the page will be updated with options specific to asset fields; 1. Tick **Restrict assets to a single location?** ; 1. Select the **Images** volume from the revealed **Asset Location** menu; @@ -188,7 +188,7 @@ Posts’ primary images will be added to an _asset_ field. Our _topics_ field only needs a couple of options: 1. Click **+ New Field**; -1. Enter “Post Categories” into the **Name** field; +1. Enter “Post Categories” into the **Name** field (and note that Craft automatically generates a **Handle** of `postCategories`); 1. Choose “Categories” from the **Field Type** menu—the rest of the page will be updated with options specific to categories fields; 1. Choose “Topics” from the **Source** menu (it will probably be selected, already); 1. Save the field. @@ -220,7 +220,7 @@ Matrix fields are inherently a bit more complex than other field types, because 1. Click **+ New Field**; -1. Enter “Post Content” in the **Name** field; +1. Enter “Post Content” in the **Name** field (and note that Craft automatically generates a **Handle** of `postContent`); 1. Choose “Matrix” from the **Field Type** menu—the rest of the page will be updated with options specific to matrix fields; 1. Within the **Configuration** space, use the **+ New block type** button to create two _block types_: diff --git a/package-lock.json b/package-lock.json index 7fb617326..33100f49a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27,6 +27,7 @@ "jest": "^27.5.1", "markdown-it-deflist": "^2.1.0", "markdown-it-imsize": "^2.0.1", + "markdown-it-include": "^2.0.0", "nprogress": "^0.2.0", "postcss": "^8.4.8", "postcss-import": "^12.0.1", @@ -20885,6 +20886,18 @@ "integrity": "sha512-5SH90ademqcR8ifQCBXRCfIR4HGfZZOh5pO0j2TglulfSQH+SBXM4Iw/QlTUbSoUwVZArCYgECoMvktDS2kP3w==", "dev": true }, + "node_modules/markdown-it-include": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/markdown-it-include/-/markdown-it-include-2.0.0.tgz", + "integrity": "sha512-wfgIX92ZEYahYWiCk6Jx36XmHvAimeHN420csOWgfyZjpf171Y0xREqZWcm/Rwjzyd0RLYryY+cbNmrkYW2MDw==", + "dev": true, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "markdown-it": ">=8.4.2" + } + }, "node_modules/markdown-it-table-of-contents": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/markdown-it-table-of-contents/-/markdown-it-table-of-contents-0.4.4.tgz", @@ -47812,6 +47825,13 @@ "integrity": "sha512-5SH90ademqcR8ifQCBXRCfIR4HGfZZOh5pO0j2TglulfSQH+SBXM4Iw/QlTUbSoUwVZArCYgECoMvktDS2kP3w==", "dev": true }, + "markdown-it-include": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/markdown-it-include/-/markdown-it-include-2.0.0.tgz", + "integrity": "sha512-wfgIX92ZEYahYWiCk6Jx36XmHvAimeHN420csOWgfyZjpf171Y0xREqZWcm/Rwjzyd0RLYryY+cbNmrkYW2MDw==", + "dev": true, + "requires": {} + }, "markdown-it-table-of-contents": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/markdown-it-table-of-contents/-/markdown-it-table-of-contents-0.4.4.tgz", diff --git a/package.json b/package.json index 823cbb378..0a7f33481 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "jest": "^27.5.1", "markdown-it-deflist": "^2.1.0", "markdown-it-imsize": "^2.0.1", + "markdown-it-include": "^2.0.0", "nprogress": "^0.2.0", "postcss": "^8.4.8", "postcss-import": "^12.0.1",