BaseElementType

Type
Abstract Class
Namespace
Craft
Inherits
Craft\BaseElementType » Craft\BaseComponentType » Craft\BaseApplicationComponent » CApplicationComponent (opens new window) » CComponent (opens new window)
Implements
Craft\IComponentType, Craft\IElementType, IApplicationComponent
Extended by
Craft\AssetElementType, Craft\CategoryElementType, Craft\EntryElementType, Craft\GlobalSetElementType, Craft\MatrixBlockElementType, Craft\TagElementType, Craft\UserElementType
Since
1.0

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

See also http://craftcms.com

View source (opens new window)

# Public Properties

Property Description
$behaviors (opens new window) array (opens new window) – The behaviors that should be attached to this component.

# Protected Properties

# $componentType

Signature

protected string $componentType = 'ElementType'

# Public Methods

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

# defineAvailableTableAttributes()

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 {@link BaseElementModel::__toString() __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 {@link getTableAttributeHtml()}.)

IElementType::defineAvailableTableAttributes()

View source (opens new window)

Returns

array (opens new window) – The table attributes.

Signature

public array defineAvailableTableAttributes ( )

# defineCriteriaAttributes()

Defines any custom element criteria attributes for this element type.

This method returns an array which will get merged into the array defined in {@link ElementCriteriaModel::defineAttributes()}, when new ElementCriteriaModel instances are created targeting this element type (generally from {@link ElementsService::getCriteria() 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 {@link modifyElementsQuery()}.

IElementType::defineCriteriaAttributes()

View source (opens new window)

Returns

array (opens new window) – Custom criteria attributes.

Signature

public array defineCriteriaAttributes ( )

# defineSearchableAttributes()

Defines which element model attributes should be searchable.

This method should return an array of attribute names that can be accessed on your {@link BaseElementModel element model} (for example, the attributes defined by your element model’s {@link BaseElementType::defineAttributes() defineAttributes()} method). {@link 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.

IElementType::defineSearchableAttributes()

View source (opens new window)

Returns

array (opens new window) – The attributes that should be searchable

Signature

public array defineSearchableAttributes ( )

# defineSortableAttributes()

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.

IElementType::defineSortableAttributes()

View source (opens new window)

Returns

array (opens new window) – The attributes that elements can be sorted by.

Signature

public array defineSortableAttributes ( )

# getAvailableActions()

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 {@link IElementAction} instance.

IElementType::getAvailableActions()

View source (opens new window)

Arguments

Returns

array (opens new window), null (opens new window) – The available element actions.

Signature

public array, null getAvailableActions ( $source = null )

# getContentFieldColumnsForElementsQuery()

DEPRECATED

Deprecated Deprecated in 2.3. Element types should implement {@link getFieldsForElementsQuery()} instead.

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

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

IElementType::getContentFieldColumnsForElementsQuery()

View source (opens new window)

Arguments

Returns

array (opens new window)

Signature

public array getContentFieldColumnsForElementsQuery ( Craft\ElementCriteriaModel $criteria )

# getContentTableForElementsQuery()

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

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

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

IElementType::getContentTableForElementsQuery()

View source (opens new window)

Arguments

Returns

false (opens new window), string (opens new window) – The content table name, or false if it cannot be determined.

Signature

public false, string getContentTableForElementsQuery ( Craft\ElementCriteriaModel $criteria )

# getDefaultTableAttributes()

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 {@link defineAvailableTableAttributes()}.

IElementType::getDefaultTableAttributes()

View source (opens new window)

Arguments

Returns

array (opens new window) – The table attribute keys.

Signature

public array getDefaultTableAttributes ( $source = null )

# getEagerLoadingMap()

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:

  • elementType – indicating the type of sub-elements to eager-load (the element type class handle)
  • map – an array of element ID mappings, where each element is a sub-array with source and target keys.

IElementType::getEagerLoadingMap()

View source (opens new window)

Arguments

Returns

array (opens new window), false (opens new window) – The eager-loading element ID mappings, or false if no mappings exist

Signature

public array, false getEagerLoadingMap ( $sourceElements, $handle )

# getEditorHtml()

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

IElementType::getEditorHtml()

View source (opens new window)

Arguments

Returns

string (opens new window) – The HTML for the editor HUD.

Signature

public string getEditorHtml ( Craft\BaseElementModel $element )

# getElementQueryStatusCondition()

Returns the element query condition for a custom status criteria.

If the ElementCriteriaModel’s {@link ElementCriteriaModel::status status} parameter is set to something besides 'enabled' or 'disabled', and it’s one of the statuses that you’ve defined in {@link 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;
    }
}

IElementType::getElementQueryStatusCondition()

View source (opens new window)

Arguments

Returns

false (opens new window), string (opens new window), void

Signature

public false, string, void getElementQueryStatusCondition ( Craft\DbCommand $query, $status )

# getFieldsForElementsQuery()

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

These fields will get their own parameters in the {@link 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 {@link FieldModel}, so {@link ElementsService::buildElementsQuery()} knows which column to select.

IElementType::getFieldsForElementsQuery()

View source (opens new window)

Arguments

Returns

Craft\FieldModel[]

Signature

public Craft\FieldModel[] getFieldsForElementsQuery ( Craft\ElementCriteriaModel $criteria )

# getIndexHtml()

Returns the element index HTML.

IElementType::getIndexHtml()

View source (opens new window)

Arguments

Returns

string (opens new window)

Signature

public string getIndexHtml ( $criteria, $disabledElementIds, $viewState, $sourceKey, $context, $includeContainer, $showCheckboxes )

# getSource()

Returns a source by its key and context.

IElementType::getSource()

View source (opens new window)

Arguments

Returns

array (opens new window), null (opens new window)

Signature

public array, null getSource ( $key, $context = null )

# getSources()

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:

  • label – The human-facing label of the source.
  • criteria – An array of criteria parameters that the source should use when the source is selected. (Optional)
  • data – An array of data-X attributes that should be set on the source’s <a> tag in the source list’s, HTML, where each key is the name of the attribute (without the “data-” prefix), and each value is the value of the attribute. (Optional)
  • defaultSort – A string identifying the sort attribute that should be selected by default, or an array where the first value identifies the sort attribute, and the second determines which direction to sort by. (Optional)
  • hasThumbs – A boolean that defines whether this source supports Thumbs View. (Use your element model’s {@link BaseElementModel::getThumbUrl() getThumbUrl()} method to define your elements’ thumb URL.) (Optional)
  • structureId – The ID of the Structure that contains the elements in this source. If set, Structure View will be available to this source. (Optional)
  • newChildUrl – The URL that should be loaded when a usel select’s the “New child” menu option on an element in this source while it is in Structure View. (Optional)
  • nested – An array of sources that are nested within this one. Each nested source can have the same keys as top-level sources.

IElementType::getSources()

View source (opens new window)

Arguments

Returns

array (opens new window), boolean (opens new window), false (opens new window) – The element type's sources.

Signature

public array, boolean, false getSources ( $context = null )

# getStatuses()

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 {@link hasStatuses()} method returns true. It will also be called when {@link ElementsService} is querying for elements, to ensure that the {@link 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 {@link getElementQueryStatusCondition()}.

IElementType::getStatuses()

View source (opens new window)

Returns

array (opens new window), null (opens new window)

Signature

public array, null getStatuses ( )

# getTableAttributeHtml()

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:

  • If the attribute name is ‘uri’, it will be linked to the front-end URL.
  • If the attribute name is ‘dateCreated’ or ‘dateUpdated’, the date will be formatted according to the active locale.

IElementType::getTableAttributeHtml()

View source (opens new window)

Arguments

Returns

mixed, string (opens new window)

Signature

public mixed, string getTableAttributeHtml ( Craft\BaseElementModel $element, $attribute )

# hasContent()

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

IElementType::hasContent()

View source (opens new window)

Returns

boolean (opens new window) – Whether the element type has content. Default is false.

Signature

public boolean hasContent ( )

# hasStatuses()

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 {@link getStatuses()} to customize which statuses the elements might have.

IElementType::hasStatuses()

View source (opens new window)

Returns

boolean (opens new window) – Whether the element type has statuses. Default is false.

Signature

public boolean hasStatuses ( )

# hasTitles()

Returns whether this element type has titles.

IElementType::hasTitles()

View source (opens new window)

Returns

boolean (opens new window) – Whether the element type has titles. Default is false.

Signature

public boolean hasTitles ( )

# isLocalized()

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

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

IElementType::isLocalized()

View source (opens new window)

Returns

boolean (opens new window) – Whether the element type is localized. Default is false.

Signature

public boolean isLocalized ( )

# modifyElementsQuery()

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 {@link 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.

IElementType::modifyElementsQuery()

View source (opens new window)

Arguments

Returns

false (opens new window), null (opens new window), voidfalse in the event that the method is sure that no elements are going to be found.

Signature

public false, null, void modifyElementsQuery ( Craft\DbCommand $query, Craft\ElementCriteriaModel $criteria )

# onAfterMoveElementInStructure()

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

IElementType::onAfterMoveElementInStructure()

View source (opens new window)

Arguments

Returns

null (opens new window), void

Signature

public null, void onAfterMoveElementInStructure ( Craft\BaseElementModel $element, $structureId )

# populateElementModel()

Populates an element model based on a query result.

This method is called by {@link 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);

IElementType::populateElementModel()

View source (opens new window)

Arguments

Returns

Craft\BaseElementModel, void – The element model, populated with the data in $row.

Signature

public Craft\BaseElementModel, void populateElementModel ( $row )

# routeRequestForMatchedElement()

Routes the request when the URI matches an element.

IElementType::routeRequestForMatchedElement()

View source (opens new window)

Arguments

Returns

boolean (opens new window), 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.

Signature

public boolean, mixed routeRequestForMatchedElement ( Craft\BaseElementModel $element )

# saveElement()

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.

IElementType::saveElement()

View source (opens new window)

Arguments

Returns

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

Signature

public boolean saveElement ( Craft\BaseElementModel $element, $params )

# Protected Methods

Method Description
getTableAttributesForSource() Returns the attributes that should be shown for the given source.
prepElementCriteriaForTableAttribute() Preps the element criteria for a given table attribute

# getTableAttributesForSource()

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

View source (opens new window)

Arguments

Returns

array (opens new window) – The attributes that should be shown for the given source

Signature

protected array getTableAttributesForSource ( $sourceKey )

# prepElementCriteriaForTableAttribute()

Preps the element criteria for a given table attribute

View source (opens new window)

Arguments

Returns

void

Signature

protected void prepElementCriteriaForTableAttribute ( Craft\ElementCriteriaModel $criteria, $attribute )