Matrix

Type
Class
Namespace
craft\fields
Inherits
craft\fields\Matrix » craft\base\Field » craft\base\SavableComponent » craft\base\Component » craft\base\Model » yii\base\Model » yii\base\Component » yii\base\BaseObject
Implements
ArrayAccess, IteratorAggregate, craft\base\ComponentInterface, craft\base\EagerLoadingFieldInterface, craft\base\FieldInterface, craft\base\SavableComponentInterface, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface
Uses traits
craft\base\ClonefixTrait, craft\base\FieldTrait, craft\base\SavableComponentTrait, yii\base\ArrayableTrait, yii\base\StaticInstanceTrait
Since
3.0

Matrix represents a Matrix field.

View source

Public Properties

PropertyDescription
$activeValidatorsyii\validators\Validator – The validators applicable to the current $scenario.
$attributesarray – Attribute values (name => value).
$behaviorsyii\base\Behavior – List of behaviors attached to this component
$blockTypeFieldscraft\base\FieldInterface[]
$blockTypescraft\models\MatrixBlockType[]
$columnPrefixstring, null – The field’s content column prefix
$contentColumnTypestring – The column type.
$contextstring, null – The field’s context
$dateCreatedDateTime, null – The date that the component was created
$dateUpdatedDateTime, null – The date that the component was last updated
$elementValidationRulesarray
$errorsarray – Errors for all attributes or the specified attribute.
$firstErrorsarray – The first errors.
$groupcraft\records\FieldGroup, null
$groupIdinteger, null – The field’s group’s ID
$handlestring, null – The field’s handle
$idinteger, string, null – The component’s ID (could be a temporary one: "new:X")
$instructionsstring, null – The field’s instructions
$isNewboolean – Whether the component is new
$isTranslatableboolean
$iteratorArrayIterator – An iterator for traversing the items in the list.
$layoutIdinteger, null – The ID of the field layout that the field was fetched from
$localizeBlocksinteger – Whether each site should get its own unique set of blocks
$maxBlocksinteger, null – Max blocks
$minBlocksinteger, null – Min blocks
$namestring, null – The field’s name
$oldHandlestring, null – The field’s previous handle
$requiredboolean, null – Whether the field is required in the field layout it was fetched from
$scenariostring – The scenario that this model is in.
$settingsarray – The component’s settings.
$settingsHtmlstring, null
$sortOrderinteger, null – The field’s sort position in the field layout it was fetched from
$tabIdinteger, null – The tab ID of the field layout that the field was fetched from
$translationKeyFormatstring, null – The field’s translation key format, if $translationMethod is "custom"
$translationMethodstring – The field’s translation method
$validatorsArrayObject, yii\validators\Validator – All the validators declared in the model.

$blockTypeFields

Signature

public craft\base\FieldInterface[] getBlockTypeFields ( )

$blockTypes

Signature

public craft\models\MatrixBlockType[] getBlockTypes ( )
public void setBlockTypes ( $blockTypes )

$elementValidationRules

Type
array
Access
Read-only

View source

Signature

public array getElementValidationRules ( )

$isTranslatable

Type
boolean
Access
Read-only

View source

Signature

public boolean getIsTranslatable ( craft\base\ElementInterface $element = null )

$localizeBlocks

Type
integer

Whether each site should get its own unique set of blocks

View source

Signature

public integer $localizeBlocks = false

$maxBlocks

Type
integer, null

Max blocks

View source

Signature

public integer, null $maxBlocks = null

$minBlocks

Type
integer, null

Min blocks

View source

Signature

public integer, null $minBlocks = null

$settingsHtml

Type
string, null
Access
Read-only

View source

Signature

public string, null getSettingsHtml ( )

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__clone()
__construct()Constructor.
__get()Returns the value of an object property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets value of an object property.
__toString()Use the translated field name as the string representation.
__unset()Sets an object property to null.
activeAttributes()Returns the attribute names that are subject to validation in the current scenario.
addError()Adds a new error to the specified attribute.
addErrors()Adds a list of errors.
addModelErrors()Adds errors from another model, with a given attribute name prefix.
afterDelete()Performs actions after a component is deleted.
afterElementDelete()Performs actions after the element has been deleted.
afterElementSave()Performs actions after the element has been saved.
afterSave()Performs actions after a component is saved.
afterValidate()This method is invoked after validation ends.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
attributeHints()Returns the attribute hints.
attributeLabels()Returns the attribute labels.
attributes()Returns the list of attribute names.
beforeDelete()Performs actions before a component is deleted.
beforeElementDelete()Performs actions before an element is deleted.
beforeElementSave()Performs actions before an element is saved.
beforeSave()Performs actions before a component is saved.
beforeValidate()This method is invoked before validation starts.
behaviors()Returns a list of behaviors that this component should behave as.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
clearErrors()Removes errors for all attributes or a single attribute.
createValidators()Creates validator objects based on the validation rules specified in rules().
datetimeAttributes()Returns the names of any attributes that should hold DateTime values.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
displayName()Returns the display name of this class.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
extraFields()Returns the list of fields that can be expanded further and returned by toArray().
fields()Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.
formName()Returns the form name that this model class should use.
generateAttributeLabel()Generates a user friendly attribute label based on the give attribute name.
getActiveValidators()Returns the validators applicable to the current $scenario.
getAttributeHint()Returns the text hint for the specified attribute.
getAttributeLabel()Returns the text label for the specified attribute.
getAttributes()Returns attribute values.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getBlockTypeFields()Returns all of the block types' fields.
getBlockTypes()Returns the block types.
getContentColumnType()Returns the column type that this field should get within the content table.
getEagerLoadingMap()Returns an array that maps source-to-target element IDs based on this custom field.
getElementValidationRules()Returns the validation rules for an element with this field.
getError()Returns the first error of the specified attribute.
getErrorSummary()Returns the errors for all attributes as a one-dimensional array.
getErrors()Returns the errors for all attributes or a single attribute.
getFirstError()Returns the first error of the specified attribute.
getFirstErrors()Returns the first error of every attribute in the model.
getGroup()Returns the field’s group.
getInputHtml()Returns the field’s input HTML.
getIsNew()Returns whether the component is new (unsaved).
getIsTranslatable()Returns whether the field should be shown as translatable in the UI.
getIterator()Returns an iterator for traversing the attributes in the model.
getScenario()Returns the scenario that this model is used in.
getSearchKeywords()Returns the search keywords that should be associated with this field.
getSettings()Returns an array of the component’s settings.
getSettingsHtml()Returns the component’s settings HTML.
getStaticHtml()Returns a static (non-editable) version of the field’s input HTML.
getTableAttributeHtml()Returns the HTML that should be shown for this field in Table View.
getTranslationKey()Returns the field’s translation key, based on a given element.
getValidators()Returns all the validators declared in rules().
hasContentColumn()Returns whether this field has a column in the content table.
hasErrors()Returns a value indicating whether there is any validation error.
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasMethod()Returns a value indicating whether a method is defined.
hasProperty()Returns a value indicating whether a property is defined.
init()Initializes the object.
instance()Returns static class instance, which can be used to obtain meta information.
isAttributeActive()Returns a value indicating whether the attribute is active in the current scenario.
isAttributeRequired()Returns a value indicating whether the attribute is required.
isAttributeSafe()Returns a value indicating whether the attribute is safe for massive assignments.
isEmpty()
isSelectable()Returns whether the component should be selectable in component Type selects.
isValueEmpty()Returns whether the given value should be considered “empty” to a validator.
load()Populates the model with input data.
loadMultiple()Populates a set of models with the data from end user.
modifyElementIndexQuery()Modifies an element index query.
modifyElementsQuery()Modifies an element query.
normalizeValue()Normalizes the field’s value for use.
off()Detaches an existing event handler from this component.
offsetExists()Returns whether there is an element at the specified offset.
offsetGet()Returns the element at the specified offset.
offsetSet()Sets the element at the specified offset.
offsetUnset()Sets the element value at the specified offset to null.
on()Attaches an event handler to an event.
onUnsafeAttribute()This method is invoked when an unsafe attribute is being massively assigned.
rules()Returns the validation rules for attributes.
safeAttributes()Returns the attribute names that are safe to be massively assigned in the current scenario.
scenarios()Returns a list of scenarios and the corresponding active attributes.
serializeValue()Prepares the field’s value to be stored somewhere, like the content table or JSON-encoded in an entry revision table.
setAttributes()Sets the attribute values in a massive way.
setBlockTypes()Sets the block types.
setIsFresh()Sets whether the field is fresh.
setScenario()Sets the scenario for the model.
settingsAttributes()Returns the list of settings attribute names.
supportedTranslationMethods()Returns which translation methods the field supports.
toArray()Converts the model into an array.
trigger()Triggers an event.
validate()Validates the component.
validateBlocks()Validates an owner element’s Matrix blocks.
validateMultiple()Validates multiple models.

afterElementSave()

Performs actions after the element has been saved.

View source

Arguments

Signature

public void afterElementSave ( craft\base\ElementInterface $element, \craft\fields\bool $isNew )

afterSave()

Performs actions after a component is saved.

View source

Arguments

  • $isNew (boolean) – Whether the component is brand new

Signature

public void afterSave ( \craft\fields\bool $isNew )

beforeDelete()

Performs actions before a component is deleted.

View source

Returns

boolean – Whether the component should be deleted

Signature

public boolean beforeDelete ( )

beforeElementDelete()

Performs actions before an element is deleted.

View source

Arguments

Returns

boolean – Whether the element should be deleted

Signature

public boolean beforeElementDelete ( craft\base\ElementInterface $element )

displayName()

Returns the display name of this class.

View source

Returns

string – The display name of this class.

Signature

public static string displayName ( )

getBlockTypeFields()

Returns all of the block types' fields.

View source

Returns

craft\base\FieldInterface[]

Signature

public craft\base\FieldInterface[] getBlockTypeFields ( )

getBlockTypes()

Returns the block types.

View source

Returns

craft\models\MatrixBlockType[]

Signature

public craft\models\MatrixBlockType[] getBlockTypes ( )

getEagerLoadingMap()

Returns an array that maps source-to-target element IDs based on this custom field.

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

  • elementType – the fully qualified class name of the element type that should be eager-loaded
  • map – an array of element ID mappings, where each element is a sub-array with source and target keys.
  • criteria(optional) – Any criteria parameters that should be applied to the element query when fetching the eager-loaded elements.

View source

Arguments

Returns

array, false – The eager-loading element ID mappings, or false if no mappings exist

Signature

public array, false getEagerLoadingMap ( array $sourceElements )

getElementValidationRules()

Returns the validation rules for an element with this field.

Rules should be defined in the array syntax required by yii\base\Model::rules(), with one difference: you can skip the first argument (the attribute list).

[
    // explicitly specify the field attribute
    [$this->handle, 'string', 'min' => 3, 'max' => 12],
    // skip the field attribute
    ['string', 'min' => 3, 'max' => 12],
    // you can only pass the validator class name/handle if not setting any params
    'bool',
]

To register validation rules that should only be enforced for live elements, set the rule scenario to live:

[
    ['string', 'min' => 3, 'max' => 12, 'on' => \craft\base\Element::SCENARIO_LIVE],
]

View source

Returns

array

Signature

public array getElementValidationRules ( )

getInputHtml()

Returns the field’s input HTML.

An extremely simple implementation would be to directly return some HTML:

return '<textarea name="'.$name.'">'.$value.'</textarea>';

For more complex inputs, you might prefer to create a template, and render it via craft\web\View::renderTemplate(). For example, the following code would render a template located at path/to/myplugin/templates/_fieldinput.html, passing the $name and $value variables to it:

return Craft::$app->view->renderTemplate('myplugin/_fieldinput', [
    'name'  => $name,
    'value' => $value
]);

If you need to tie any JavaScript code to your input, it’s important to know that any name= and id= attributes within the returned HTML will probably get namespaced, however your JavaScript code will be left untouched. For example, if getInputHtml() returns the following HTML:

<textarea id="foo" name="foo"></textarea>
<script type="text/javascript">
    var textarea = document.getElementById('foo');
</script>

…then it might actually look like this before getting output to the browser:

<textarea id="namespace-foo" name="namespace[foo]"></textarea>
<script type="text/javascript">
    var textarea = document.getElementById('foo');
</script>

As you can see, that JavaScript code will not be able to find the textarea, because the textarea’s id= attribute was changed from foo to namespace-foo. Before you start adding namespace- to the beginning of your element ID selectors, keep in mind that the actual namespace is going to change depending on the context. Often they are randomly generated. So it’s not quite that simple.

Thankfully, craft\web\View provides a couple handy methods that can help you deal with this:

So here’s what a getInputHtml() method that includes field-targeting JavaScript code might look like:

public function getInputHtml($value, $element)
{
    // Come up with an ID value based on $name
    $id = Craft::$app->view->formatInputId($name);
    // Figure out what that ID is going to be namespaced into
    $namespacedId = Craft::$app->view->namespaceInputId($id);
    // Render and return the input template
    return Craft::$app->view->renderTemplate('myplugin/_fieldinput', [
        'name'         => $name,
        'id'           => $id,
        'namespacedId' => $namespacedId,
        'value'        => $value
    ]);
}

And the _fieldinput.html template might look like this:

<textarea id="{{ id }}" name="{{ name }}">{{ value }}</textarea>
<script type="text/javascript">
    var textarea = document.getElementById('{{ namespacedId }}');
</script>

The same principles also apply if you’re including your JavaScript code with craft\web\View::registerJs().

View source

Arguments

  • $value (mixed) – The field’s value. This will either be the normalized value, raw POST data (i.e. if there was a validation error), or null
  • $element (craft\base\ElementInterface, null) – The element the field is associated with, if there is one

Returns

string – The input HTML.

Signature

public string getInputHtml ( $value, craft\base\ElementInterface $element = null )

getIsTranslatable()

Returns whether the field should be shown as translatable in the UI.

Note this method has no effect on whether the field’s value will get copied over to other sites when the entry is actually getting saved. That is determined by getTranslationKey().

View source

Arguments

Returns

boolean

Signature

public boolean getIsTranslatable ( craft\base\ElementInterface $element = null )

getSearchKeywords()

Returns the search keywords that should be associated with this field.

The keywords can be separated by commas and/or whitespace; it doesn’t really matter. craft\services\Search will be able to find the individual keywords in whatever string is returned, and normalize them for you.

View source

Arguments

  • $value (mixed) – The field’s value
  • $element (craft\base\ElementInterface) – The element the field is associated with, if there is one

Returns

string – A string of search keywords.

Signature

public string getSearchKeywords ( $value, craft\base\ElementInterface $element )

getSettingsHtml()

Returns the component’s settings HTML.

An extremely simple implementation would be to directly return some HTML:

return '<textarea name="foo">'.$this->foo.'</textarea>';

For more complex settings, you might prefer to create a template, and render it via craft\web\View::renderTemplate(). For example, the following code would render a template located at src/templates/_settings.html, passing the settings to it:

return Craft::$app->view->renderTemplate('plugin-handle/_widget-settings', [
    'widget' => $this
]);

If you need to tie any JavaScript code to your settings, it’s important to know that any name= and id= attributes within the returned HTML will probably get namespaced, however your JavaScript code will be left untouched. For example, if getSettingsHtml() returns the following HTML:

<textarea id="foo" name="foo"></textarea>
<script type="text/javascript">
    var textarea = document.getElementById('foo');
</script>

…then it might actually look like this before getting output to the browser:

<textarea id="namespace-foo" name="namespace[foo]"></textarea>
<script type="text/javascript">
    var textarea = document.getElementById('foo');
</script>

As you can see, that JavaScript code will not be able to find the textarea, because the textarea’s id= attribute was changed from foo to namespace-foo. Before you start adding namespace- to the beginning of your element ID selectors, keep in mind that the actual namespace is going to change depending on the context. Often they are randomly generated. So it’s not quite that simple.

Thankfully, craft\web\View service provides a couple handy methods that can help you deal with this:

So here’s what a getSettingsHtml() method that includes field-targeting JavaScript code might look like:

public function getSettingsHtml()
{
    // Come up with an ID value for 'foo'
    $id = Craft::$app->getView()->formatInputId('foo');
    // Figure out what that ID is going to be namespaced into
    $namespacedId = Craft::$app->view->namespaceInputId($id);
    // Render and return the input template
    return Craft::$app->view->renderTemplate('plugin-handle/_widget-settings', [
        'id'           => $id,
        'namespacedId' => $namespacedId,
        'widget'       => $this
    ]);
}

And the _widget-settings.twig template might look like this:

<textarea id="{{ id }}" name="foo">{{ widget.foo }}</textarea>
<script type="text/javascript">
    var textarea = document.getElementById('{{ namespacedId }}');
</script>

The same principles also apply if you’re including your JavaScript code with craft\web\View::registerJs().

View source

Returns

string, null

Signature

public string, null getSettingsHtml ( )

getStaticHtml()

Returns a static (non-editable) version of the field’s input HTML.

This function is called to output field values when viewing entry drafts.

View source

Arguments

Returns

string – The static version of the field’s input HTML

Signature

public string getStaticHtml ( $value, craft\base\ElementInterface $element )

hasContentColumn()

Returns whether this field has a column in the content table.

View source

Returns

boolean

Signature

public static boolean hasContentColumn ( )

isValueEmpty()

Returns whether the given value should be considered “empty” to a validator.

View source

Arguments

  • $value (mixed) – The field’s value
  • $element (craft\base\ElementInterface) – The element the field is associated with, if there is one

Returns

boolean – Whether the value should be considered “empty”

Signature

public boolean isValueEmpty ( $value, craft\base\ElementInterface $element )

modifyElementsQuery()

Modifies an element query.

This method will be called whenever elements are being searched for that may have this field assigned to them. If the method returns false, the query will be stopped before it ever gets a chance to execute.

View source

Arguments

Returns

null, falsefalse in the event that the method is sure that no elements are going to be found.

Signature

public null, false modifyElementsQuery ( craft\elements\db\ElementQueryInterface $query, $value )

normalizeValue()

Normalizes the field’s value for use.

This method is called when the field’s value is first accessed from the element. For example, the first time entry.myFieldHandle is called from a template, or right before getInputHtml() is called. Whatever this method returns is what entry.myFieldHandle will likewise return, and what getInputHtml()’s and serializeValue()’s $value arguments will be set to.

View source

Arguments

Returns

mixed – The prepared field value

Signature

public mixed normalizeValue ( $value, craft\base\ElementInterface $element = null )

rules()

Returns the validation rules for attributes.

Validation rules are used by validate() to check if attribute values are valid. Child classes may override this method to declare different validation rules.

Each rule is an array with the following structure:

[
    ['attribute1', 'attribute2'],
    'validator type',
    'on' => ['scenario1', 'scenario2'],
    //...other parameters...
]

where

  • attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
  • validator type: required, specifies the validator to be used. It can be a built-in validator name, a method name of the model class, an anonymous function, or a validator class name.
  • on: optional, specifies the scenarios array in which the validation rule can be applied. If this option is not set, the rule will apply to all scenarios.
  • additional name-value pairs can be specified to initialize the corresponding validator properties. Please refer to individual validator class API for possible properties.

A validator can be either an object of a class extending \craft\fields\Validator, or a model class method (called inline validator) that has the following signature:

// $params refers to validation parameters given in the rule
function validatorName($attribute, $params)

In the above $attribute refers to the attribute currently being validated while $params contains an array of validator configuration options such as max in case of string validator. The value of the attribute currently being validated can be accessed as $this->$attribute. Note the $ before attribute; this is taking the value of the variable $attribute and using it as the name of the property to access.

Yii also provides a set of \craft\fields\Validator::builtInValidators. Each one has an alias name which can be used when specifying a validation rule.

Below are some examples:

[
    // built-in "required" validator
    [['username', 'password'], 'required'],
    // built-in "string" validator customized with "min" and "max" properties
    ['username', 'string', 'min' => 3, 'max' => 12],
    // built-in "compare" validator that is used in "register" scenario only
    ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
    // an inline validator defined via the "authenticate()" method in the model class
    ['password', 'authenticate', 'on' => 'login'],
    // a validator of class "DateRangeValidator"
    ['dateRange', 'DateRangeValidator'],
];

Note, in order to inherit rules defined in the parent class, a child class needs to merge the parent rules with child rules using functions such as array_merge().

View source

Returns

array – Validation rules

Signature

public array rules ( )

serializeValue()

Prepares the field’s value to be stored somewhere, like the content table or JSON-encoded in an entry revision table.

Data types that are JSON-encodable are safe (arrays, integers, strings, booleans, etc). Whatever this returns should be something normalizeValue() can handle.

View source

Arguments

Returns

mixed – The serialized field value

Signature

public mixed serializeValue ( $value, craft\base\ElementInterface $element = null )

setBlockTypes()

Sets the block types.

View source

Arguments

Signature

public void setBlockTypes ( $blockTypes )

supportedTranslationMethods()

Returns which translation methods the field supports.

This method should return an array with at least one of the following values:

  • 'none' (values will always be copied to other sites)
  • 'language' (values will be copied to other sites with the same language)
  • 'site' (values will never be copied to other sites)
  • 'custom' (values will be copied/not copied depending on a custom translation key)

View source

Returns

string[]

Signature

public static string[] supportedTranslationMethods ( )

validate()

Validates the component.

View source

Arguments

  • $attributeNames (string[], null) – List of attribute names that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated.
  • $clearErrors (boolean) – Whether existing errors should be cleared before performing validation

Returns

boolean – Whether the validation is successful without any error.

Signature

public boolean validate ( $attributeNames = null, $clearErrors = true )

validateBlocks()

Validates an owner element’s Matrix blocks.

View source

Arguments

Signature

public void validateBlocks ( craft\base\ElementInterface $element )

Protected Methods

MethodDescription
extractFieldsFor()Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id".
extractRootFields()Extracts the root field names from nested fields.
isFresh()Returns whether this is the first time the element's content has been edited.
requestParamName()Returns the field’s param name on the request.
resolveFields()Determines which fields can be returned by toArray().

Constants

ConstantDescription
SCENARIO_DEFAULTThe name of the default scenario.
TRANSLATION_METHOD_CUSTOM
TRANSLATION_METHOD_LANGUAGE
TRANSLATION_METHOD_NONE
TRANSLATION_METHOD_SITE
TRANSLATION_METHOD_SITE_GROUP