Model

Type
Abstract Class
Namespace
craft\base
Inherits
craft\base\Model » yii\base\Model (opens new window) » yii\base\Component (opens new window) » yii\base\BaseObject (opens new window)
Implements
ArrayAccess (opens new window), IteratorAggregate (opens new window), craft\base\ModelInterface, yii\base\Arrayable (opens new window), yii\base\Configurable (opens new window), yii\base\StaticInstanceInterface (opens new window)
Uses traits
craft\base\ClonefixTrait, yii\base\ArrayableTrait (opens new window), yii\base\StaticInstanceTrait (opens new window)
Extended by
craft\assetpreviews\Image, craft\assetpreviews\Pdf, craft\assetpreviews\Text, craft\assetpreviews\Video, craft\base\AssetPreviewHandler, craft\base\Component, craft\base\ConfigurableComponent, craft\base\Element, craft\base\ElementAction, craft\base\ElementExporter, craft\base\Field, craft\base\FieldLayoutComponent, craft\base\FieldLayoutElement, craft\base\Fs, craft\base\SavableComponent, craft\base\Utility, craft\base\Widget, craft\base\conditions\BaseCondition, craft\base\conditions\BaseConditionRule, craft\base\conditions\BaseDateRangeConditionRule, craft\base\conditions\BaseElementSelectConditionRule, craft\base\conditions\BaseLightswitchConditionRule, craft\base\conditions\BaseMultiSelectConditionRule, craft\base\conditions\BaseNumberConditionRule, craft\base\conditions\BaseSelectConditionRule, craft\base\conditions\BaseTextConditionRule, craft\config\BaseConfig, craft\config\DbConfig, craft\config\GeneralConfig, craft\elements\Address, craft\elements\Asset, craft\elements\Category, craft\elements\Entry, craft\elements\GlobalSet, craft\elements\MatrixBlock, craft\elements\Tag, craft\elements\User, craft\elements\actions\CopyReferenceTag, craft\elements\actions\CopyUrl, craft\elements\actions\Delete, craft\elements\actions\DeleteAssets, craft\elements\actions\DeleteForSite, craft\elements\actions\DeleteUsers, craft\elements\actions\DownloadAssetFile, craft\elements\actions\Duplicate, craft\elements\actions\Edit, craft\elements\actions\EditImage, craft\elements\actions\MoveAssets, craft\elements\actions\NewChild, craft\elements\actions\NewSiblingAfter, craft\elements\actions\NewSiblingBefore, craft\elements\actions\PreviewAsset, craft\elements\actions\RenameFile, craft\elements\actions\ReplaceFile, craft\elements\actions\Restore, craft\elements\actions\SetStatus, craft\elements\actions\SuspendUsers, craft\elements\actions\UnsuspendUsers, craft\elements\actions\View, craft\elements\conditions\DateCreatedConditionRule, craft\elements\conditions\DateUpdatedConditionRule, craft\elements\conditions\ElementCondition, craft\elements\conditions\HasUrlConditionRule, craft\elements\conditions\IdConditionRule, craft\elements\conditions\LevelConditionRule, craft\elements\conditions\RelatedToConditionRule, craft\elements\conditions\SiteConditionRule, craft\elements\conditions\SlugConditionRule, craft\elements\conditions\StatusConditionRule, craft\elements\conditions\TitleConditionRule, craft\elements\conditions\UriConditionRule, craft\elements\conditions\addresses\AddressCondition, craft\elements\conditions\addresses\AdministrativeAreaConditionRule, craft\elements\conditions\addresses\CountryConditionRule, craft\elements\conditions\assets\AssetCondition, craft\elements\conditions\assets\DateModifiedConditionRule, craft\elements\conditions\assets\FileSizeConditionRule, craft\elements\conditions\assets\FileTypeConditionRule, craft\elements\conditions\assets\FilenameConditionRule, craft\elements\conditions\assets\HasAltConditionRule, craft\elements\conditions\assets\HeightConditionRule, craft\elements\conditions\assets\SavableConditionRule, craft\elements\conditions\assets\UploaderConditionRule, craft\elements\conditions\assets\ViewableConditionRule, craft\elements\conditions\assets\VolumeConditionRule, craft\elements\conditions\assets\WidthConditionRule, craft\elements\conditions\categories\CategoryCondition, craft\elements\conditions\categories\GroupConditionRule, craft\elements\conditions\entries\AuthorConditionRule, craft\elements\conditions\entries\AuthorGroupConditionRule, craft\elements\conditions\entries\EntryCondition, craft\elements\conditions\entries\ExpiryDateConditionRule, craft\elements\conditions\entries\PostDateConditionRule, craft\elements\conditions\entries\SavableConditionRule, craft\elements\conditions\entries\SectionConditionRule, craft\elements\conditions\entries\TypeConditionRule, craft\elements\conditions\entries\ViewableConditionRule, craft\elements\conditions\tags\GroupConditionRule, craft\elements\conditions\tags\TagCondition, craft\elements\conditions\users\AdminConditionRule, craft\elements\conditions\users\CredentialedConditionRule, craft\elements\conditions\users\EmailConditionRule, craft\elements\conditions\users\FirstNameConditionRule, craft\elements\conditions\users\GroupConditionRule, craft\elements\conditions\users\LastLoginDateConditionRule, craft\elements\conditions\users\LastNameConditionRule, craft\elements\conditions\users\UserCondition, craft\elements\conditions\users\UsernameConditionRule, craft\elements\exporters\Expanded, craft\elements\exporters\Raw, craft\fieldlayoutelements\BaseField, craft\fieldlayoutelements\BaseNativeField, craft\fieldlayoutelements\BaseUiElement, craft\fieldlayoutelements\CustomField, craft\fieldlayoutelements\FullNameField, craft\fieldlayoutelements\Heading, craft\fieldlayoutelements\HorizontalRule, craft\fieldlayoutelements\Html, craft\fieldlayoutelements\LineBreak, craft\fieldlayoutelements\Template, craft\fieldlayoutelements\TextField, craft\fieldlayoutelements\TextareaField, craft\fieldlayoutelements\Tip, craft\fieldlayoutelements\TitleField, craft\fieldlayoutelements\addresses\AddressField, craft\fieldlayoutelements\addresses\CountryCodeField, craft\fieldlayoutelements\addresses\LabelField, craft\fieldlayoutelements\addresses\LatLongField, craft\fieldlayoutelements\addresses\OrganizationField, craft\fieldlayoutelements\addresses\OrganizationTaxIdField, craft\fieldlayoutelements\assets\AltField, craft\fieldlayoutelements\assets\AssetTitleField, craft\fieldlayoutelements\entries\EntryTitleField, craft\fieldlayoutelements\users\AddressesField, craft\fields\Assets, craft\fields\BaseOptionsField, craft\fields\BaseRelationField, craft\fields\Categories, craft\fields\Checkboxes, craft\fields\Color, craft\fields\Country, craft\fields\Date, craft\fields\Dropdown, craft\fields\Email, craft\fields\Entries, craft\fields\Lightswitch, craft\fields\Matrix, craft\fields\MissingField, craft\fields\Money, craft\fields\MultiSelect, craft\fields\Number, craft\fields\PlainText, craft\fields\RadioButtons, craft\fields\Table, craft\fields\Tags, craft\fields\Time, craft\fields\Url, craft\fields\Users, craft\fields\conditions\CountryFieldConditionRule, craft\fields\conditions\DateFieldConditionRule, craft\fields\conditions\EmptyFieldConditionRule, craft\fields\conditions\LightswitchFieldConditionRule, craft\fields\conditions\NumberFieldConditionRule, craft\fields\conditions\OptionsFieldConditionRule, craft\fields\conditions\RelationalFieldConditionRule, craft\fields\conditions\TextFieldConditionRule, craft\fs\Local, craft\fs\MissingFs, craft\fs\Temp, craft\gql\ArgumentManager, craft\gql\ElementQueryConditionBuilder, craft\gql\TypeManager, craft\gql\base\ElementMutationResolver, craft\gql\base\MutationResolver, craft\gql\resolvers\mutations\Asset, craft\gql\resolvers\mutations\Category, craft\gql\resolvers\mutations\Entry, craft\gql\resolvers\mutations\GlobalSet, craft\gql\resolvers\mutations\Tag, craft\imagetransforms\FallbackTransformer, craft\imagetransforms\ImageTransformer, craft\mail\transportadapters\BaseTransportAdapter, craft\mail\transportadapters\Gmail, craft\mail\transportadapters\Sendmail, craft\mail\transportadapters\Smtp, craft\models\AssetIndexData, craft\models\AssetIndexingSession, craft\models\CategoryGroup, craft\models\CategoryGroup_SiteSettings, craft\models\CraftIdToken, craft\models\CraftSupport, craft\models\DeprecationError, craft\models\EntryType, craft\models\FieldGroup, craft\models\FieldLayout, craft\models\FieldLayoutForm, craft\models\FieldLayoutFormTab, craft\models\FieldLayoutTab, craft\models\FolderCriteria, craft\models\FsListing, craft\models\GqlSchema, craft\models\GqlToken, craft\models\ImageTransform, craft\models\ImageTransformIndex, craft\models\Info, craft\models\MailSettings, craft\models\MatrixBlockType, craft\models\ProjectConfigData, craft\models\ReadOnlyProjectConfigData, craft\models\Section, craft\models\Section_SiteSettings, craft\models\Site, craft\models\SiteGroup, craft\models\Structure, craft\models\SystemMessage, craft\models\TagGroup, craft\models\Update, craft\models\UpdateRelease, craft\models\Updates, craft\models\Url, craft\models\UserGroup, craft\models\Volume, craft\models\VolumeFolder, craft\test\EventItem, craft\test\console\CommandTestItem, craft\test\mockclasses\components\ComponentExample, craft\test\mockclasses\components\DependencyHeavyComponentExample, craft\test\mockclasses\components\EventTriggeringComponent, craft\test\mockclasses\components\ExtendedComponentExample, craft\test\mockclasses\elements\ExampleElement, craft\test\mockclasses\models\ExampleModel, craft\utilities\AssetIndexes, craft\utilities\ClearCaches, craft\utilities\DbBackup, craft\utilities\DeprecationErrors, craft\utilities\FindAndReplace, craft\utilities\Migrations, craft\utilities\PhpInfo, craft\utilities\ProjectConfig, craft\utilities\QueueManager, craft\utilities\SystemMessages, craft\utilities\SystemReport, craft\utilities\Updates, craft\utilities\Upgrade, craft\widgets\CraftSupport, craft\widgets\Feed, craft\widgets\MissingWidget, craft\widgets\MyDrafts, craft\widgets\NewUsers, craft\widgets\QuickPost, craft\widgets\RecentEntries, craft\widgets\Updates
Since
3.0.0

Model base class.

View source (opens new window)

# Public Properties

Property Description
activeValidators (opens new window) yii\validators\Validator (opens new window) – The validators applicable to the current scenario (opens new window).
attributes (opens new window) array (opens new window) – Attribute values (name => value).
behaviors (opens new window) yii\base\Behavior (opens new window) – List of behaviors attached to this component.
errors (opens new window) array (opens new window) – Errors for all attributes or the specified attribute.
firstErrors (opens new window) array (opens new window) – The first errors.
iterator (opens new window) ArrayIterator (opens new window) – An iterator for traversing the items in the list.
scenario (opens new window) string (opens new window) – The scenario that this model is in.
validators (opens new window) ArrayObject (opens new window), yii\validators\Validator (opens new window) – All the validators declared in the model.

# Public Methods

Method Description
__call() (opens new window) Calls the named method which is not a class method.
__clone()
__construct()
__get() (opens new window) Returns the value of a component property.
__isset() (opens new window) Checks if a property is set, i.e. defined and not null.
__set() (opens new window) Sets the value of a component property.
__unset() (opens new window) Sets a component property to be null.
activeAttributes() (opens new window) Returns the attribute names that are subject to validation in the current scenario.
addError() (opens new window) Adds a new error to the specified attribute.
addErrors() (opens new window) Adds a list of errors.
addModelErrors() Adds errors from another model, with a given attribute name prefix.
afterValidate() (opens new window) This method is invoked after validation ends.
attachBehavior() (opens new window) Attaches a behavior to this component.
attachBehaviors() (opens new window) Attaches a list of behaviors to the component.
attributeHints() (opens new window) Returns the attribute hints.
attributeLabels() (opens new window) Returns the attribute labels.
attributes() (opens new window) Returns the list of attribute names.
beforeValidate() (opens new window) This method is invoked before validation starts.
behaviors() Returns a list of behaviors that this component should behave as.
canGetProperty() (opens new window) Returns a value indicating whether a property can be read.
canSetProperty() (opens new window) Returns a value indicating whether a property can be set.
className() (opens new window) Returns the fully qualified name of this class.
clearErrors() (opens new window) Removes errors for all attributes or a single attribute.
createValidators() (opens new window) Creates validator objects based on the validation rules specified in rules() (opens new window).
datetimeAttributes() Returns the names of any attributes that should hold DateTime (opens new window) values.
detachBehavior() (opens new window) Detaches a behavior from the component.
detachBehaviors() (opens new window) Detaches all behaviors from the component.
ensureBehaviors() (opens new window) Makes sure that the behaviors declared in behaviors() (opens new window) are attached to this component.
extraFields() Returns the list of fields that can be expanded further and returned by toArray() (opens new window).
fields() Returns the list of fields that should be returned by default by toArray() (opens new window) when no specific fields are specified.
formName() (opens new window) Returns the form name that this model class should use.
generateAttributeLabel() (opens new window) Generates a user friendly attribute label based on the give attribute name.
getActiveValidators() (opens new window) Returns the validators applicable to the current scenario (opens new window).
getAttributeHint() (opens new window) Returns the text hint for the specified attribute.
getAttributeLabel() (opens new window) Returns the text label for the specified attribute.
getAttributes() (opens new window) Returns attribute values.
getBehavior() (opens new window) Returns the named behavior object.
getBehaviors() (opens new window) Returns all behaviors attached to this component.
getErrorSummary() (opens new window) Returns the errors for all attributes as a one-dimensional array.
getErrors() (opens new window) Returns the errors for all attributes or a single attribute.
getFirstError() (opens new window) Returns the first error of the specified attribute.
getFirstErrors() (opens new window) Returns the first error of every attribute in the model.
getIterator() (opens new window) Returns an iterator for traversing the attributes in the model.
getScenario() (opens new window) Returns the scenario that this model is used in.
getValidators() (opens new window) Returns all the validators declared in rules() (opens new window).
hasErrors() Returns a value indicating whether there is any validation error.
hasEventHandlers() (opens new window) Returns a value indicating whether there is any handler attached to the named event.
hasMethod() (opens new window) Returns a value indicating whether a method is defined.
hasProperty() (opens new window) Returns a value indicating whether a property is defined for this component.
init() Initializes the object.
instance() (opens new window) Returns static class instance, which can be used to obtain meta information.
isAttributeActive() (opens new window) Returns a value indicating whether the attribute is active in the current scenario.
isAttributeRequired() (opens new window) Returns a value indicating whether the attribute is required.
isAttributeSafe() (opens new window) Returns a value indicating whether the attribute is safe for massive assignments.
load() (opens new window) Populates the model with input data.
loadMultiple() (opens new window) Populates a set of models with the data from end user.
off() (opens new window) Detaches an existing event handler from this component.
offsetExists() (opens new window) Returns whether there is an element at the specified offset.
offsetGet() (opens new window) Returns the element at the specified offset.
offsetSet() (opens new window) Sets the element at the specified offset.
offsetUnset() (opens new window) Sets the element value at the specified offset to null.
on() (opens new window) Attaches an event handler to an event.
onUnsafeAttribute() (opens new window) This method is invoked when an unsafe attribute is being massively assigned.
rules() Returns the validation rules for attributes.
safeAttributes() (opens new window) Returns the attribute names that are safe to be massively assigned in the current scenario.
scenarios() (opens new window) Returns a list of scenarios and the corresponding active attributes.
setAttributes() Sets the attribute values in a massive way.
setScenario() (opens new window) Sets the scenario for the model.
toArray() (opens new window) Converts the model into an array.
trigger() (opens new window) Triggers an event.
validate() (opens new window) Performs the data validation.
validateMultiple() (opens new window) Validates multiple models.

# __construct()

View source (opens new window)

Arguments

  • $config

# addModelErrors()

Adds errors from another model, with a given attribute name prefix.

View source (opens new window)

Arguments

# behaviors()

Returns a list of behaviors that this component should behave as.

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from \craft\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() (opens new window) or be detached using detachBehavior() (opens new window). Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

View source (opens new window)

Returns

array (opens new window) – The behavior configurations.

# datetimeAttributes()

DEPRECATED

Deprecated in 4.0.0. Use DateTime (opens new window) type declarations instead.

Returns the names of any attributes that should hold DateTime (opens new window) values.

See also:

View source (opens new window)

Returns

string (opens new window)[]

# extraFields()

Returns the list of fields that can be expanded further and returned by toArray() (opens new window).

This method is similar to fields() except that the list of fields returned by this method are not returned by default by toArray() (opens new window). Only when field names to be expanded are explicitly specified when calling toArray() (opens new window), will their values be exported.

The default implementation returns an empty array.

You may override this method to return a list of expandable fields based on some context information (e.g. the current application user).

View source (opens new window)

Returns

array (opens new window) – The list of expandable field names or field definitions. Please refer to fields() on the format of the return value.

# fields()

Returns the list of fields that should be returned by default by toArray() (opens new window) when no specific fields are specified.

A field is a named element in the returned array by toArray() (opens new window).

This method should return an array of field names or field definitions. If the former, the field name will be treated as an object property name whose value will be used as the field value. If the latter, the array key should be the field name while the array value should be the corresponding field definition which can be either an object property name or a PHP callable returning the corresponding field value. The signature of the callable should be:

function ($model, $field) {
    // return field value
}

For example, the following code declares four fields:

  • email: the field name is the same as the property name email;
  • firstName and lastName: the field names are firstName and lastName, and their values are obtained from the first_name and last_name properties;
  • fullName: the field name is fullName. Its value is obtained by concatenating first_name and last_name.
return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function ($model) {
        return $model->first_name . ' ' . $model->last_name;
    },
];

In this method, you may also want to return different lists of fields based on some context information. For example, depending on scenario (opens new window) or the privilege of the current application user, you may return different sets of visible fields or filter out some fields.

The default implementation of this method returns attributes() (opens new window) indexed by the same attribute names.

View source (opens new window)

Returns

array (opens new window) – The list of field names or field definitions.

# hasErrors()

Returns a value indicating whether there is any validation error.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether there is any error.

# init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

View source (opens new window)

# rules()

Returns the validation rules for attributes.

Validation rules are used by validate() (opens new window) 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 (opens new window) 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 yii\validators\Validator (opens new window), 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 built-in validators (opens new window). 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 (opens new window)

Returns

array (opens new window) – Validation rules

# setAttributes()

Since
4.0.0

Sets the attribute values in a massive way.

View source (opens new window)

Arguments

# Protected Methods

Method Description
defineBehaviors() Returns the behaviors to attach to this class.
defineRules() Returns the validation rules for attributes.
extractFieldsFor() (opens new window) 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() (opens new window) Extracts the root field names from nested fields.
resolveFields() (opens new window) Determines which fields can be returned by toArray() (opens new window).

# defineBehaviors()

Since
4.0.0

Returns the behaviors to attach to this class.

See behaviors() for details about what should be returned.

Models should override this method instead of behaviors() so EVENT_DEFINE_BEHAVIORS handlers can modify the class-defined behaviors.

View source (opens new window)

Returns

array (opens new window)

# defineRules()

Since
3.4.0

Returns the validation rules for attributes.

See rules() for details about what should be returned.

Models should override this method instead of rules() so EVENT_DEFINE_RULES handlers can modify the class-defined rules.

View source (opens new window)

Returns

array (opens new window)

# Constants

Constant Description
SCENARIO_DEFAULT The name of the default scenario.

# Events

# EVENT_DEFINE_BEHAVIORS

Type
craft\events\DefineBehaviorsEvent

The event that is triggered when defining the class behaviors

See also behaviors()

# EVENT_DEFINE_EXTRA_FIELDS

Type
craft\events\DefineFieldsEvent
Since
3.5.0

The event that is triggered when defining the extra arrayable fields

See also extraFields()

# EVENT_DEFINE_FIELDS

Type
craft\events\DefineFieldsEvent
Since
3.5.0

The event that is triggered when defining the arrayable fields

See also fields()

# EVENT_DEFINE_RULES

Type
craft\events\DefineRulesEvent
Since
3.1.0

The event that is triggered when defining the model rules

See also rules()

# EVENT_INIT

Type
yii\base\Event (opens new window)

The event that is triggered after the model's init cycle

See also init()