ElementsService

Type
Class
Namespace
Craft
Inherits
Craft\ElementsService » Craft\BaseApplicationComponent » CApplicationComponent » CComponent
Implements
IApplicationComponent
Since
1.0

ElementsService provides APIs for managing elements.

An instance of ElementsService is globally accessible in Craft via {@link WebApp::elements craft()->elements}.

See also http://craftcms.com

View source

Public Properties

PropertyDescription
$behaviorsarray – The behaviors that should be attached to this component.

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__get()Returns a property value, an event handler list or a behavior based on its name.
__isset()Checks if a property value is null.
__set()Sets value of a component property.
__unset()Sets a component property to be null.
asa()Returns the named behavior object.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
attachEventHandler()Attaches an event handler to an event.
buildElementsQuery()Preps a {@link DbCommand} object for querying for elements, based on a given element criteria.
canGetProperty()Determines whether a property can be read.
canSetProperty()Determines whether a property can be set.
deleteElementById()Deletes an element(s) by its ID(s).
deleteElementsByType()Deletes elements by a given type.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
detachEventHandler()Detaches an existing event handler.
disableBehavior()Disables an attached behavior.
disableBehaviors()Disables all behaviors attached to this component.
eagerLoadElements()Eager-loads additional elements onto a given set of elements.
enableBehavior()Enables an attached behavior.
enableBehaviors()Enables all behaviors attached to this component.
evaluateExpression()Evaluates a PHP expression or callback under the context of this component.
findElements()Finds elements.
getAction()Returns an element action by its class handle.
getAllActions()Returns all installed element actions.
getAllElementTypes()Returns all installed element types.
getCriteria()Returns an element criteria model for a given element type.
getElementById()Returns an element by its ID.
getElementByUri()Returns an element by its URI.
getElementType()Returns an element type by its class handle.
getElementTypeById()Returns the element type(s) used by the element of a given ID(s).
getElementUriForLocale()Returns an element’s URI for a given locale.
getEnabledLocalesForElement()Returns the locales that a given element is enabled in.
getEventHandlers()Returns the list of attached event handlers for an event.
getIsInitialized()Checks if this application component has been initialized.
getTotalElements()Returns the total number of elements that match a given criteria.
handleRequestEnd()Perform element clean-up work.
hasEvent()Determines whether an event is defined.
hasEventHandler()Checks whether the named event has attached handlers.
hasProperty()Determines whether a property is defined.
init()Initializes the application component.
isInitialized()Checks if this application component has been initialized yet, or not.
mergeElementsByIds()Merges two elements together.
onBeforeBuildElementsQuery()Fires an 'onBeforeBuildElementsQuery' event.
onBeforeDeleteElements()Fires an 'onBeforeDeleteElements' event.
onBeforePerformAction()Fires an 'onBeforePerformAction' event.
onBeforeSaveElement()Fires an 'onBeforeSaveElement' event.
onBuildElementsQuery()Fires an 'onBuildElementsQuery' event.
onMergeElements()Fires an 'onMergeElements' event.
onPerformAction()Fires an 'onPerformAction' event.
onPopulateElement()Fires an 'onPopulateElement' event.
onPopulateElements()Fires an 'onPopulateElements' event.
onSaveElement()Fires an 'onSaveElement' event.
parseRefs()Parses a string for element reference tags.
populateElements()Populates element models from a given element query's result set.
raiseEvent()Raises an event.
saveElement()Handles all of the routine tasks that go along with saving elements.
setPlaceholderElement()Stores a placeholder element that {@link findElements()} should use instead of populating a new element with a matching ID and locale.
updateDescendantSlugsAndUris()Updates an element’s descendants’ slugs and URIs.
updateElementSlugAndUri()Updates an element’s slug and URI, along with any descendants.
updateElementSlugAndUriInOtherLocales()Updates an element’s slug and URI, for any locales besides the given one.

buildElementsQuery()

Preps a {@link DbCommand} object for querying for elements, based on a given element criteria.

View source

Arguments

  • $criteria
  • $contentTable
  • $fieldColumns
  • $justIds (boolean) – Whether the method should only return an array of the IDs of the matched elements. Defaults to false.

Returns

Craft\DbCommand, false – The DbCommand object, or false if the method was able to determine ahead of time that there’s no chance any elements are going to be found with the given parameters.

Signature

public Craft\DbCommand, false buildElementsQuery ( &$criteria = null, &$contentTable = null, &$fieldColumns = null, $justIds = false )

deleteElementById()

Deletes an element(s) by its ID(s).

View source

Arguments

  • $elementIds (integer, array) – The element’s ID, or an array of elements’ IDs.

Returns

boolean – Whether the element(s) were deleted successfully.

Throws

Signature

public boolean deleteElementById ( $elementIds )

deleteElementsByType()

Deletes elements by a given type.

View source

Arguments

  • $type (string) – The element type class handle.

Returns

boolean – Whether the elements were deleted successfully.

Signature

public boolean deleteElementsByType ( $type )

eagerLoadElements()

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

View source

Arguments

  • $elementType (Craft\BaseElementType) – The root element type
  • $elements (Craft\BaseElementModel[]) – 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

Returns

void

Signature

public void eagerLoadElements ( Craft\BaseElementType $elementType, $elements, $with )

findElements()

Finds elements.

View source

Arguments

  • $criteria (Craft\ElementCriteriaModel) – An element criteria model that defines the parameters for the elements we should be looking for.
  • $justIds (boolean) – Whether the method should only return an array of the IDs of the matched elements. Defaults to false.

Returns

array – The matched elements, or their IDs, depending on $justIds.

Signature

public array findElements ( $criteria = null, $justIds = false )

getAction()

Returns an element action by its class handle.

View source

Arguments

  • $class (string) – The element action class handle.

Returns

Craft\IElementAction, null – The element action, or null.

Signature

public Craft\IElementAction, null getAction ( $class )

getAllActions()

Returns all installed element actions.

View source

Returns

Craft\IElementAction[] – The installed element actions.

Signature

public Craft\IElementAction[] getAllActions ( )

getAllElementTypes()

Returns all installed element types.

View source

Returns

Craft\IElementType[] – The installed element types.

Signature

public Craft\IElementType[] getAllElementTypes ( )

getCriteria()

Returns an element criteria model for a given element type. This should be the starting point any time you want to fetch elements in Craft.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'news';
$entries = $criteria->find();

View source

Arguments

  • $type (string) – The element type class handle (e.g. one of the values in the {@link ElementType} enum).
  • $attributes (mixed) – Any criteria attribute values that should be pre-populated on the criteria model.

Returns

Craft\ElementCriteriaModel – An element criteria model, wired to fetch elements of the given $type.

Throws

Signature

public Craft\ElementCriteriaModel getCriteria ( $type, $attributes = null )

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 $elementId 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 (null) – The element type’s class handle.
  • $localeId (string) – The locale to fetch the element in. Defaults to {@link WebApp::language craft()->language}.

Returns

Craft\BaseElementModel, null – The matching element, or null.

Signature

public Craft\BaseElementModel, null getElementById ( $elementId, $elementType = null, $localeId = null )

getElementByUri()

Returns an element by its URI.

View source

Arguments

  • $uri (string) – The element’s URI.
  • $localeId (string, null) – The locale to look for the URI in, and to return the element in. Defaults to {@link WebApp::language craft()->language}.
  • $enabledOnly (boolean) – Whether to only look for an enabled element. Defaults to false.

Returns

Craft\BaseElementModel, null – The matching element, or null.

Signature

public Craft\BaseElementModel, null getElementByUri ( $uri, $localeId = null, $enabledOnly = false )

getElementType()

Returns an element type by its class handle.

View source

Arguments

  • $class (string) – The element type class handle.

Returns

Craft\IElementType, null – The element type, or null.

Signature

public Craft\IElementType, null getElementType ( $class )

getElementTypeById()

Returns the element type(s) used by the element of a given ID(s). If a single ID is passed in (an int), then a single element type will be returned (a string), or null if no element exists by that ID.

If an array is passed in, then an array will be returned.

View source

Arguments

  • $elementId (integer, array) – An element’s ID, or an array of elements’ IDs.

Returns

string, array, null – The element type(s).

Signature

public string, array, null getElementTypeById ( $elementId )

getElementUriForLocale()

Returns an element’s URI for a given locale.

View source

Arguments

  • $elementId (integer) – The element’s ID.
  • $localeId (string) – The locale to search for the element’s URI in.

Returns

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

Signature

public string, null getElementUriForLocale ( $elementId, $localeId )

getEnabledLocalesForElement()

Returns the locales that a given element is enabled in.

View source

Arguments

  • $elementId (integer) – The element’s ID.

Returns

array – The locales that the element is enabled in. If the element could not be found, an empty array will be returned.

Signature

public array getEnabledLocalesForElement ( $elementId )

getTotalElements()

Returns the total number of elements that match a given criteria.

View source

Arguments

  • $criteria (Craft\ElementCriteriaModel) – An element criteria model that defines the parameters for the elements we should be counting.

Returns

integer – The total number of elements that match the criteria.

Signature

public integer getTotalElements ( $criteria = null )

handleRequestEnd()

Perform element clean-up work.

View source

Signature

public void handleRequestEnd ( )

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

Signature

public boolean mergeElementsByIds ( $mergedElementId, $prevailingElementId )

onBeforeBuildElementsQuery()

Fires an 'onBeforeBuildElementsQuery' event.

View source

Arguments

Returns

null

Signature

public null onBeforeBuildElementsQuery ( Craft\Event $event )

onBeforeDeleteElements()

Fires an 'onBeforeDeleteElements' event.

View source

Arguments

Returns

null

Signature

public null onBeforeDeleteElements ( Craft\Event $event )

onBeforePerformAction()

Fires an 'onBeforePerformAction' event.

View source

Arguments

Returns

null

Signature

public null onBeforePerformAction ( Craft\Event $event )

onBeforeSaveElement()

Fires an 'onBeforeSaveElement' event.

View source

Arguments

Returns

null

Signature

public null onBeforeSaveElement ( Craft\Event $event )

onBuildElementsQuery()

Fires an 'onBuildElementsQuery' event.

View source

Arguments

Returns

null

Signature

public null onBuildElementsQuery ( Craft\Event $event )

onMergeElements()

Fires an 'onMergeElements' event.

View source

Arguments

Returns

null

Signature

public null onMergeElements ( Craft\Event $event )

onPerformAction()

Fires an 'onPerformAction' event.

View source

Arguments

Returns

null

Signature

public null onPerformAction ( Craft\Event $event )

onPopulateElement()

Fires an 'onPopulateElement' event.

View source

Arguments

Returns

null

Signature

public null onPopulateElement ( Craft\Event $event )

onPopulateElements()

Fires an 'onPopulateElements' event.

View source

Arguments

Returns

null

Signature

public null onPopulateElements ( Craft\Event $event )

onSaveElement()

Fires an 'onSaveElement' event.

View source

Arguments

Returns

null

Signature

public null onSaveElement ( Craft\Event $event )

parseRefs()

Parses a string for element reference tags.

View source

Arguments

  • $str (string) – The string to parse.

Returns

string – The parsed string.

Signature

public string parseRefs ( $str )

populateElements()

Populates element models from a given element query's result set.

View source

Arguments

  • $results (array) – The result set of an element query
  • $criteria (Craft\ElementCriteriaModel) – The element criteria model
  • $contentTable (string) – The content table that was joined in by buildElementsQuery()
  • $fieldColumns (array) – Info about the content field columns being selected

Returns

Craft\BaseElementModel[] – The populated element models.

Signature

public Craft\BaseElementModel[] populateElements ( $results, Craft\ElementCriteriaModel $criteria, $contentTable, $fieldColumns )

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 {@link BaseElementType::hasTitles() 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_i18n and content tables
  • Deleting any rows in the elements_i18n and content tables that no longer need to be there
  • Calling the field types’ {@link BaseFieldType::onAfterElementSave() onAfterElementSave()} methods
  • Cleaing any template caches that the element was involved in

This method should be called by a service’s “saveX()” method, after it is done validating any attributes on the element that are of particular concern to its element type. For example, if the element were an entry, saveElement() should be called only after the entry’s sectionId and typeId attributes had been validated to ensure that they point to valid section and entry type IDs.

View source

Arguments

  • $element (Craft\BaseElementModel) – The element that is being saved
  • $validateContent (boolean, null) – Whether the element's content should be validated. If left 'null', it will depend on whether the element is enabled or not.

Returns

boolean

Throws

  • \Craft\Exception|\Exception

Signature

public boolean saveElement ( Craft\BaseElementModel $element, $validateContent = null )

setPlaceholderElement()

Stores a placeholder element that {@link findElements()} should use instead of populating a new element with a matching ID and locale. This is used by Live Preview and Sharing features.

View source

Arguments

Returns

null

Signature

public null setPlaceholderElement ( Craft\BaseElementModel $element )

updateDescendantSlugsAndUris()

Updates an element’s descendants’ slugs and URIs.

View source

Arguments

  • $element (Craft\BaseElementModel) – The element whose descendants should be updated.
  • $updateOtherLocales (boolean) – Whether the element’s other locales should also be updated.
  • $asTask (boolean) – Whether the descendants’ slugs and URIs should be updated via a background task.

Returns

null

Signature

public null updateDescendantSlugsAndUris ( Craft\BaseElementModel $element, $updateOtherLocales = true, $asTask = false )

updateElementSlugAndUri()

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

View source

Arguments

  • $element (Craft\BaseElementModel) – The element to update.
  • $updateOtherLocales (boolean) – Whether the element’s other locales should also be updated.
  • $updateDescendants (boolean) – Whether the element’s descendants should also be updated.
  • $asTask (boolean) – Whether the element’s slug and URI should be updated via a background task.

Returns

null

Signature

public null updateElementSlugAndUri ( Craft\BaseElementModel $element, $updateOtherLocales = true, $updateDescendants = true, $asTask = false )

updateElementSlugAndUriInOtherLocales()

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

View source

Arguments

Returns

null

Signature

public null updateElementSlugAndUriInOtherLocales ( Craft\BaseElementModel $element )