Model ​
- Type
- Abstract Class
- Namespace
- craft\base
- Inherits
- craft\base\Model » yii\base\Model » yii\base\Component » yii\base\BaseObject
- Implements
- ArrayAccess, IteratorAggregate, craft\base\ModelInterface, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface
- Uses traits
- craft\base\ClonefixTrait, yii\base\ArrayableTrait, yii\base\StaticInstanceTrait
- 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\HasDescendantsRule, craft\elements\conditions\HasUrlConditionRule, craft\elements\conditions\IdConditionRule, craft\elements\conditions\LanguageConditionRule, craft\elements\conditions\LevelConditionRule, craft\elements\conditions\RelatedToConditionRule, craft\elements\conditions\SiteConditionRule, craft\elements\conditions\SiteGroupConditionRule, 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.
Public Properties ​
Property | Description |
---|---|
activeValidators | yii\validators\Validator – The validators applicable to the current scenario. |
attributes | array – Attribute values (name => value). |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
errors | array – Errors for all attributes or the specified attribute. |
firstErrors | array – The first errors. |
iterator | ArrayIterator – An iterator for traversing the items in the list. |
scenario | string – The scenario that this model is in. |
validators | ArrayObject, yii\validators\Validator – All the validators declared in the model. |
Public Methods ​
Method | Description |
---|---|
__call() | Calls the named method which is not a class method. |
__clone() | This method is called after the object is created by cloning an existing one. |
__construct() | |
__get() | Returns the value of a component property. |
__isset() | Checks if a property is set, i.e. defined and not null. |
__set() | Sets the value of a component property. |
__unset() | Sets a component property to be 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. |
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. |
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. |
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. |
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. |
getIterator() | Returns an iterator for traversing the attributes in the model. |
getScenario() | Returns the scenario that this model is used in. |
getValidators() | Returns all the validators declared in rules(). |
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 for this component. |
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. |
load() | Populates the model with input data. |
loadMultiple() | Populates a set of models with the data from end user. |
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. |
setAttributes() | Sets the attribute values in a massive way. |
setScenario() | Sets the scenario for the model. |
toArray() | Converts the model into an array. |
trigger() | Triggers an event. |
validate() | Performs the data validation. |
validateMultiple() | Validates multiple models. |
__construct()
​
Arguments ​
$config
addModelErrors()
​
Adds errors from another model, with a given attribute name prefix.
Arguments ​
$model
(yii\base\Model) – The other model$attrPrefix
(string) – The prefix that should be added to error attributes when adding them to this model
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() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
Returns ​
array – The behavior configurations.
datetimeAttributes()
​
DEPRECATED
Deprecated in 4.0.0. Use DateTime type declarations instead.
Returns the names of any attributes that should hold DateTime values.
See also:
Returns ​
string[]
extraFields()
​
Returns the list of fields that can be expanded further and returned by toArray().
This method is similar to fields() except that the list of fields returned by this method are not returned by default by toArray(). Only when field names to be expanded are explicitly specified when calling toArray(), 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).
Returns ​
array – 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() when no specific fields are specified.
A field is a named element in the returned array by toArray().
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 nameemail
;firstName
andlastName
: the field names arefirstName
andlastName
, and their values are obtained from thefirst_name
andlast_name
properties;fullName
: the field name isfullName
. Its value is obtained by concatenatingfirst_name
andlast_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 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() indexed by the same attribute names.
Returns ​
array – The list of field names or field definitions.
hasErrors()
​
Returns a value indicating whether there is any validation error.
Arguments ​
Returns ​
boolean – 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.
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 yii\validators\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 built-in validators. 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()
.
Returns ​
array – Validation rules
setAttributes()
​
- Since
- 4.0.0
Sets the attribute values in a massive way.
Arguments ​
$values
(array) – Attribute values (name => value) to be assigned to the model.$safeOnly
(boolean) – Whether the assignments should only be done to the safe attributes. A safe attribute is one that is associated with a validation rule in the current scenario.
Protected Methods ​
Method | Description |
---|---|
defineBehaviors() | Returns the behaviors to attach to this class. |
defineRules() | Returns the validation rules for attributes. |
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. |
resolveFields() | Determines which fields can be returned by toArray(). |
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.
Returns ​
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.
Returns ​
Constants ​
Constant | Description |
---|---|
SCENARIO_DEFAULT | The name of the default scenario. |
Events ​
EVENT_DEFINE_BEHAVIORS ​
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
The event that is triggered after the model's init cycle
See also init()