Elements

Type
Class
Namespace
craft\services
Inherits
craft\services\Elements » yii\base\Component (opens new window) » yii\base\BaseObject (opens new window)
Implements
yii\base\Configurable (opens new window)
Since
3.0.0

The Elements service provides APIs for managing elements.

An instance of the Elements service is globally accessible in Craft via Craft::$app->elements.

View source (opens new window)

# Public Properties

Property Description
allElementTypes string (opens new window)[] – The available element classes.
behaviors (opens new window) yii\base\Behavior (opens new window) – List of behaviors attached to this component
duplicatedElementIds integer (opens new window)[] – Stores a mapping of source element IDs to their duplicated element IDs.
duplicatedElementSourceIds integer (opens new window)[] – Stores a mapping of duplicated element IDs to their source element IDs.
isCollectingCacheTags boolean (opens new window)
placeholderElement craft\base\ElementInterface – The element currently being edited by Live Preview.
placeholderElements craft\base\ElementInterface[]

# allElementTypes

Type
string (opens new window)[]
Default value
null
Access
Read-only

The available element classes.

View source (opens new window)

# duplicatedElementIds

Type
integer (opens new window)[]
Default value
[]

Stores a mapping of source element IDs to their duplicated element IDs.

View source (opens new window)

# duplicatedElementSourceIds

Type
integer (opens new window)[]
Default value
[]
Since
3.4.0

Stores a mapping of duplicated element IDs to their source element IDs.

View source (opens new window)

# isCollectingCacheTags

Type
boolean (opens new window)
Default value
null
Access
Read-only
Since
3.5.0

View source (opens new window)

# placeholderElement

Type
craft\base\ElementInterface
Default value
null
Access
Write-only

The element currently being edited by Live Preview.

View source (opens new window)

# placeholderElements

Type
craft\base\ElementInterface[]
Default value
null
Access
Read-only
Since
3.2.5

View source (opens new window)

# Public Methods

Method Description
__call() (opens new window) Calls the named method which is not a class method.
__clone() (opens new window) This method is called after the object is created by cloning an existing one.
__construct() (opens new window) Constructor.
__get() (opens new window) Returns the value of an object property.
__isset() (opens new window) Checks if a property is set, i.e. defined and not null.
__set() (opens new window) Sets value of an object property.
__unset() (opens new window) Sets an object property to null.
attachBehavior() (opens new window) Attaches a behavior to this component.
attachBehaviors() (opens new window) Attaches a list of behaviors to the component.
behaviors() (opens new window) Returns a list of behaviors that this component should behave as.
canGetProperty() (opens new window) Returns a value indicating whether a property can be read.
canSetProperty() (opens new window) Returns a value indicating whether a property can be set.
className() (opens new window) Returns the fully qualified name of this class.
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.
detachBehavior() (opens new window) Detaches a behavior from the component.
detachBehaviors() (opens new window) Detaches all behaviors from the component.
duplicateElement() Duplicates an element.
eagerLoadElements() Eager-loads additional elements onto a given set of elements.
ensureBehaviors() (opens new window) Makes sure that the behaviors declared in behaviors() (opens new window) are attached to this component.
getAllElementTypes() Returns all available element classes.
getBehavior() (opens new window) Returns the named behavior object.
getBehaviors() (opens new window) 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.
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.
hasEventHandlers() (opens new window) Returns a value indicating whether there is any handler attached to the named event.
hasMethod() (opens new window) Returns a value indicating whether a method is defined.
hasProperty() (opens new window) Returns a value indicating whether a property is defined.
init() (opens new window) Initializes the object.
invalidateAllCaches() Invalidates all element caches.
invalidateCachesForElement() Invalidates caches for the given element.
invalidateCachesForElementType() Invalidates caches for the given element type.
mergeElements() Merges two elements together.
mergeElementsByIds() Merges two elements together by their IDs.
off() (opens new window) Detaches an existing event handler from this component.
on() (opens new window) Attaches an event handler to an event.
parseRefs() Parses a string for element reference tags (opens new window).
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.
setPlaceholderElement() Stores a placeholder element that element queries should use instead of populating a new element with a matching ID and site ID.
startCollectingCacheTags() Starts collecting element cache invalidation tags.
stopCollectingCacheTags() Stops collecting element cache invalidation tags, and returns a cache dependency object.
trigger() (opens new window) Triggers an event.
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.

# collectCacheTags()

Since
3.5.0

Adds element cache invalidation tags to the current collection.

View source (opens new window)

Arguments

# createAction()

Creates an element action with a given config.

View source (opens new window)

Arguments

  • $config (mixed) – The element action’s class name, or its config, with a type value and optionally a settings value

Returns

craft\base\ElementActionInterface – The element action

# createEagerLoadingPlans()

Since
3.5.0

Normalizes a with element query param into an array of eager-loading plans.

View source (opens new window)

Arguments

  • $with

Returns

craft\elements\db\EagerLoadPlan[]

# createElement()

Creates an element with a given config.

View source (opens new window)

Arguments

  • $config (mixed) – The field’s class name, or its config, with a type value and optionally a settings value

Returns

craft\base\ElementInterface – The element

# createElementQuery()

Since
3.5.0

Creates an element query for a given element type.

View source (opens new window)

Arguments

Returns

craft\elements\db\ElementQueryInterface – The element query

Throws

# createExporter()

Creates an element exporter with a given config.

View source (opens new window)

Arguments

  • $config (mixed) – The element exporter’s class name, or its config, with a type value and optionally a settings value

Returns

craft\base\ElementExporterInterface – The element exporter

# deleteElement()

Deletes an element.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the element was deleted successfully

Throws

# deleteElementById()

Deletes an element by its ID.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the element was deleted successfully

Throws

# duplicateElement()

Duplicates an element.

View source (opens new window)

Arguments

Returns

craft\base\ElementInterface – The duplicated element

Throws

# eagerLoadElements()

Eager-loads additional elements onto a given set of elements.

View source (opens new window)

Arguments

# getAllElementTypes()

Returns all available element classes.

View source (opens new window)

Returns

string (opens new window)[] – 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.

View source (opens new window)

Arguments

Returns

craft\base\ElementInterface, null (opens new window) – 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.

View source (opens new window)

Arguments

Returns

craft\base\ElementInterface, null (opens new window) – The matching element, or null.

# getElementByUri()

Returns an element by its URI.

View source (opens new window)

Arguments

Returns

craft\base\ElementInterface, null (opens new window) – The matching element, or null.

# getElementTypeById()

Returns the class of an element with a given ID.

View source (opens new window)

Arguments

Returns

string (opens new window), null (opens new window) – The element’s class, or null if it could not be found

# getElementTypeByRefHandle()

Returns an element class by its handle.

View source (opens new window)

Arguments

Returns

string (opens new window), null (opens new window) – 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.

View source (opens new window)

Arguments

Returns

string (opens new window), null (opens new window) – The element’s class, or null if it could not be found

# getElementTypesByIds()

Returns the classes of elements with the given IDs.

View source (opens new window)

Arguments

Returns

string (opens new window)[]

# getElementUriForSite()

Returns an element’s URI for a given site.

View source (opens new window)

Arguments

Returns

string (opens new window), null (opens new window), false (opens new window) – 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.

View source (opens new window)

Arguments

Returns

integer (opens new window)[] – The site IDs that the element is enabled in. If the element could not be found, an empty array will be returned.

# getIsCollectingCacheTags()

Since
3.5.0

Returns whether we are currently collecting element cache invalidation tags.

See also:

View source (opens new window)

Returns

boolean (opens new window)

# getPlaceholderElement()

Returns a placeholder element by its ID and site ID.

See also setPlaceholderElement() View source (opens new window)

Arguments

Returns

craft\base\ElementInterface, null (opens new window) – The placeholder element if one exists, or null.

# getPlaceholderElements()

Since
3.2.5

Returns all placeholder elements.

View source (opens new window)

Returns

craft\base\ElementInterface[]

# invalidateAllCaches()

Since
3.5.0

Invalidates all element caches.

View source (opens new window)

# invalidateCachesForElement()

Since
3.5.0

Invalidates caches for the given element.

View source (opens new window)

Arguments

# invalidateCachesForElementType()

Since
3.5.0

Invalidates caches for the given element type.

View source (opens new window)

Arguments

# 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

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the elements were merged successfully.

Throws

# 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

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the elements were merged successfully.

Throws

# parseRefs()

Parses a string for element reference tags (opens new window).

View source (opens new window)

Arguments

Returns

string (opens new window) – The parsed string

# propagateElement()

Since
3.0.13

Propagates an element to a different site.

View source (opens new window)

Arguments

Throws

# propagateElements()

Since
3.2.0

Propagates all elements that match a given element query to another site(s).

View source (opens new window)

Arguments

Throws

# resaveElements()

Since
3.2.0

Resaves all elements that match a given element query.

View source (opens new window)

Arguments

Throws

# restoreElement()

Since
3.1.0

Restores an element.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the element was restored successfully

Throws

# restoreElements()

Restores multiple elements.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether at least one element was restored successfully

Throws

# 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 as null 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 and content tables
  • Deleting any rows in the elements_sites and content 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__);
}

View source (opens new window)

Arguments

Returns

boolean (opens new window)

Throws

# 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 (opens new window)

Arguments

Throws

# startCollectingCacheTags()

Since
3.5.0

Starts collecting element cache invalidation tags.

View source (opens new window)

# stopCollectingCacheTags()

Since
3.5.0

Stops collecting element cache invalidation tags, and returns a cache dependency object.

View source (opens new window)

Returns

yii\caching\TagDependency (opens new window)

# updateDescendantSlugsAndUris()

Updates an element’s descendants’ slugs and URIs.

View source (opens new window)

Arguments

# updateElementSlugAndUri()

Updates an element’s slug and URI, along with any descendants.

View source (opens new window)

Arguments

# updateElementSlugAndUriInOtherSites()

Updates an element’s slug and URI, for any sites besides the given one.

View source (opens new window)

Arguments

# Events

# EVENT_AFTER_DELETE_ELEMENT

Type
craft\events\ElementEvent

The event that is triggered after an element is deleted.

# EVENT_AFTER_MERGE_ELEMENTS

Type
craft\events\MergeElementsEvent

The event that is triggered after two elements are merged together.

# EVENT_AFTER_PERFORM_ACTION

Type
craft\events\ElementActionEvent

The event that is triggered after an element action is performed.

# EVENT_AFTER_PROPAGATE_ELEMENT

Type
craft\events\BatchElementActionEvent

The event that is triggered after an element is propagated.

# EVENT_AFTER_PROPAGATE_ELEMENTS

Type
craft\events\ElementQueryEvent

The event that is triggered after propagating a batch of elements.

# EVENT_AFTER_RESAVE_ELEMENT

Type
craft\events\BatchElementActionEvent

The event that is triggered after an element is resaved.

# EVENT_AFTER_RESAVE_ELEMENTS

Type
craft\events\ElementQueryEvent

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

Type
craft\events\ElementEvent

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

Type
craft\events\ElementEvent

The event that is triggered after an element’s slug and URI are updated, usually following a Structure move.

# EVENT_BEFORE_DELETE_ELEMENT

Type
craft\events\DeleteElementEvent

The event that is triggered before an element is deleted.

# 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_PERFORM_ACTION

Type
craft\events\ElementActionEvent

The event that is triggered before an element action is performed.

You may set craft\events\ElementActionEvent::$isValid to false to prevent the action from being performed.

# EVENT_BEFORE_PROPAGATE_ELEMENT

Type
craft\events\BatchElementActionEvent

The event that is triggered before an element is propagated.

# EVENT_BEFORE_PROPAGATE_ELEMENTS

Type
craft\events\ElementQueryEvent

The event that is triggered before propagating a batch of elements.

# EVENT_BEFORE_RESAVE_ELEMENT

Type
craft\events\BatchElementActionEvent

The event that is triggered before an element is resaved.

# EVENT_BEFORE_RESAVE_ELEMENTS

Type
craft\events\ElementQueryEvent

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

Type
craft\events\ElementEvent

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_SLUG_AND_URI

Type
craft\events\ElementEvent

The event that is triggered before an element’s slug and URI are updated, usually following a Structure move.

# EVENT_REGISTER_ELEMENT_TYPES

Type
craft\events\RegisterComponentTypesEvent

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 (opens new window) 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;
    }
);