Elements

Type
Class
Namespace
craft\services
Inherits
craft\services\Elements » yii\base\Component » yii\base\BaseObject
Implements
yii\base\Configurable
Since
3.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

Public Properties

PropertyDescription
allElementTypesstring[] – The available element classes.
behaviorsyii\base\Behavior – List of behaviors attached to this component
duplicatedElementIdsarray – Stores a mapping of element IDs to their duplicated element ID(s).
placeholderElementcraft\base\ElementInterface – The element currently being edited by Live Preview.

allElementTypes

Type
string[]
Access
Read-only

The available element classes.

View source

duplicatedElementIds

Type
array

Stores a mapping of element IDs to their duplicated element ID(s).

View source

placeholderElement

Type
craft\base\ElementInterface
Access
Write-only

The element currently being edited by Live Preview.

View source

Public Methods

MethodDescription
__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 an object property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets value of an object property.
__unset()Sets an object property to 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.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
createAction()Creates an element action with a given config.
createElement()Creates an element with a given config.
deleteElement()Deletes an element.
deleteElementById()Deletes an element by its ID.
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.
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.
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.
getPlaceholderElement()Returns a placeholder element by its ID and site ID.
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.
init()Initializes the object.
mergeElementsByIds()Merges two elements together.
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.
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 \craft\services\findElements() should use instead of populating a new element with a matching ID and site ID.
trigger()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.

createAction()

Creates an element action with a given config.

View source

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

createElement()

Creates an element with a given config.

View source

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

deleteElement()

Deletes an element.

View source

Arguments

Returns

boolean – Whether the element was deleted successfully

Throws

deleteElementById()

Deletes an element by its ID.

View source

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.

Returns

boolean – Whether the element was deleted successfully

Throws

duplicateElement()

Duplicates an element.

View source

Arguments

Returns

craft\base\ElementInterface – The duplicated element

Throws

eagerLoadElements()

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

View source

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 (string, array) – Dot-delimited paths of the elements that should be eager-loaded into the root elements

getAllElementTypes()

Returns all available element classes.

View source

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.

View source

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.

Returns

craft\base\ElementInterface, null – The matching element, or null.

getElementByUri()

Returns an element by its URI.

View source

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 to false.

Returns

craft\base\ElementInterface, null – The matching element, or null.

getElementTypeById()

Returns the class of an element with a given ID.

View source

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.

View source

Arguments

  • $refHandle (string) – The element class handle

Returns

string, null – The element class, or null if it could not be found

getElementTypesByIds()

Returns the classes of elements with the given IDs.

View source

Arguments

  • $elementIds (integer[]) – The elements’ IDs

Returns

string[]

getElementUriForSite()

Returns an element’s URI for a given site.

View source

Arguments

  • $elementId (integer) – The element’s ID.
  • $siteId (integer) – The site to search for the element’s URI in.

Returns

string, null – The element’s URI, or null.

getEnabledSiteIdsForElement()

Returns the site IDs that a given element is enabled in.

View source

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.

getPlaceholderElement()

Returns a placeholder element by its ID and site ID.

See also setPlaceholderElement()View source

Arguments

  • $id (integer) – The element’s ID
  • $siteId (integer) – The element’s site ID

Returns

craft\base\ElementInterface, null – The placeholder element if one exists, or null.

mergeElementsByIds()

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

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

parseRefs()

Parses a string for element reference tags.

View source

Arguments

  • $str (string) – The string to parse
  • $siteId (integer, null) – The site ID to query the elements in

Returns

string – The parsed string

propagateElement()

Propagates an element to a different site.

View source

Arguments

Throws

restoreElement()

Restores an element.

View source

Arguments

Returns

boolean – Whether the element was restored successfully

Throws

restoreElements()

Restores multiple elements.

View source

Arguments

Returns

boolean – 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

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

Returns

boolean

Throws

setPlaceholderElement()

Stores a placeholder element that \craft\services\findElements() 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

updateDescendantSlugsAndUris()

Updates an element’s descendants’ slugs and URIs.

View source

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.

View source

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.

updateElementSlugAndUriInOtherSites()

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

View source

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\services\ElementActionEvent

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

EVENT_AFTER_RESTORE_ELEMENT

Type
craft\events\ElementEvent

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.

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_PERFORM_ACTION

Type
\craft\services\ElementActionEvent

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

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

EVENT_BEFORE_RESTORE_ELEMENT

Type
craft\events\ElementEvent

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.

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 for documentation on creating element types.

Example