MetaModels Interfaces

The MetaModels interfaces form the foundation of the API and provide access to a MetaModel down to the individual item.

Much of the work when using the interfaces focuses on querying existing data from a MetaModel. The structure follows the same pattern as a query or listing via a content element or frontend module with:

Via the MetaModel interfaces, various objects (MetaModel, attribute, item) can also be created, their values modified, or properties such as count or language queried.

MetaModelsServiceContainer Interface:

The MetaModelsServiceContainer interface allows a connection to MetaModels to be established. This is necessary, for example, when accessing a MetaModel outside a MetaModel template.

For access you need a “service container”, which can be obtained e.g. in global scope:

$container = $this->getContainer();

Then an interface can be accessed via it — e.g.:

$factory = $container->getFactory();
or
$factory = $this->getContainer()->get('metamodels.factory');

The service container can easily be accessed in custom templates and programming. Other options include events such as “MetaModelsEvents::SUBSYSTEM_BOOT”.

Current information at: IMetaModelsServiceContainer

Interfaces:

getFactory()
returns access to MetaModels

getAttributeFactory()
returns access to the attributes

getFilterFactory()
returns access to the filters

getRenderSettingFactory()
returns access to the render settings

getEventDispatcher()
returns access to the event dispatcher

getDatabase()
returns access to the database

getCache()
returns access to the cache

setService($service, $serviceName = null)
adds a custom service to the container

getService($serviceName)
returns access to a service with the given name

ServiceContainerAware Interface:

The ServiceContainerAware interface provides access to the service container or allows a new service container to be assigned.

Current information at: IServiceContainerAware

Interfaces:

setServiceContainer(IMetaModelsServiceContainer $serviceContainer)
sets the service container to be used

getServiceContainer()
returns the service container

Factory Interface:

The Factory interface allows instances of a MetaModel to be created and certain properties to be queried.

Creating a new MetaModel is not intended — though possible — as very complex parameters would need to be passed and creation is oriented around backend work.

Current information at: IFactory

Interfaces:

getMetaModel($modelName);
creates a MetaModel instance with the given name

translateIdToMetaModelName($modelId);
returns the name for a given MetaModel ID

collectNames();
returns all MetaModel names as an array

getServiceContainer();
returns the service container

Warning

The methods byTableName, byId and getAllTables were removed in version 2.0

byTableName($strTableName);
use method getMetaModel($modelName); instead

byId($intMetaModelId);
use method getMetaModel($modelName); with translateIdToMetaModelName($modelId); instead

getAllTables();
use method collectNames(); instead

MetaModel Interface:

The MetaModel interface allows properties of a MetaModel instance to be queried or modified.

First, a MetaModels instance must be created via the ID or name of a MetaModel (see Factory Interface:)

$model = \MetaModels\IFactory::getMetaModel($modelName);

or including the service container:

1<?php
2$modelId = 42;
3
4/** @var $container */
5$factory   = $this->getContainer()->get('metamodels.factory');
6$modelName = $factory->translateIdToMetaModelName($modelId);
7$model     = $factory->getMetaModel($modelName);

Then a property can be queried or set — e.g. querying all available attributes:

$attributes = $metaModel->getAttributes();

Current information at: IMetaModel

Interfaces:

Warning

The method getServiceContainer is deprecated — please use as a service

getServiceContainer()
returns the service container

get($strKey)
returns the configuration settings

getTableName()
returns the table name of the instantiated MetaModel

getName()
returns the name of the instantiated MetaModel

Warning

The method isTranslated is deprecated — please use ITranslatedMetaModel

isTranslated()
checks whether the instantiated MetaModel can create translations

hasVariants()
checks whether the instantiated MetaModel can create variants

Warning

The method getAvailableLanguages is deprecated — please use ITranslatedMetaModel

getAvailableLanguages()
returns all language codes of the instantiated MetaModel as an array

Warning

The method getFallbackLanguage is deprecated — please use ITranslatedMetaModel

getFallbackLanguage()
returns the language code of the fallback language of the instantiated MetaModel

Warning

The method getActiveLanguage is deprecated — please use ITranslatedMetaModel

getActiveLanguage()
returns the language code of the active language of the instantiated MetaModel

addAttribute(IAttribute $attribute)
adds an attribute to the internal attribute list

hasAttribute($attributeName)
checks whether an attribute with the given name exists in the internal attribute list

getAttributes()
returns an array of all attributes of the instantiated MetaModel

getInVariantAttributes()
returns an array of the attributes of the instantiated MetaModel that are not defined as variants

getAttribute($attributeName)
returns the instance of the attribute with the given attribute name

getAttributeById($id)
returns the instance of the attribute with the given attribute ID

findById($id, $attrOnly = [])
returns the item with the given ID; optionally an array of attribute names can be specified whose values should be returned

getEmptyFilter()
creates an “empty” filter object without filter rules

Warning

The method prepareFilter is deprecated — please use Filter-Setting-Factory

prepareFilter($filterSettings, $filterUrl)
creates a filter object from a given filter ID and an optional array of filter parameters, e.g. for taking GET values from a URL

findByFilter( $filter, $sortBy = '', $offset = 0, $limit = 0, $sortOrder = 'ASC', $attrOnly = [] )
returns the items found by a given filter in the instantiated MetaModel — in addition to the sorting, offset, limit, and sort direction parameters, an array of attribute names can be specified whose values should be returned

getIdsFromFilter( $filter, $sortBy = '', $offset = 0, $limit = 0, $sortOrder = 'ASC' )
returns the IDs of items found by a given filter in the instantiated MetaModel — sorting, offset, limit, and sort direction parameters can be specified

getCount($filter)
returns the number of items found by a given filter

findVariantBase($filter)
returns all items of a variant base found by a given filter

findVariants($ids, $filter)
returns all variant items for an array of IDs and a given filter

findVariantsWithBase($ids, $filter)
returns all variant items for an array of IDs and a given filter; the query does not distinguish between variant base items and variant items

getAttributeOptions($attribute, $filter = null)
returns all options of a given attribute; optionally a filter can be specified

saveItem($item, $timestamp = null)
saves a given item, or creates a new item if no ID was passed

delete($item)
deletes a given item

Warning

The method getView is deprecated — please use Render-Setting-Factory

getView($viewId = 0)
returns the render settings instance of the instantiated MetaModel

Translated MetaModel Interface:

Note

This feature is available from MM 2.2.

The Translated MetaModel interface allows the language settings of a translated MetaModel to be queried or set.

Up to version MM 2.1, the active language of a translated MetaModel could only be set via the (temporary) assignment of $GLOBALS['TL_LANGUAGE']. With this interface, the language of the MetaModel can be set independently of Contao’s backend language.

For example, to save an item in a specific language for a translated MetaModel, the language can be set via the language code (de, en, fr, …) as follows:

$model->selectLanguage('de');

A type check can be implemented as follows:

1<?php
2
3use MetaModels\ITranslatedMetaModel;
4
5if ($model instanceof ITranslatedMetaModel) {
6    // make anything...
7}

From MetaModels 2.2, the following interfaces must be used:

Interfaces:

getLanguages()
determines all language codes marked as available for translation in this MetaModel

getMainLanguage()
determines the language code marked as the fallback language in this MetaModel

getLanguage()
determines the current language code

selectLanguage($activeLanguage)
sets the new active language and returns the previous language code

Items Interface:

The Items interface allows properties of items to be queried.

First, a MetaModels instance must be created via the ID or name of a MetaModel, and then a list of items retrieved, e.g. via a filter.

$items = $model->findByFilter($filter);

Then a property can be queried — e.g. the total count of all items:

$amountItems = $items->getCount();

Current information at: IItems

Interfaces:

getItem()
returns the current item

getCount()
returns the number of items

first()
sets the pointer to the first element of the items

prev()
sets the pointer to the previous element of the items

last()
sets the pointer to the last element of the items

reset()
resets the current result

getClass()
returns the CSS class of the current item (first, last, even, odd)

parseValue($outputFormat = 'text', $settings = null)
parses the current item and returns the result as an array of attributes; for HTML5 output the render settings must be passed as $objSettings, e.g. $metaModel->getView(3)

parseAll($outputFormat = 'text', $settings = null)
parses all items and returns the result as an array of items with their attributes; for HTML5 output the render settings must be passed as $objSettings, e.g. $metaModel->getView(3)

Item Interface:

The Item interface allows properties of an item to be queried.

First, a MetaModels instance must be created via the ID or name of a MetaModel, and then a list of items retrieved via a filter (optionally also an empty filter).

$items = $model->findByFilter($filter);

Then a property can be queried — e.g. the value of an attribute:

$attribute = $items->getItem()->get($attributeName);

A new item is created as follows:

$item = new \MetaModels\Item($model, []);

Key-value pairs can be passed in the array — but this is only useful for simple item types such as Text.

Current information at: IItem

Interfaces:

get($attributeName)
returns the value of an attribute for the given attribute name

set($attributeName, $value)
sets the value of an attribute for the given attribute name

getMetaModel()
returns the MetaModel instance of the item

getAttribute($attributeName)
returns the instance of an attribute for the given attribute name

isVariant()
determines whether the item is a variant of another item

isVariantBase()
determines whether the item is a variant base

getVariants($filter)
returns an array of the item’s variants, or null if the item does not support variants

getVariantBase()
returns the variant base item; for an item without variants, the variant base is the item itself

parseValue($outputFormat = 'text', $settings = null)
renders the item in the specified format; raw data is always included in output, including attributes of referenced MetaModels

parseAttribute($attributeName, $outputFormat = 'text', $settings = null)
renders a single attribute of the item in the specified format; raw data is always included in output, including attributes of referenced MetaModels

copy()
creates a new item as a copy of an existing item

varCopy()
creates a new item as a copy of an existing item as a variant

save()
saves the current value(s) for the item

Example:

The following example provides a brief introduction to working with the interfaces. For inspiration when testing the API, see the talk by Ingolf Steinhardt at CK23.

Examples for using filters can be found here: Filter Interfaces

The example builds on “The First MetaModel”.

 1<?php
 2// Example for implementation in a template file for testing.
 3// In a live environment, use a "helper class" and inject services there.
 4
 5
 6// Name of the MetaModel table (see "The First MetaModel")
 7$modelName = 'mm_employeelist';
 8// ID of the render setting "FE List"
 9$renderId = 2;
10// ID of the filter
11$filterId = 1;
12
13// MM factories
14$factory       = \Contao\System::getContainer()->get('metamodels.factory');
15$renderFactory = \Contao\System::getContainer()->get('metamodels.render_setting_factory');
16
17// Create MetaModel when table/MetaModel name is known.
18$model = $factory->getMetaModel($modelName);
19// Create MetaModel when only id is known ($metaModelId == tl_metamodel.id of the MetaModel).
20//$model = $factory->getMetaModel($factory->translateIdToMetaModelName($metaModelId));
21
22// empty filter - see also "Filter interfaces"
23$filter = $model->getEmptyFilter();
24// predefined filter via filter ID; an array of values can be passed as second parameter
25//$filter = $model->prepareFilter($filterId, []);
26
27// fetch all items with filter
28$items = $model->findByFilter($filter);
29
30// number of items
31echo 'Count: '.$items->getCount()."<br>\n";
32// or check
33if (!$items->getCount()) {
34    return;
35}
36
37// Output: variant 1 - items object
38/*
39foreach ($items as $item)
40{
41    echo $item->get('name')."<br>\n";
42}
43*/
44
45// Output: variant 2 - items array
46// all items parsed to array with HTML5 nodes
47$arrItems = $items->parseAll('html5', $renderFactory->createCollection($model, $renderId));
48// alternatively only raw and text nodes
49//$arrItems = $items->parseAll('text');
50foreach ($arrItems as $arrItem)
51{
52    echo $arrItem['html5']['name']."<br>\n";
53}
54
55// Output: variant 3 - process only current item
56$item = $items->getItem()->parseValue('text', $renderFactory->createCollection($model, $renderId));
57echo $item['text']['name']."<br>\n";