Craft 3 Class Reference

Class craft\services\Elements

Inheritance
craft\services\Elements » yii\base\Component » yii\base\BaseObject
Implements
yii\base\Configurable
Available since version
3.0
Source Code
https://github.com/craftcms/cms/blob/master/src/services/Elements.php

The Elements service provides APIs for managing elements.

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

Public Methods
Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
createAction() Creates an element action with a given config. craft\services\Elements
createElement() Creates an element with a given config. craft\services\Elements
deleteElement() Deletes an element. craft\services\Elements
deleteElementById() Deletes an element by its ID. craft\services\Elements
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
duplicateElement() Duplicates an element. craft\services\Elements
eagerLoadElements() Eager-loads additional elements onto a given set of elements. craft\services\Elements
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getAllElementTypes() Returns all available element classes. craft\services\Elements
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getElementById() Returns an element by its ID. craft\services\Elements
getElementByUri() Returns an element by its URI. craft\services\Elements
getElementTypeById() Returns the class of an element with a given ID. craft\services\Elements
getElementTypeByRefHandle() Returns an element class by its handle. craft\services\Elements
getElementTypesByIds() Returns the classes of elements with the given IDs. craft\services\Elements
getElementUriForSite() Returns an element’s URI for a given site. craft\services\Elements
getEnabledSiteIdsForElement() Returns the site IDs that a given element is enabled in. craft\services\Elements
getPlaceholderElement() Returns a placeholder element by its ID and site ID. craft\services\Elements
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
mergeElementsByIds() Merges two elements together. craft\services\Elements
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
parseRefs() Parses a string for element reference tags. craft\services\Elements
saveElement() Handles all of the routine tasks that go along with saving elements. craft\services\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. craft\services\Elements
trigger() Triggers an event. yii\base\Component
updateDescendantSlugsAndUris() Updates an element’s descendants’ slugs and URIs. craft\services\Elements
updateElementSlugAndUri() Updates an element’s slug and URI, along with any descendants. craft\services\Elements
updateElementSlugAndUriInOtherSites() Updates an element’s slug and URI, for any sites besides the given one. craft\services\Elements
Events
Event Type Description Defined By
EVENT_AFTER_DELETE_ELEMENT craft\events\ElementEvent The event that is triggered after an element is deleted. craft\services\Elements
EVENT_AFTER_MERGE_ELEMENTS craft\events\MergeElementsEvent The event that is triggered after two elements are merged together. craft\services\Elements
EVENT_AFTER_PERFORM_ACTION \craft\services\ElementActionEvent The event that is triggered after an element action is performed. craft\services\Elements
EVENT_AFTER_SAVE_ELEMENT craft\events\ElementEvent The event that is triggered after an element is saved. craft\services\Elements
EVENT_AFTER_UPDATE_SLUG_AND_URI craft\events\ElementEvent The event that is triggered after an element’s slug and URI are updated, usually following a Structure move. craft\services\Elements
EVENT_BEFORE_DELETE_ELEMENT craft\events\ElementEvent The event that is triggered before an element is deleted. craft\services\Elements
EVENT_BEFORE_PERFORM_ACTION \craft\services\ElementActionEvent The event that is triggered before an element action is performed. craft\services\Elements
EVENT_BEFORE_SAVE_ELEMENT craft\events\ElementEvent The event that is triggered before an element is saved. craft\services\Elements
EVENT_BEFORE_UPDATE_SLUG_AND_URI craft\events\ElementEvent The event that is triggered before an element’s slug and URI are updated, usually following a Structure move. craft\services\Elements
EVENT_REGISTER_ELEMENT_TYPES craft\events\RegisterComponentTypesEvent The event that is triggered when registering element types. craft\services\Elements

Method Details

createAction() public method #

Creates an element action with a given config.

public craft\base\ElementActionInterface createAction ( $config )
$config mixed The element action’s class name, or its config, with a type value and optionally a settings value
return craft\base\ElementActionInterface The element action

createElement() public method #

Creates an element with a given config.

public craft\base\ElementInterface createElement ( $config )
$config mixed The field’s class name, or its config, with a type value and optionally a settings value
return craft\base\ElementInterface The element

deleteElement() public method #

Deletes an element.

public boolean deleteElement ( craft\base\ElementInterface $element )
$element craft\base\ElementInterface The element to be deleted
return boolean Whether the element was deleted successfully
throws Throwable

deleteElementById() public method #

Deletes an element by its ID.

public boolean deleteElementById ( \craft\services\int $elementId, \craft\services\string $elementType null, \craft\services\int $siteId null )
$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.
return boolean Whether the element was deleted successfully
throws Throwable

duplicateElement() public method #

Duplicates an element.

public craft\base\ElementInterface duplicateElement ( craft\base\ElementInterface $element, array $newAttributes = [] )
$element craft\base\ElementInterface The element to duplicate
$newAttributes array Any attributes to apply to the duplicate
return craft\base\ElementInterface The duplicated element
throws craft\errors\InvalidElementException if saveElement() returns false for any of the sites
throws Throwable if reasons

eagerLoadElements() public method #

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

public void eagerLoadElements ( \craft\services\string $elementType, array $elements, $with )
$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() public method #

Returns all available element classes.

public string[] getAllElementTypes ( )
return string[] The available element classes.

getElementById() public method #

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.

public craft\base\ElementInterface, null getElementById ( \craft\services\int $elementId, \craft\services\string $elementType null, \craft\services\int $siteId null )
$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.
return craft\base\ElementInterface, null The matching element, or null.

getElementByUri() public method #

Returns an element by its URI.

public craft\base\ElementInterface, null getElementByUri ( \craft\services\string $uri, \craft\services\int $siteId null, \craft\services\bool $enabledOnly false )
$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.
return craft\base\ElementInterface, null The matching element, or null.

getElementTypeById() public method #

Returns the class of an element with a given ID.

public string, null getElementTypeById ( \craft\services\int $elementId )
$elementId integer The element’s ID
return string, null The element’s class, or null if it could not be found

getElementTypeByRefHandle() public method #

Returns an element class by its handle.

public string, null getElementTypeByRefHandle ( \craft\services\string $refHandle )
$refHandle string The element class handle
return string, null The element class, or null if it could not be found

getElementTypesByIds() public method #

Returns the classes of elements with the given IDs.

public string[] getElementTypesByIds ( array $elementIds )
$elementIds integer[] The elements’ IDs

getElementUriForSite() public method #

Returns an element’s URI for a given site.

public string, null getElementUriForSite ( \craft\services\int $elementId, \craft\services\int $siteId )
$elementId integer The element’s ID.
$siteId integer The site to search for the element’s URI in.
return string, null The element’s URI, or null.

getEnabledSiteIdsForElement() public method #

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

public integer[] getEnabledSiteIdsForElement ( \craft\services\int $elementId )
$elementId integer The element’s ID.
return integer[] The site IDs that the element is enabled in. If the element could not be found, an empty array will be returned.

getPlaceholderElement() public method #

Returns a placeholder element by its ID and site ID.

See also setPlaceholderElement().

public craft\base\ElementInterface, null getPlaceholderElement ( \craft\services\int $id, \craft\services\int $siteId )
$id integer The element’s ID
$siteId integer The element’s site ID
return craft\base\ElementInterface, null The placeholder element if one exists, or null.

mergeElementsByIds() public method #

Merges two elements together.

This method will update the following:

public boolean mergeElementsByIds ( \craft\services\int $mergedElementId, \craft\services\int $prevailingElementId )
$mergedElementId integer The ID of the element that is going away.
$prevailingElementId integer The ID of the element that is sticking around.
return boolean Whether the elements were merged successfully.
throws Throwable if reasons

parseRefs() public method #

Parses a string for element reference tags.

public string parseRefs ( \craft\services\string $str, \craft\services\int $siteId null )
$str string The string to parse
$siteId integer, null The site ID to query the elements in
return string The parsed string

saveElement() public method #

Handles all of the routine tasks that go along with saving elements.

Those tasks include:

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->fieldLayoutId = $entry->getType()->fieldLayoutId;
$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__);
}
public boolean saveElement ( craft\base\ElementInterface $element, \craft\services\bool $runValidation true, \craft\services\bool $propagate true )
$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
throws craft\errors\ElementNotFoundException if $element has an invalid $id
throws yii\base\Exception if the $element doesn’t have any supported sites
throws Throwable if reasons

setPlaceholderElement() public method #

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().

public void setPlaceholderElement ( craft\base\ElementInterface $element )
$element craft\base\ElementInterface The element currently being edited by Live Preview.

updateDescendantSlugsAndUris() public method #

Updates an element’s descendants’ slugs and URIs.

public void updateDescendantSlugsAndUris ( craft\base\ElementInterface $element, \craft\services\bool $updateOtherSites true, \craft\services\bool $queue false )
$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() public method #

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

public void updateElementSlugAndUri ( craft\base\ElementInterface $element, \craft\services\bool $updateOtherSites true, \craft\services\bool $updateDescendants true, \craft\services\bool $queue false )
$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() public method #

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

public void updateElementSlugAndUriInOtherSites ( craft\base\ElementInterface $element )
$element craft\base\ElementInterface The element to update.

Event Details

EVENT_AFTER_DELETE_ELEMENT event of type craft\events\ElementEvent #

The event that is triggered after an element is deleted.

EVENT_AFTER_MERGE_ELEMENTS event of type craft\events\MergeElementsEvent #

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

EVENT_AFTER_PERFORM_ACTION event of type \craft\services\ElementActionEvent #

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

EVENT_AFTER_SAVE_ELEMENT event of type craft\events\ElementEvent #

The event that is triggered after an element is saved.

EVENT_AFTER_UPDATE_SLUG_AND_URI event of 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 event of type craft\events\ElementEvent #

The event that is triggered before an element is deleted.

EVENT_BEFORE_PERFORM_ACTION event of 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_SAVE_ELEMENT event of type craft\events\ElementEvent #

The event that is triggered before an element is saved.

EVENT_BEFORE_UPDATE_SLUG_AND_URI event of 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 event of type craft\events\RegisterComponentTypesEvent #

The event that is triggered when registering element types.