Elements
- Type
- Class
- Namespace
- craft\services
- Inherits
- craft\services\Elements » yii\base\Component » yii\base\BaseObject
- Implements
- yii\base\Configurable
- Since
- 3.0.0
The Elements service provides APIs for managing elements.
An instance of the service is available via Craft::$app->elements
.
Public Properties
Property | Description |
---|---|
allElementTypes | string[] – The available element classes. |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
cacheExpiryDate | DateTime |
duplicatedElementIds | integer[] – Stores a mapping of source element IDs to their duplicated element IDs. |
duplicatedElementSourceIds | integer[] – Stores a mapping of duplicated element IDs to their source element IDs. |
elementUri | craft\base\ElementInterface |
isCollectingCacheInfo | boolean |
isCollectingCacheTags | boolean |
placeholderElement | craft\base\ElementInterface – The element currently being edited by Live Preview. |
placeholderElements | craft\base\ElementInterface[] |
allElementTypes
- Type
- string[]
- Default value
null
- Access
- Read-only
The available element classes.
cacheExpiryDate
- Type
- DateTime
- Default value
null
- Access
- Write-only
- Since
- 4.3.0
duplicatedElementIds
- Type
- integer[]
- Default value
[]
Stores a mapping of source element IDs to their duplicated element IDs.
duplicatedElementSourceIds
- Type
- integer[]
- Default value
[]
- Since
- 3.4.0
Stores a mapping of duplicated element IDs to their source element IDs.
elementUri
- Type
- craft\base\ElementInterface
- Default value
null
- Access
- Write-only
- Since
- 4.6.0
isCollectingCacheInfo
- Type
- boolean
- Default value
null
- Access
- Read-only
- Since
- 4.3.0
isCollectingCacheTags
- Type
- boolean
- Default value
null
- Access
- Read-only
- Since
- 3.5.0
placeholderElement
- Type
- craft\base\ElementInterface
- Default value
null
- Access
- Write-only
The element currently being edited by Live Preview.
placeholderElements
- Type
- craft\base\ElementInterface[]
- Default value
null
- Access
- Read-only
- Since
- 3.2.5
Public Methods
Method | Description |
---|---|
__call() | Calls the named method which is not a class method. |
__clone() | This method is called after the object is created by cloning an existing one. |
__construct() | Constructor. |
__get() | Returns the value of a component property. |
__isset() | Checks if a property is set, i.e. defined and not null. |
__set() | Sets the value of a component property. |
__unset() | Sets a component property to be null. |
attachBehavior() | Attaches a behavior to this component. |
attachBehaviors() | Attaches a list of behaviors to the component. |
behaviors() | Returns a list of behaviors that this component should behave as. |
canCreateDrafts() | Returns whether a user is authorized to create drafts for the given element. |
canDelete() | Returns whether a user is authorized to delete the given element. |
canDeleteForSite() | Returns whether a user is authorized to delete the given element for its current site. |
canDuplicate() | Returns whether a user is authorized to duplicate the given element. |
canGetProperty() | Returns a value indicating whether a property can be read. |
canSave() | Returns whether a user is authorized to save the given element in its current form. |
canSetProperty() | Returns a value indicating whether a property can be set. |
canView() | Returns whether a user is authorized to view the given element’s edit page. |
className() | Returns the fully qualified name of this class. |
collectCacheInfoForElement() | * Stores cache invalidation info for a given element. |
collectCacheTags() | Adds element cache invalidation tags to the current collection. |
createAction() | Creates an element action with a given config. |
createEagerLoadingPlans() | Normalizes a with element query param into an array of eager-loading plans. |
createElement() | Creates an element with a given config. |
createElementQuery() | Creates an element query for a given element type. |
createExporter() | Creates an element exporter with a given config. |
deleteElement() | Deletes an element. |
deleteElementById() | Deletes an element by its ID. |
deleteElementForSite() | Deletes an element in the site it’s loaded in. |
deleteElementsForSite() | Deletes elements in the site they are currently loaded in. |
detachBehavior() | Detaches a behavior from the component. |
detachBehaviors() | Detaches all behaviors from the component. |
duplicateElement() | Duplicates an element. |
eagerLoadElements() | Eager-loads additional elements onto a given set of elements. |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. |
getAllElementTypes() | Returns all available element classes. |
getBehavior() | Returns the named behavior object. |
getBehaviors() | Returns all behaviors attached to this component. |
getElementById() | Returns an element by its ID. |
getElementByUid() | Returns an element by its UID. |
getElementByUri() | Returns an element by its URI. |
getElementTypeById() | Returns the class of an element with a given ID. |
getElementTypeByRefHandle() | Returns an element class by its handle. |
getElementTypeByUid() | Returns the class of an element with a given UID. |
getElementTypesByIds() | Returns the classes of elements with the given IDs. |
getElementUriForSite() | Returns an element’s URI for a given site. |
getEnabledSiteIdsForElement() | Returns the site IDs that a given element is enabled in. |
getIsCollectingCacheInfo() | Returns whether we are currently collecting element cache invalidation info. |
getIsCollectingCacheTags() | Returns whether we are currently collecting element cache invalidation tags. |
getPlaceholderElement() | Returns a placeholder element by its ID and site ID. |
getPlaceholderElements() | Returns all placeholder elements. |
getRecentActivity() | Returns the recent activity for an element. |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. |
hasMethod() | Returns a value indicating whether a method is defined. |
hasProperty() | Returns a value indicating whether a property is defined for this component. |
init() | Initializes the object. |
invalidateAllCaches() | Invalidates all element caches. |
invalidateCachesForElement() | Invalidates caches for the given element. |
invalidateCachesForElementType() | Invalidates caches for the given element type. |
mergeCanonicalChanges() | Merges recent canonical element changes into a given derivative, such as a draft. |
mergeElements() | Merges two elements together. |
mergeElementsByIds() | Merges two elements together by their IDs. |
off() | Detaches an existing event handler from this component. |
on() | Attaches an event handler to an event. |
parseRefs() | Parses a string for element reference tags. |
propagateElement() | Propagates an element to a different site. |
propagateElements() | Propagates all elements that match a given element query to another site(s). |
resaveElements() | Resaves all elements that match a given element query. |
restoreElement() | Restores an element. |
restoreElements() | Restores multiple elements. |
saveElement() | Handles all of the routine tasks that go along with saving elements. |
setCacheExpiryDate() | Sets a possible cache expiration date that stopCollectingCacheInfo() should return. |
setElementUri() | Sets the URI on an element. |
setPlaceholderElement() | Stores a placeholder element that element queries should use instead of populating a new element with a matching ID and site ID. |
startCollectingCacheInfo() | Starts collecting element cache invalidation info. |
startCollectingCacheTags() | Starts collecting element cache invalidation tags. |
stopCollectingCacheInfo() | Stops collecting element invalidation info, and returns a yii\caching\TagDependency and recommended max cache duration that should be used when saving the cache data. |
stopCollectingCacheTags() | Stops collecting element cache invalidation tags, and returns a cache dependency object. |
trackActivity() | Tracks new activity for an element. |
trigger() | Triggers an event. |
updateCanonicalElement() | Updates the canonical element from a given derivative, such as a draft or revision. |
updateDescendantSlugsAndUris() | Updates an element’s descendants’ slugs and URIs. |
updateElementSlugAndUri() | Updates an element’s slug and URI, along with any descendants. |
updateElementSlugAndUriInOtherSites() | Updates an element’s slug and URI, for any sites besides the given one. |
canCreateDrafts()
- Since
- 4.3.0
Returns whether a user is authorized to create drafts for the given element.
This should always be called in conjunction with canView() or canSave().
Arguments
$element
(craft\base\ElementInterface)$user
(craft\elements\User, null)
Returns
canDelete()
- Since
- 4.3.0
Returns whether a user is authorized to delete the given element.
This should always be called in conjunction with canView() or canSave().
Arguments
$element
(craft\base\ElementInterface)$user
(craft\elements\User, null)
Returns
canDeleteForSite()
- Since
- 4.3.0
Returns whether a user is authorized to delete the given element for its current site.
This should always be called in conjunction with canView() or canSave().
Arguments
$element
(craft\base\ElementInterface)$user
(craft\elements\User, null)
Returns
canDuplicate()
- Since
- 4.3.0
Returns whether a user is authorized to duplicate the given element.
This should always be called in conjunction with canView() or canSave().
Arguments
$element
(craft\base\ElementInterface)$user
(craft\elements\User, null)
Returns
canSave()
- Since
- 4.3.0
Returns whether a user is authorized to save the given element in its current form.
Arguments
$element
(craft\base\ElementInterface)$user
(craft\elements\User, null)
Returns
canView()
- Since
- 4.3.0
Returns whether a user is authorized to view the given element’s edit page.
Arguments
$element
(craft\base\ElementInterface)$user
(craft\elements\User, null)
Returns
collectCacheInfoForElement()
- Since
- 4.5.0
- Stores cache invalidation info for a given element.
Arguments
$element
(craft\base\ElementInterface)
collectCacheTags()
- Since
- 3.5.0
Adds element cache invalidation tags to the current collection.
Arguments
$tags
(string[])
createAction()
Creates an element action with a given config.
Arguments
$config
(string, array) – The element action’s class name, or its config, with atype
value and optionally asettings
value
Returns
\craft\services\T
– The element action
createEagerLoadingPlans()
- Since
- 3.5.0
Normalizes a with
element query param into an array of eager-loading plans.
Arguments
Returns
craft\elements\db\EagerLoadPlan[]
createElement()
Creates an element with a given config.
Arguments
Returns
\craft\services\T
– The element
createElementQuery()
- Since
- 3.5.0
Creates an element query for a given element type.
Arguments
$elementType
(string) – The element class
Returns
craft\elements\db\ElementQueryInterface – The element query
Throws
- yii\base\InvalidArgumentException
if $elementType is not a valid element
createExporter()
Creates an element exporter with a given config.
Arguments
$config
(string, array) – The element exporter’s class name, or its config, with atype
value and optionally asettings
value
Returns
\craft\services\T
– The element exporter
deleteElement()
Deletes an element.
Arguments
$element
(craft\base\ElementInterface) – The element to be deleted$hardDelete
(boolean) – Whether the element should be hard-deleted immediately, instead of soft-deleted
Returns
boolean – Whether the element was deleted successfully
Throws
deleteElementById()
Deletes an element by its ID.
Arguments
$elementId
(integer) – The element’s ID$elementType
(string, null) – The element class.$siteId
(integer, null) – The site to fetch the element in. Defaults to the current site.$hardDelete
(boolean) – Whether the element should be hard-deleted immediately, instead of soft-deleted
Returns
boolean – Whether the element was deleted successfully
Throws
deleteElementForSite()
- Since
- 4.4.0
Deletes an element in the site it’s loaded in.
Arguments
$element
(craft\base\ElementInterface)
deleteElementsForSite()
- Since
- 4.4.0
Deletes elements in the site they are currently loaded in.
Arguments
$elements
(craft\base\ElementInterface[])
Throws
- yii\base\InvalidArgumentException
if all elements don’t have the same type and site ID.
duplicateElement()
Duplicates an element.
Arguments
$element
(\craft\services\T
) – The element to duplicate$newAttributes
(array) – Any attributes to apply to the duplicate. This can contain asiteAttributes
key, set to an array of site-specific attribute array, indexed by site IDs.$placeInStructure
(boolean) – Whether to position the cloned element after the original one in its structure. (This will only happen if the duplicated element is canonical.)$trackDuplication
(boolean) – Whether to keep track of the duplication from craft\services\Elements::$duplicatedElementIds and craft\services\Elements::$duplicatedElementSourceIds
Returns
\craft\services\T
– The duplicated element
Throws
- craft\errors\UnsupportedSiteException
if the element is being duplicated into a site it doesn’t support - craft\errors\InvalidElementException
if saveElement() returns false for any of the sites - Throwable
if reasons
eagerLoadElements()
Eager-loads additional elements onto a given set of elements.
Arguments
$elementType
(string) – The root element type class$elements
(craft\base\ElementInterface[]) – The root element models that should be updated with the eager-loaded elements$with
(array, string, craft\elements\db\EagerLoadPlan[]) – Dot-delimited paths of the elements that should be eager-loaded into the root elements
getAllElementTypes()
Returns all available element classes.
Returns
string[] – The available element classes.
getElementById()
Returns an element by its ID.
If no element type is provided, the method will first have to run a DB query to determine what type of element the $id is, so you should definitely pass it if it’s known. The element’s status will not be a factor when using this method.
Arguments
$elementId
(integer) – The element’s ID.$elementType
(string, null) – The element class.$siteId
(integer, string, integer[], null) – The site(s) to fetch the element in. Defaults to the current site.$criteria
(array)
Returns
\craft\services\T
, null – The matching element, or null
.
getElementByUid()
- Since
- 3.5.13
Returns an element by its UID.
If no element type is provided, the method will first have to run a DB query to determine what type of element the $uid is, so you should definitely pass it if it’s known. The element’s status will not be a factor when using this method.
Arguments
$uid
(string) – The element’s UID.$elementType
(string, null) – The element class.$siteId
(integer, string, integer[], null) – The site(s) to fetch the element in. Defaults to the current site.$criteria
(array)
Returns
\craft\services\T
, null – The matching element, or null
.
getElementByUri()
Returns an element by its URI.
Arguments
$uri
(string) – The element’s URI.$siteId
(integer, null) – The site to look for the URI in, and to return the element in. Defaults to the current site.$enabledOnly
(boolean) – Whether to only look for an enabled element. Defaults tofalse
.
Returns
craft\base\ElementInterface, null – The matching element, or null
.
getElementTypeById()
Returns the class of an element with a given ID.
Arguments
$elementId
(integer) – The element’s ID
Returns
string, null – The element’s class, or null if it could not be found
getElementTypeByRefHandle()
Returns an element class by its handle.
Arguments
$refHandle
(string) – The element class handle
Returns
string, null – The element class, or null if it could not be found
getElementTypeByUid()
- Since
- 3.5.13
Returns the class of an element with a given UID.
Arguments
$uid
(string) – The element’s UID
Returns
string, null – The element’s class, or null if it could not be found
getElementTypesByIds()
Returns the classes of elements with the given IDs.
Arguments
$elementIds
(integer[]) – The elements’ IDs
Returns
string[]
getElementUriForSite()
Returns an element’s URI for a given site.
Arguments
$elementId
(integer) – The element’s ID.$siteId
(integer) – The site to search for the element’s URI in.
Returns
string, null, false – The element’s URI or null
, or false
if the element doesn’t exist.
getEnabledSiteIdsForElement()
Returns the site IDs that a given element is enabled in.
Arguments
$elementId
(integer) – The element’s ID.
Returns
integer[] – The site IDs that the element is enabled in. If the element could not be found, an empty array will be returned.
getIsCollectingCacheInfo()
- Since
- 4.3.0
Returns whether we are currently collecting element cache invalidation info.
See also:
Returns
getIsCollectingCacheTags()
DEPRECATED
Deprecated in 4.3.0. getIsCollectingCacheInfo() should be used instead.
- Since
- 3.5.0
Returns whether we are currently collecting element cache invalidation tags.
Returns
getPlaceholderElement()
Returns a placeholder element by its ID and site ID.
See also setPlaceholderElement()View source
Arguments
Returns
craft\base\ElementInterface, null – The placeholder element if one exists, or null.
getPlaceholderElements()
- Since
- 3.2.5
Returns all placeholder elements.
Returns
getRecentActivity()
- Since
- 4.5.0
Returns the recent activity for an element.
Arguments
$element
(craft\base\ElementInterface)$excludeUserId
(integer, null)
Returns
craft\models\ElementActivity[]
invalidateAllCaches()
- Since
- 3.5.0
Invalidates all element caches.
invalidateCachesForElement()
- Since
- 3.5.0
Invalidates caches for the given element.
Arguments
$element
(craft\base\ElementInterface)
invalidateCachesForElementType()
- Since
- 3.5.0
Invalidates caches for the given element type.
Arguments
$elementType
(string)
mergeCanonicalChanges()
- Since
- 3.7.0
Merges recent canonical element changes into a given derivative, such as a draft.
Arguments
$element
(craft\base\ElementInterface) – The derivative element
mergeElements()
- Since
- 3.1.31
Merges two elements together.
This method will update the following:
- Any relations involving the merged element
- Any structures that contain the merged element
- Any reference tags in textual custom fields referencing the merged element
Arguments
$mergedElement
(craft\base\ElementInterface) – The element that is going away.$prevailingElement
(craft\base\ElementInterface) – The element that is sticking around.
Returns
boolean – Whether the elements were merged successfully.
Throws
- Throwable
if reasons
mergeElementsByIds()
Merges two elements together by their IDs.
This method will update the following:
- Any relations involving the merged element
- Any structures that contain the merged element
- Any reference tags in textual custom fields referencing the merged element
Arguments
$mergedElementId
(integer) – The ID of the element that is going away.$prevailingElementId
(integer) – The ID of the element that is sticking around.
Returns
boolean – Whether the elements were merged successfully.
Throws
- craft\errors\ElementNotFoundException
if one of the element IDs don’t exist. - Throwable
if reasons
parseRefs()
Parses a string for element reference tags.
Arguments
$str
(string) – The string to parse$defaultSiteId
(integer, null) – The default site ID to query the elements in
Returns
string – The parsed string
propagateElement()
- Since
- 3.0.13
Propagates an element to a different site.
Arguments
$element
(craft\base\ElementInterface) – The element to propagate$siteId
(integer) – The site ID that the element should be propagated to$siteElement
(craft\base\ElementInterface, false, null) – The element loaded for the propagated site (only pass this if you already had a reason to load it). Set tofalse
if it is known to not exist yet.
Returns
craft\base\ElementInterface – The element in the target site
Throws
- yii\base\Exception
if the element couldn't be propagated - craft\errors\UnsupportedSiteException
if the element doesn’t support$siteId
propagateElements()
- Since
- 3.2.0
Propagates all elements that match a given element query to another site(s).
Arguments
$query
(craft\elements\db\ElementQueryInterface) – The element query to fetch elements with$siteIds
(integer, integer[], null) – The site ID(s) that the elements should be propagated to. If null, elements will be$continueOnError
(boolean) – Whether to continue going if an error occurs
Throws
- Throwable
if reasons propagated to all supported sites, except the one they were queried in.
resaveElements()
- Since
- 3.2.0
Resaves all elements that match a given element query.
Arguments
$query
(craft\elements\db\ElementQueryInterface) – The element query to fetch elements with$continueOnError
(boolean) – Whether to continue going if an error occurs$skipRevisions
(boolean) – Whether elements that are (or belong to) a revision should be skipped$updateSearchIndex
(boolean, null) – Whether to update the element search index for the element (this will happen via a background job if this is a web request)$touch
(boolean) – Whether to update thedateUpdated
timestamps for the elements
Throws
- Throwable
if reasons
restoreElement()
- Since
- 3.1.0
Restores an element.
Arguments
$element
(craft\base\ElementInterface)
Returns
boolean – Whether the element was restored successfully
Throws
- yii\base\Exception
if the $element doesn’t have any supported sites - Throwable
if reasons
restoreElements()
Restores multiple elements.
Arguments
$elements
(craft\base\ElementInterface[])
Returns
boolean – Whether at least one element was restored successfully
Throws
- craft\errors\UnsupportedSiteException
if an element is being restored for a site it doesn’t support - Throwable
if reasons
saveElement()
Handles all of the routine tasks that go along with saving elements.
Those tasks include:
- Validating its content (if $validateContent is
true
, or it’s left asnull
and the element is enabled) - Ensuring the element has a title if its type has titles, and giving it a default title in the event that $validateContent is set to
false
- Saving a row in the
elements
table - Assigning the element’s ID on the element model, if it’s a new element
- Assigning the element’s ID on the element’s content model, if there is one and it’s a new set of content
- Updating the search index with new keywords from the element’s content
- Setting a unique URI on the element, if it’s supposed to have one.
- Saving the element’s row(s) in the
elements_sites
andcontent
tables - Deleting any rows in the
elements_sites
andcontent
tables that no longer need to be there - Cleaning any template caches that the element was involved in
The function will fire beforeElementSave
and afterElementSave
events, and will call beforeSave()
and afterSave()
methods on the passed-in element, giving the element opportunities to hook into the save process.
Example usage - creating a new entry:
$entry = new Entry();
$entry->sectionId = 10;
$entry->typeId = 1;
$entry->authorId = 5;
$entry->enabled = true;
$entry->title = "Hello World!";
$entry->setFieldValues([
'body' => "<p>I can’t believe I literally just called this “Hello World!”.</p>",
]);
$success = Craft::$app->elements->saveElement($entry);
if (!$success) {
Craft::error('Couldn’t save the entry "'.$entry->title.'"', __METHOD__);
}
Arguments
$element
(craft\base\ElementInterface) – The element that is being saved$runValidation
(boolean) – Whether the element should be validated$propagate
(boolean) – Whether the element should be saved across all of its supported sites (this can only be disabled when updating an existing element)$updateSearchIndex
(boolean, null) – Whether to update the element search index for the element (this will happen via a background job if this is a web request)$forceTouch
(boolean) – Whether to force thedateUpdated
timestamp to be updated for the element, regardless of whether it’s being resaved$crossSiteValidate
Returns
Throws
- craft\errors\ElementNotFoundException
if $element has an invalid $id - yii\base\Exception
if the $element doesn’t have any supported sites - Throwable
if reasons
setCacheExpiryDate()
- Since
- 4.3.0
Sets a possible cache expiration date that stopCollectingCacheInfo() should return.
The value will only be used if it is less than the currently stored expiration date.
Arguments
$expiryDate
(DateTime)
setElementUri()
- Since
- 4.6.0
Sets the URI on an element.
Arguments
$element
(craft\base\ElementInterface)
Throws
- craft\errors\OperationAbortedException
if a unique URI could not be found
setPlaceholderElement()
Stores a placeholder element that element queries should use instead of populating a new element with a matching ID and site ID.
This is used by Live Preview and Sharing features.
See also getPlaceholderElement()View source
Arguments
$element
(craft\base\ElementInterface) – The element currently being edited by Live Preview.
Throws
- yii\base\InvalidArgumentException
if the element is missing an ID
startCollectingCacheInfo()
- Since
- 4.3.0
Starts collecting element cache invalidation info.
startCollectingCacheTags()
DEPRECATED
Deprecated in 4.3.0. startCollectingCacheInfo() should be used instead.
- Since
- 3.5.0
Starts collecting element cache invalidation tags.
stopCollectingCacheInfo()
- Since
- 4.3.0
Stops collecting element invalidation info, and returns a yii\caching\TagDependency and recommended max cache duration that should be used when saving the cache data.
If no cache tags were registered, [null, null]
will be returned.
Returns
stopCollectingCacheTags()
DEPRECATED
Deprecated in 4.3.0. stopCollectingCacheInfo() should be used instead.
- Since
- 3.5.0
Stops collecting element cache invalidation tags, and returns a cache dependency object.
Returns
trackActivity()
- Since
- 4.5.0
Tracks new activity for an element.
Arguments
$element
(craft\base\ElementInterface)$type
(\craft\models\ElementActivity::TYPE_*
) – $type$user
(craft\elements\User, null)
updateCanonicalElement()
- Since
- 3.7.0
Updates the canonical element from a given derivative, such as a draft or revision.
Arguments
$element
(\craft\services\T
) – The derivative element$newAttributes
(array) – Any attributes to apply to the canonical element
Returns
\craft\services\T
– The updated canonical element
Throws
- yii\base\InvalidArgumentException
if the element is already a canonical element
updateDescendantSlugsAndUris()
Updates an element’s descendants’ slugs and URIs.
Arguments
$element
(craft\base\ElementInterface) – The element whose descendants should be updated.$updateOtherSites
(boolean) – Whether the element’s other sites should also be updated.$queue
(boolean) – Whether the descendants’ slugs and URIs should be updated via a job in the queue.
updateElementSlugAndUri()
Updates an element’s slug and URI, along with any descendants.
Arguments
$element
(craft\base\ElementInterface) – The element to update.$updateOtherSites
(boolean) – Whether the element’s other sites should also be updated.$updateDescendants
(boolean) – Whether the element’s descendants should also be updated.$queue
(boolean) – Whether the element’s slug and URI should be updated via a job in the queue.
Throws
- craft\errors\OperationAbortedException
if a unique URI can’t be generated based on the element’s URI format
updateElementSlugAndUriInOtherSites()
Updates an element’s slug and URI, for any sites besides the given one.
Arguments
$element
(craft\base\ElementInterface) – The element to update.
Events
EVENT_AFTER_DELETE_ELEMENT
The event that is triggered after an element is deleted.
EVENT_AFTER_DELETE_FOR_SITE
- Type
- craft\events\ElementEvent
- Since
- 4.4.0
The event that is triggered after deleting an element for a single site.
See also:
EVENT_AFTER_MERGE_CANONICAL_CHANGES
- Type
- craft\events\ElementEvent
- Since
- 3.7.0
The event that is triggered after canonical element changes are merged into a derivative.
EVENT_AFTER_MERGE_ELEMENTS
The event that is triggered after two elements are merged together.
EVENT_AFTER_PERFORM_ACTION
The event that is triggered after an element action is performed.
EVENT_AFTER_PROPAGATE_ELEMENT
The event that is triggered after an element is propagated.
EVENT_AFTER_PROPAGATE_ELEMENTS
The event that is triggered after propagating a batch of elements.
EVENT_AFTER_RESAVE_ELEMENT
The event that is triggered after an element is resaved.
EVENT_AFTER_RESAVE_ELEMENTS
The event that is triggered after resaving a batch of elements.
EVENT_AFTER_RESTORE_ELEMENT
- Type
- craft\events\ElementEvent
- Since
- 3.1.0
The event that is triggered after an element is restored.
EVENT_AFTER_SAVE_ELEMENT
The event that is triggered after an element is saved.
If you want to ignore events for drafts or revisions, call craft\helpers\ElementHelper::isDraftOrRevision() from your event handler:
use craft\events\ElementEvent;
use craft\helpers\ElementHelper;
use craft\services\Elements;
Craft::$app->elements->on(Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $e) {
if (ElementHelper::isDraftOrRevision($e->element)) {
return;
}
// ...
});
EVENT_AFTER_UPDATE_SLUG_AND_URI
The event that is triggered after an element’s slug and URI are updated, usually following a Structure move.
EVENT_AUTHORIZE_CREATE_DRAFTS
- Type
- craft\events\AuthorizationCheckEvent
- Since
- 4.3.0
The event that is triggered when determining whether a user is authorized to create drafts for an element.
To authorize the user, set craft\events\AuthorizationCheckEvent::$authorized to true
.
use craft\events\AuthorizationCheckEvent;
use craft\services\Elements;
use yii\base\Event;
Event::on(
Elements::class,
Elements::EVENT_AUTHORIZE_CREATE_DRAFTS,
function(AuthorizationCheckEvent $event) {
$event->authorized = true;
}
);
See also canCreateDrafts()
EVENT_AUTHORIZE_DELETE
- Type
- craft\events\AuthorizationCheckEvent
- Since
- 4.3.0
The event that is triggered when determining whether a user is authorized to delete an element.
To authorize the user, set craft\events\AuthorizationCheckEvent::$authorized to true
.
use craft\events\AuthorizationCheckEvent;
use craft\services\Elements;
use yii\base\Event;
Event::on(
Elements::class,
Elements::EVENT_AUTHORIZE_DELETE,
function(AuthorizationCheckEvent $event) {
$event->authorized = true;
}
);
See also canDelete()
EVENT_AUTHORIZE_DELETE_FOR_SITE
- Type
- craft\events\AuthorizationCheckEvent
- Since
- 4.3.0
The event that is triggered when determining whether a user is authorized to delete an element for its current site.
To authorize the user, set craft\events\AuthorizationCheckEvent::$authorized to true
.
use craft\events\AuthorizationCheckEvent;
use craft\services\Elements;
use yii\base\Event;
Event::on(
Elements::class,
Elements::EVENT_AUTHORIZE_DELETE_FOR_SITE,
function(AuthorizationCheckEvent $event) {
$event->authorized = true;
}
);
See also canDeleteForSite()
EVENT_AUTHORIZE_DUPLICATE
- Type
- craft\events\AuthorizationCheckEvent
- Since
- 4.3.0
The event that is triggered when determining whether a user is authorized to duplicate an element.
To authorize the user, set craft\events\AuthorizationCheckEvent::$authorized to true
.
use craft\events\AuthorizationCheckEvent;
use craft\services\Elements;
use yii\base\Event;
Event::on(
Elements::class,
Elements::EVENT_AUTHORIZE_DUPLICATE,
function(AuthorizationCheckEvent $event) {
$event->authorized = true;
}
);
See also canDuplicate()
EVENT_AUTHORIZE_SAVE
- Type
- craft\events\AuthorizationCheckEvent
- Since
- 4.3.0
The event that is triggered when determining whether a user is authorized to save an element in its current state.
To authorize the user, set craft\events\AuthorizationCheckEvent::$authorized to true
.
use craft\events\AuthorizationCheckEvent;
use craft\services\Elements;
use yii\base\Event;
Event::on(
Elements::class,
Elements::EVENT_AUTHORIZE_SAVE,
function(AuthorizationCheckEvent $event) {
$event->authorized = true;
}
);
See also canSave()
EVENT_AUTHORIZE_VIEW
- Type
- craft\events\AuthorizationCheckEvent
- Since
- 4.3.0
The event that is triggered when determining whether a user is authorized to view an element’s edit page.
To authorize the user, set craft\events\AuthorizationCheckEvent::$authorized to true
.
use craft\events\AuthorizationCheckEvent;
use craft\services\Elements;
use yii\base\Event;
Event::on(
Elements::class,
Elements::EVENT_AUTHORIZE_VIEW,
function(AuthorizationCheckEvent $event) {
$event->authorized = true;
}
);
See also canView()
EVENT_BEFORE_DELETE_ELEMENT
The event that is triggered before an element is deleted.
EVENT_BEFORE_DELETE_FOR_SITE
- Type
- craft\events\ElementEvent
- Since
- 4.4.0
The event that is triggered before deleting an element for a single site.
See also:
EVENT_BEFORE_EAGER_LOAD_ELEMENTS
- Type
- craft\events\EagerLoadElementsEvent
- Since
- 3.5.0
The event that is triggered before elements are eager-loaded.
EVENT_BEFORE_MERGE_CANONICAL_CHANGES
- Type
- craft\events\ElementEvent
- Since
- 3.7.0
The event that is triggered before canonical element changes are merged into a derivative.
EVENT_BEFORE_PERFORM_ACTION
The event that is triggered before an element action is performed.
You may set craft\events\CancelableEvent::$isValid to false
to prevent the action from being performed.
EVENT_BEFORE_PROPAGATE_ELEMENT
The event that is triggered before an element is propagated.
EVENT_BEFORE_PROPAGATE_ELEMENTS
The event that is triggered before propagating a batch of elements.
EVENT_BEFORE_RESAVE_ELEMENT
The event that is triggered before an element is resaved.
EVENT_BEFORE_RESAVE_ELEMENTS
The event that is triggered before resaving a batch of elements.
EVENT_BEFORE_RESTORE_ELEMENT
- Type
- craft\events\ElementEvent
- Since
- 3.1.0
The event that is triggered before an element is restored.
EVENT_BEFORE_SAVE_ELEMENT
The event that is triggered before an element is saved.
If you want to ignore events for drafts or revisions, call craft\helpers\ElementHelper::isDraftOrRevision() from your event handler:
use craft\events\ElementEvent;
use craft\helpers\ElementHelper;
use craft\services\Elements;
Craft::$app->elements->on(Elements::EVENT_BEFORE_SAVE_ELEMENT, function(ElementEvent $e) {
if (ElementHelper::isDraftOrRevision($e->element)) {
return;
}
// ...
});
EVENT_BEFORE_UPDATE_SEARCH_INDEX
- Type
- craft\events\ElementEvent
- Since
- 3.7.12
The event that is triggered before indexing an element’s search keywords, or queuing the element’s search keywords to be updated.
You may set craft\events\CancelableEvent::$isValid to false
to prevent the search index from being updated.
EVENT_BEFORE_UPDATE_SLUG_AND_URI
The event that is triggered before an element’s slug and URI are updated, usually following a Structure move.
EVENT_INVALIDATE_CACHES
- Type
- craft\events\InvalidateElementCachesEvent
- Since
- 4.2.0
The event that is triggered when element caches are invalidated.
EVENT_REGISTER_ELEMENT_TYPES
The event that is triggered when registering element types.
Element types must implement craft\base\ElementInterface. craft\base\Element provides a base implementation.
See Element Types for documentation on creating element types.
Example
use craft\events\RegisterComponentTypesEvent;
use craft\services\Elements;
use yii\base\Event;
Event::on(Elements::class,
Elements::EVENT_REGISTER_ELEMENT_TYPES,
function(RegisterComponentTypesEvent $event) {
$event->types[] = MyElementType::class;
}
);
EVENT_SET_ELEMENT_URI
- Type
- craft\events\ElementEvent
- Since
- 4.6.0
The event that is triggered when setting a unique URI on an element.
Event handlers must set $event->handled
to true
for their change to take effect.
See also setElementUri()