Craft 2 Class Reference

Class BaseElementType

Package
craft.app.elementtypes
Namespace
Craft
Inheritance
abstract class BaseElementType » BaseComponentType » BaseApplicationComponent » \CApplicationComponent » \CComponent
Implements
IComponentType, \IApplicationComponent, IElementType
Subclasses
AssetElementType, CategoryElementType, EntryElementType, GlobalSetElementType, MatrixBlockElementType, TagElementType, UserElementType
Since
1.0
Source Code
craft/app/elementtypes/BaseElementType.php

The base class for all Craft element types. Any element type must extend this class.

Public Properties
Property Type Description Defined By
availableActions array / null Returns the available element actions for a given source (if one is provided). BaseElementType
behaviors array the behaviors that should be attached to this component. \CApplicationComponent
classHandle string Returns the component’s handle, ideally based on the class name. BaseComponentType
defaultTableAttributes array Returns the list of table attribute keys that should be shown by default. BaseElementType
isInitialized bool Checks if this application component has been initialized. \CApplicationComponent
name string Returns the component’s name. BaseComponentType
sources array / bool / false Returns this element type's sources. BaseElementType
statuses array / null Returns all of the possible statuses that elements of this type may have. BaseElementType
Protected Properties
Property Type Description Defined By
componentType string The type of component, e.g. "Plugin", "Widget", "FieldType", etc. Defined by the component type's base class. BaseElementType
Public Methods
Method Description Defined By
__call() Calls the named method which is not a class method. \CComponent
__get() Returns a property value, an event handler list or a behavior based on its name. \CComponent
__isset() Checks if a property value is null. \CComponent
__set() Sets value of a component property. \CComponent
__unset() Sets a component property to be null. \CComponent
asa() Returns the named behavior object. \CComponent
attachBehavior() Attaches a behavior to this component. \CComponent
attachBehaviors() Attaches a list of behaviors to the component. \CComponent
attachEventHandler() Attaches an event handler to an event. \CComponent
canGetProperty() Determines whether a property can be read. \CComponent
canSetProperty() Determines whether a property can be set. \CComponent
defineAvailableTableAttributes() Defines all of the available columns that can be shown in table views. BaseElementType
defineCriteriaAttributes() Defines any custom element criteria attributes for this element type. BaseElementType
defineSearchableAttributes() Defines which element model attributes should be searchable. BaseElementType
defineSortableAttributes() Defines the attributes that elements can be sorted by. BaseElementType
detachBehavior() Detaches a behavior from the component. \CComponent
detachBehaviors() Detaches all behaviors from the component. \CComponent
detachEventHandler() Detaches an existing event handler. \CComponent
disableBehavior() Disables an attached behavior. \CComponent
disableBehaviors() Disables all behaviors attached to this component. \CComponent
enableBehavior() Enables an attached behavior. \CComponent
enableBehaviors() Enables all behaviors attached to this component. \CComponent
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. \CComponent
getAvailableActions() Returns the available element actions for a given source (if one is provided). BaseElementType
getClassHandle() Returns the component’s handle, ideally based on the class name. BaseComponentType
getContentFieldColumnsForElementsQuery() Returns the field column names that should be selected from the content table. BaseElementType
getContentTableForElementsQuery() Returns the content table name that should be joined into an elements query for a given element criteria. BaseElementType
getDefaultTableAttributes() Returns the list of table attribute keys that should be shown by default. BaseElementType
getEagerLoadingMap() Returns an array that maps source-to-target element IDs based on the given sub-property handle. BaseElementType
getEditorHtml() Returns the HTML for an editor HUD for the given element. BaseElementType
getElementQueryStatusCondition() Returns the element query condition for a custom status criteria. BaseElementType
getEventHandlers() Returns the list of attached event handlers for an event. \CComponent
getFieldsForElementsQuery() Returns the fields that should take part in an upcoming elements qurery. BaseElementType
getIndexHtml() Returns the element index HTML. BaseElementType
getIsInitialized() Checks if this application component has been initialized. \CApplicationComponent
getName() Returns the component’s name. BaseComponentType
getSource() Returns a source by its key and context. BaseElementType
getSources() Returns this element type's sources. BaseElementType
getStatuses() Returns all of the possible statuses that elements of this type may have. BaseElementType
getTableAttributeHtml() Returns the HTML that should be shown for a given element’s attribute in Table View. BaseElementType
hasContent() Returns whether this element type will be storing any data in the content table (tiles or custom fields). BaseElementType
hasEvent() Determines whether an event is defined. \CComponent
hasEventHandler() Checks whether the named event has attached handlers. \CComponent
hasProperty() Determines whether a property is defined. \CComponent
hasStatuses() Returns whether this element type can have statuses. BaseElementType
hasTitles() Returns whether this element type has titles. BaseElementType
init() Initializes the application component. \CApplicationComponent
isInitialized() Checks if this application component has been initialized yet, or not. BaseApplicationComponent
isLocalized() Returns whether this element type stores data on a per-locale basis. BaseElementType
isSelectable() Returns whether this component should be shown when the user is creating a component of this type. BaseComponentType
modifyElementsQuery() Modifies an element query targeting elements of this type. BaseElementType
onAfterMoveElementInStructure() Performs actions after an element has been moved within a structure. BaseElementType
populateElementModel() Populates an element model based on a query result. BaseElementType
raiseEvent() Raises an event. \CComponent
routeRequestForMatchedElement() Routes the request when the URI matches an element. BaseElementType
saveElement() Saves a given element. BaseElementType
Protected Methods
Method Description Defined By
getTableAttributesForSource() Returns the attributes that should be shown for the given source. BaseElementType
prepElementCriteriaForTableAttribute() Preps the element criteria for a given table attribute BaseElementType
Events
Event Description Defined By
onAfterMoveElementInStructure BaseElementType

Property Details

availableActions public property #

Returns the available element actions for a given source (if one is provided).

The actions can either be represented by their class handle (e.g. 'SetStatus'), or by an IElementAction instance.

public array|null getAvailableActions(string|null $source = null)

componentType protected property #

The type of component, e.g. "Plugin", "Widget", "FieldType", etc. Defined by the component type's base class.

protected string $componentType;

defaultTableAttributes public property #

Returns the list of table attribute keys that should be shown by default.

This method should return an array where each element in the array maps to one of the keys of the array returned by defineAvailableTableAttributes().

public array getDefaultTableAttributes(string|null $source = null)

sources public property #

Returns this element type's sources.

This defines what will show up in the source list on element indexes and element selector modals.

Each item in the array should have a key that identifies the source’s key (e.g. "section:3"), and should be set to an array that has the following keys:

public array|bool|false getSources(null $context = null)

statuses public property #

Returns all of the possible statuses that elements of this type may have.

This method will be called when populating the Status menu on element indexes, for element types whose hasStatuses() method returns true. It will also be called when ElementsService is querying for elements, to ensure that the ElementCriteriaModel’s “status” parameter is set to a valid status.

It should return an array whose keys are the status values, and values are the human-facing status labels.

You can customize the database query condition that should be applied for your custom statuses from getElementQueryStatusCondition().

public array|null getStatuses()

Method Details

defineAvailableTableAttributes() public method #

Defines all of the available columns that can be shown in table views.

This method should return an array whose keys map to attribute names and database columns that can be sorted against when querying for elements, and whose values make up the table’s column headers.

The first item that this array returns will just identify the database column name, and the table column’s header, but will not have any effect on what shows up in the table’s body. That’s because the first column is reserved for displaying whatever your element model’s __toString() method returns (the string representation of the element).

All other items besides the first one will also define which element attribute should be shown within the data cells. (The actual HTML to be shown can be customized with getTableAttributeHtml().)

public array defineAvailableTableAttributes()
Returns array The table attributes.

defineCriteriaAttributes() public method #

Defines any custom element criteria attributes for this element type.

This method returns an array which will get merged into the array defined in ElementCriteriaModel::defineAttributes(), when new ElementCriteriaModel instances are created targeting this element type (generally from craft()->elements->getCriteria()).

If this method were to return the following:

return array(
    'foo' => AttributeType::String,
    'bar' => AttributeType::String,
);

then when someone creates a new ElementCriteriaModel instance targeting this elmeent type, they will be able to do this:

$criteria = craft()->elements->getCriteria('ThisElementType');
$criteria->foo = 'FooParamValue';
$criteria->bar = 'BarParamValue';

You can check for these custom criteria attributes, and factor their values into the actual database query, from modifyElementsQuery().

public array defineCriteriaAttributes()
Returns array Custom criteria attributes.

defineSearchableAttributes() public method #

Defines which element model attributes should be searchable.

This method should return an array of attribute names that can be accessed on your element model (for example, the attributes defined by your element model’s defineAttributes() method). SearchService will call this method when it is indexing keywords for one of your elements, and for each attribute it returns, it will fetch the corresponding property’s value on the element.

For example, if your elements have a “color” attribute which you want to be indexed, this method could return:

return array('color');

Not only will the “color” attribute’s values start getting indexed, but users will also be able to search directly against that attribute’s values using this search syntax:

color:blue

There is no need for this method to worry about the ‘title’ or ‘slug’ attributes, or custom field handles; those are indexed automatically.

public array defineSearchableAttributes()
Returns array The attributes that should be searchable

defineSortableAttributes() public method #

Defines the attributes that elements can be sorted by.

This method should return an array, where the keys reference database column names that should be sorted on, and where the values define the user-facing labels.

return array(
    'columnName1' => Craft::t('Attribute Label 1'),
    'columnName2' => Craft::t('Attribute Label 2'),
);

If you want to sort by multilple columns simultaneously, you can specify multiple column names in the key, separated by commas.

return array(
    'columnName1, columnName2 asc' => Craft::t('Attribute Label 1'),
    'columnName3'                  => Craft::t('Attribute Label 2'),
);

If you do that, you can specify the sort direction for the subsequent columns (asc or desc. There is no point in specifying the sort direction for the first column, though, since the end user has full control over that.

Note that this method will only get called once for the entire index; not each time that a new source is selected.

public array defineSortableAttributes()
Returns array The attributes that elements can be sorted by.

getAvailableActions() public method #

Returns the available element actions for a given source (if one is provided).

The actions can either be represented by their class handle (e.g. 'SetStatus'), or by an IElementAction instance.

public array|null getAvailableActions(string|null $source = null)
$source string / null The selected source’s key, if any.
Returns array / null The available element actions.

getClassHandle() public method #

Returns the component’s handle, ideally based on the class name.

public string getClassHandle()
Returns string The component’s handle.

getContentFieldColumnsForElementsQuery() public method #

Returns the field column names that should be selected from the content table.

This method will tell ElementsService::buildElementsQuery() which custom fields it should be selecting from the content table, as well as the custom field handle that the column corresponds to.

Deprecated in 2.3. Element types should implement getFieldsForElementsQuery() instead.

public array getContentFieldColumnsForElementsQuery(ElementCriteriaModel $criteria)
$criteria ElementCriteriaModel
Returns array

getContentTableForElementsQuery() public method #

Returns the content table name that should be joined into an elements query for a given element criteria.

This method will get called from ElementsService::buildElementsQuery() as it is building out a database query to fetch elements with a given criteria. It will only be called if hasContent() returns true.

If this method returns false, no content table will be joined in, and it will be up to the elements’ getContent() methods to fetch their content rows on demand.

public false|string getContentTableForElementsQuery(ElementCriteriaModel $criteria)
$criteria ElementCriteriaModel The element criteria.
Returns string / false The content table name, or false if it cannot be determined.

getDefaultTableAttributes() public method #

Returns the list of table attribute keys that should be shown by default.

This method should return an array where each element in the array maps to one of the keys of the array returned by defineAvailableTableAttributes().

public array getDefaultTableAttributes(string|null $source = null)
$source string / null The selected source’s key, if any.
Returns array The table attribute keys.

getEagerLoadingMap() public method #

Returns an array that maps source-to-target element IDs based on the given sub-property handle.

This method aids in the eager-loading of elements when performing an element query. The returned array should contain two sub-keys:

public array|false getEagerLoadingMap(array $sourceElements, string $handle)
$sourceElements array An array of the source elements
$handle string The property handle used to identify which target elements should be included in the map
Returns array / false The eager-loading element ID mappings, or false if no mappings exist

getEditorHtml() public method #

Returns the HTML for an editor HUD for the given element.

public string getEditorHtml(BaseElementModel $element)
$element BaseElementModel The element being edited.
Returns string The HTML for the editor HUD.

getElementQueryStatusCondition() public method #

Returns the element query condition for a custom status criteria.

If the ElementCriteriaModel’s status parameter is set to something besides 'enabled' or 'disabled', and it’s one of the statuses that you’ve defined in getStatuses(), this method is where you can turn that custom status into an actual SQL query condition.

For example, if you support a status called “pending”, which maps back to a pending database column that will either be 0 or 1, this method could do this:

switch ($status)
{
    case 'pending':
    {
        $query->andWhere('mytable.pending = 1');
        break;
    }
}
public false|string|void getElementQueryStatusCondition(DbCommand $query, string $status)
$query DbCommand The database query.
$status string The custom status.
Returns string / false

getFieldsForElementsQuery() public method #

Returns the fields that should take part in an upcoming elements qurery.

These fields will get their own parameters in the ElementCriteriaModel that gets passed in, their field types will each have an opportunity to help build the element query, and their columns in the content table will be selected by the query (for those that have one).

If a field has its own column in the content table, but the column name is prefixed with something besides “field_”, make sure you set the columnPrefix attribute on the FieldModel, so ElementsService::buildElementsQuery() knows which column to select.

public FieldModel[] getFieldsForElementsQuery(ElementCriteriaModel $criteria)
$criteria ElementCriteriaModel
Returns FieldModel[]

getIndexHtml() public method #

Returns the element index HTML.

public string getIndexHtml(ElementCriteriaModel $criteria, array $disabledElementIds, array $viewState, null|string $sourceKey, null|string $context, bool $includeContainer, bool $showCheckboxes)
$criteria ElementCriteriaModel
$disabledElementIds array
$viewState array
$sourceKey string / null
$context string / null
$includeContainer bool
$showCheckboxes bool
Returns string

getName() public method #

Returns the component’s name.

This is what your component will be called throughout the Control Panel.

public string getName()
Returns string The component’s name.

getSource() public method #

Returns a source by its key and context.

public array|null getSource(string $key, null $context = null)
$key string The source’s key.
$context string The context ('index' or 'modal').
Returns array / null

getSources() public method #

Returns this element type's sources.

This defines what will show up in the source list on element indexes and element selector modals.

Each item in the array should have a key that identifies the source’s key (e.g. "section:3"), and should be set to an array that has the following keys:

public array|bool|false getSources(null $context = null)
$context string / null The context ('index' or 'modal').
Returns array / false The element type's sources.

getStatuses() public method #

Returns all of the possible statuses that elements of this type may have.

This method will be called when populating the Status menu on element indexes, for element types whose hasStatuses() method returns true. It will also be called when ElementsService is querying for elements, to ensure that the ElementCriteriaModel’s “status” parameter is set to a valid status.

It should return an array whose keys are the status values, and values are the human-facing status labels.

You can customize the database query condition that should be applied for your custom statuses from getElementQueryStatusCondition().

public array|null getStatuses()
Returns array / null

getTableAttributeHtml() public method #

Returns the HTML that should be shown for a given element’s attribute in Table View.

This method can be used to completely customize what actually shows up within the table’s body for a given attribtue, rather than simply showing the attribute’s raw value.

For example, if your elements have an “email” attribute that you want to wrap in a mailto: link, your getTableAttributesHtml() method could do this:

switch ($attribute)
{
    case 'email':
    {
        if ($element->email)
        {
            return '<a href="mailto:'.$element->email.'">'.$element->email.'</a>';
        }

        break;
    }
    default:
    {
        return parent::getTableAttributeHtml($element, $attribute);
    }
}

BaseElementType::getTableAttributeHtml() provides a couple handy attribute checks by default, so it is a good idea to let the parent method get called (as shown above). They are:

public mixed|string getTableAttributeHtml(BaseElementModel $element, string $attribute)
$element BaseElementModel The element.
$attribute string The attribute name.
Returns string

getTableAttributesForSource() protected method #

Returns the attributes that should be shown for the given source.

protected array getTableAttributesForSource(string $sourceKey)
$sourceKey string The source key
Returns array The attributes that should be shown for the given source

hasContent() public method #

Returns whether this element type will be storing any data in the content table (tiles or custom fields).

public bool hasContent()
Returns bool Whether the element type has content. Default is false.

hasStatuses() public method #

Returns whether this element type can have statuses.

If this returns true, the element index template will show a Status menu by default, and your elements will get status indicator icons next to them.

Use getStatuses() to customize which statuses the elements might have.

public bool hasStatuses()
Returns bool Whether the element type has statuses. Default is false.

hasTitles() public method #

Returns whether this element type has titles.

public bool hasTitles()
Returns bool Whether the element type has titles. Default is false.

isLocalized() public method #

Returns whether this element type stores data on a per-locale basis.

If this returns true, the element model’s getLocales() method will be responsible for defining which locales its data should be stored in.

public bool isLocalized()
Returns bool Whether the element type is localized. Default is false.

isSelectable() public method #

Returns whether this component should be shown when the user is creating a component of this type.

public bool isSelectable()
Returns bool Whether the component should be selectable.

modifyElementsQuery() public method #

Modifies an element query targeting elements of this type.

If your element type is storing additional data in its own table, this method is the place to join that table in.

$query
    ->addSelect('mytable.foo, mytable.bar')
    ->join('mytable mytable', 'mytable.id = elements.id');

This is also where you get to check the ElementCriteriaModel for all the custom attributes that this element type supports via {@defineCriteriaAttributes()}, and modify the database query to reflect those parameters.

if ($criteria->foo)
{
    $query->andWhere(DbHelper::parseParam('mytable.foo', $criteria->foo, $query->params));
}

if ($criteria->bar)
{
    $query->andWhere(DbHelper::parseParam('mytable.bar', $criteria->bar, $query->params));
}

If you are able to determine from the element criteria’s paramteers that there’s no way that the query is going to match any elements, you can have it return false. The query will be stopped before it ever gets a chance to execute.

public false|null|void modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria)
$query DbCommand The database query currently being built to find the elements.
$criteria ElementCriteriaModel The criteria that is being used to find the elements.
Returns null / false false in the event that the method is sure that no elements are going to be found.

onAfterMoveElementInStructure() public method #

Performs actions after an element has been moved within a structure.

public null|void onAfterMoveElementInStructure(BaseElementModel $element, int $structureId)
$element BaseElementModel The element that was moved.
$structureId int The ID of the structure that it moved within.

populateElementModel() public method #

Populates an element model based on a query result.

This method is called by ElementsService::findElements() after it has finished fetching all of the matching elements’ rows from the database.

For each row of data returned by the query, it will call this method on the element type, and it is up to this method to take that array of raw data from the database, and populate a new element model with it.

You should be able to accomplish this with a single line:

return MyElementTypeModel::populateModel($row);
public BaseElementModel|void populateElementModel(array $row)
$row array The row of data in the database query result.
Returns BaseElementModel The element model, populated with the data in $row.

prepElementCriteriaForTableAttribute() protected method #

Preps the element criteria for a given table attribute

protected void prepElementCriteriaForTableAttribute(ElementCriteriaModel $criteria, string $attribute)
$criteria ElementCriteriaModel
$attribute string
Returns void

routeRequestForMatchedElement() public method #

Routes the request when the URI matches an element.

public bool|mixed routeRequestForMatchedElement(BaseElementModel $element)
$element BaseElementModel The matched element.
Returns mixed Can be false if no special action should be taken, a string if it should route to a template path, or an array that can specify a controller action path, params, etc.

saveElement() public method #

Saves a given element.

This method will be called when an Element Editor’s Save button is clicked. It should just wrap your service’s saveX() method.

public bool saveElement(BaseElementModel $element, array $params)
$element BaseElementModel The element being saved.
$params array Any element params found in the POST data.
Returns bool Whether the element was saved successfully.