DynamicModel
API reference › yii › base › DynamicModel
DynamicModel is a model class that supports defining attributes at run-time (the so-called
“dynamic attributes”) using its constructor or defineAttribute(). DynamicModel can be used
to support ad hoc data validation.
The typical usage of DynamicModel is as follows,
public function actionSearch($name, $email){ $model = DynamicModel::validateData(compact('name', 'email'), [ [['name', 'email'], 'string', 'max' => 128], ['email', 'email'], ]); if ($model->hasErrors()) { // validation fails } else { // validation succeeds }}The above example shows how to validate $name and $email with the help of DynamicModel.
The validateData() method creates an instance of DynamicModel, defines the attributes
using the given data (name and email in this example), and then calls Model::validate().
You can check the validation result using hasErrors(), like you do with a normal model.
You may also access the dynamic attributes defined through the model instance, e.g.,
$model->name and $model->email.
Alternatively, you may use the following more “classic” syntax to perform ad-hoc data validation:
$model = new DynamicModel(compact('name', 'email'));$model->addRule(['name', 'email'], 'string', ['max' => 128]) ->addRule('email', 'email') ->validate();Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$activeValidators read-only | yii\[] | The validators applicable to the current $scenario. | Model |
$attributeLabels write-only | string[] | Attribute labels. | DynamicModel |
$attributes | array<string, | Attribute values (name => value). | Model |
$behaviors read-only | array<Behavior<static>> | List of behaviors attached to this component. | Component |
$errors read-only | array<string, | Errors for all attributes. | Model |
$firstErrors read-only | array<string, | The first errors. | Model |
$iterator read-only | ArrayIterator<string, | An iterator for traversing the items in the list. | Model |
$scenario | string | The scenario that this model is in. | Model |
$validators read-only | ArrayObject<int, yii\>|yii\[] | All the validators declared in the model. | Model |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | DynamicModel |
__call() | Calls the named method which is not a class method. | Component |
__clone() | This method is called after the object is created by cloning an existing one. | Model |
__get() | Returns the value of a component property. | DynamicModel |
__isset() | Checks if a property is set, i.e. defined and not null. | DynamicModel |
__set() | Sets the value of a component property. | DynamicModel |
__unset() | Sets a component property to be null. | DynamicModel |
activeAttributes() | Returns the attribute names that are subject to validation in the current scenario. | Model |
addError() | Adds a new error to the specified attribute. | Model |
addErrors() | Adds a list of errors. | Model |
addRule() | Adds a validation rule to this model. | DynamicModel |
afterValidate() | This method is invoked after validation ends. | Model |
attachBehavior() | Attaches a behavior to this component. | Component |
attachBehaviors() | Attaches a list of behaviors to the component. | Component |
attributeHints() | Returns the attribute hints. | Model |
attributeLabels() | Returns the attribute labels. | DynamicModel |
attributes() | Returns the list of attribute names. | DynamicModel |
beforeValidate() | This method is invoked before validation starts. | Model |
behaviors() | Returns a list of behaviors that this component should behave as. | Component |
canGetProperty() | Returns a value indicating whether a property can be read. | DynamicModel |
canSetProperty() | Returns a value indicating whether a property can be set. | DynamicModel |
className() static | Returns the fully qualified name of this class. | BaseObject |
clearErrors() | Removes errors for all attributes or a single attribute. | Model |
createValidators() | Creates validator objects based on the validation rules specified in rules(). | Model |
defineAttribute() | Defines an attribute. | DynamicModel |
detachBehavior() | Detaches a behavior from the component. | Component |
detachBehaviors() | Detaches all behaviors from the component. | Component |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | Component |
extraFields() | Returns the list of fields that can be expanded further and returned by toArray(). | ArrayableTrait |
fields() | Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. | Model |
formName() | Returns the form name that this model class should use. | Model |
generateAttributeLabel() | Generates a user friendly attribute label based on the give attribute name. | Model |
getActiveValidators() | Returns the validators applicable to the current $scenario. | Model |
getAttributeHint() | Returns the text hint for the specified attribute. | Model |
getAttributeLabel() | Returns the text label for the specified attribute. | Model |
getAttributes() | Returns attribute values. | Model |
getBehavior() | Returns the named behavior object. | Component |
getBehaviors() | Returns all behaviors attached to this component. | Component |
getErrors() | Returns the errors for all attributes or a single attribute. | Model |
getErrorSummary() | Returns the errors for all attributes as a one-dimensional array. | Model |
getFirstError() | Returns the first error of the specified attribute. | Model |
getFirstErrors() | Returns the first error of every attribute in the model. | Model |
getIterator() | Returns an iterator for traversing the attributes in the model. | Model |
getScenario() | Returns the scenario that this model is used in. | Model |
getValidators() | Returns all the validators declared in rules(). | Model |
hasAttribute() | Returns a value indicating whether the model has an attribute with the specified name. | DynamicModel |
hasErrors() | Returns a value indicating whether there is any validation error. | Model |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | Component |
hasMethod() | Returns a value indicating whether a method is defined. | Component |
hasProperty() | Returns a value indicating whether a property is defined for this component. | Component |
init() | Initializes the object. | BaseObject |
instance() static | Returns static class instance, which can be used to obtain meta information. | StaticInstanceTrait |
isAttributeActive() | Returns a value indicating whether the attribute is active in the current scenario. | Model |
isAttributeRequired() | Returns a value indicating whether the attribute is required. | Model |
isAttributeSafe() | Returns a value indicating whether the attribute is safe for massive assignments. | Model |
load() | Populates the model with input data. | Model |
loadMultiple() static | Populates a set of models with the data from end user. | Model |
off() | Detaches an existing event handler from this component. | Component |
offsetExists() | Returns whether there is an element at the specified offset. | Model |
offsetGet() | Returns the element at the specified offset. | Model |
offsetSet() | Sets the element at the specified offset. | Model |
offsetUnset() | Sets the element value at the specified offset to null. | Model |
on() | Attaches an event handler to an event. | Component |
onUnsafeAttribute() | This method is invoked when an unsafe attribute is being massively assigned. | Model |
rules() | Returns the validation rules for attributes. | Model |
safeAttributes() | Returns the attribute names that are safe to be massively assigned in the current scenario. | Model |
scenarios() | Returns a list of scenarios and the corresponding active attributes. | Model |
setAttributeLabel() | Sets a label for a single attribute. | DynamicModel |
setAttributeLabels() | Sets the labels for all attributes. | DynamicModel |
setAttributes() | Sets the attribute values in a massive way. | Model |
setScenario() | Sets the scenario for the model. | Model |
toArray() | Converts the model into an array. | ArrayableTrait |
trigger() | Triggers an event. | Component |
undefineAttribute() | Undefines an attribute. | DynamicModel |
validate() | Performs the data validation. | Model |
validateData() static | Validates the given data with the specified validation rules. | DynamicModel |
validateMultiple() static | Validates multiple models. | Model |
extractFieldsFor() protected | 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”. | ArrayableTrait |
extractRootFields() protected | Extracts the root field names from nested fields. | ArrayableTrait |
resolveFields() protected | Determines which fields can be returned by toArray(). | ArrayableTrait |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_BEFORE_VALIDATE | ModelEvent | An event raised at the beginning of validate(). Event name: 'beforeValidate'. | Model |
EVENT_AFTER_VALIDATE | Event | An event raised at the end of validate() Event name: 'afterValidate'. | Model |
Constants
Section titled “Constants”| Constant | Value | Description | Defined by |
|---|---|---|---|
SCENARIO_DEFAULT | 'default' | The name of the default scenario. | Model |
Method details
Section titled “Method details”__construct()
Section titled “__construct() ”public function __construct(array<string, mixed>|string[] $attributes = [], array<string, mixed> $config = [])Constructor.
Parameters
| Parameter | Type | Description |
|---|---|---|
$attributes | array<string, | The attributes (name-value pairs, or names) being defined. |
$config | array<string, | The configuration array to be applied to this object. |
__get()
Section titled “__get() ”public function __get(mixed $name): mixedReturns the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The property name |
Returns
mixed: The property value or the value of a behavior’s property
Throws
UnknownPropertyException: if the property is not definedInvalidCallException: if the property is write-only.
__isset()
Section titled “__isset() ”public function __isset(mixed $name): boolChecks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
falsefor non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property).
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The property name or the event name |
Returns
bool: Whether the named property is set
__set()
Section titled “__set() ”public function __set(mixed $name, mixed $value): mixedSets the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of “on xyz”: attach the handler to the event “xyz”
- a behavior in the format of “as xyz”: attach the behavior named as “xyz”
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The property name or the event name |
$value | mixed | The property value |
Returns
mixed
Throws
UnknownPropertyException: if the property is not definedInvalidCallException: if the property is read-only.
__unset()
Section titled “__unset() ”public function __unset(mixed $name): mixedSets a component property to be null.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property).
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The property name |
Returns
mixed
Throws
InvalidCallException: if the property is read only.
addRule()
Section titled “addRule() ”public function addRule(string|array $attributes, string|yii\validators\Validator|Closure $validator, array $options = []): $thisAdds a validation rule to this model.
You can also directly manipulate $validators to add or remove validation rules.
This method provides a shortcut.
Parameters
| Parameter | Type | Description |
|---|---|---|
$attributes | string| | The attribute(s) to be validated by the rule. |
$validator | string|yii\|Closure | The validator. This can be either: * a built-in validator name listed in builtInValidators; * a method name of the model class; * an anonymous function; * a validator class name. * a Validator. |
$options | array | The options (name-value pairs) to be applied to the validator. |
Returns
$this
attributeLabels()
Section titled “attributeLabels() ”public function attributeLabels(): array<string, string>Returns the attribute labels.
Attribute labels are mainly used for display purpose. For example, given an attribute
firstName, we can declare a label First Name which is more user-friendly and can
be displayed to end users.
By default an attribute label is generated using generateAttributeLabel().
This method allows you to explicitly specify attribute labels.
Note, in order to inherit labels defined in the parent class, a child class needs to
merge the parent labels with child labels using functions such as array_merge().
Returns
array<string, string>: Attribute labels (name => label)
attributes()
Section titled “attributes() ”public function attributes(): string[]Returns the list of attribute names.
By default, this method returns all public non-static properties of the class. You may override this method to change the default behavior.
Returns
string[]: List of attribute names.
canGetProperty()
Section titled “canGetProperty() ”public function canGetProperty(mixed $name, mixed $checkVars = true, mixed $checkBehaviors = true): boolReturns a value indicating whether a property can be read.
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVarsis true); - an attached behavior has a readable property of the given name (when
$checkBehaviorsis true).
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The property name |
$checkVars | mixed | Whether to treat member variables as properties |
$checkBehaviors | mixed | Whether to treat behaviors’ properties as properties of this component |
Returns
bool: Whether the property can be read
canSetProperty()
Section titled “canSetProperty() ”public function canSetProperty(mixed $name, mixed $checkVars = true, mixed $checkBehaviors = true): boolReturns a value indicating whether a property can be set.
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVarsis true); - an attached behavior has a writable property of the given name (when
$checkBehaviorsis true).
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | mixed | The property name |
$checkVars | mixed | Whether to treat member variables as properties |
$checkBehaviors | mixed | Whether to treat behaviors’ properties as properties of this component |
Returns
bool: Whether the property can be written
defineAttribute()
Section titled “defineAttribute() ”public function defineAttribute(string $name, mixed $value = null): mixedDefines an attribute.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The attribute name. |
$value | mixed | The attribute value. |
Returns
mixed
hasAttribute()
Section titled “hasAttribute() ”public function hasAttribute(string $name): boolReturns a value indicating whether the model has an attribute with the specified name.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the attribute. |
Returns
bool: Whether the model has an attribute with the specified name.
Since
2.0.16
setAttributeLabel()
Section titled “setAttributeLabel() ”public function setAttributeLabel(string $attribute, string $label): $thisSets a label for a single attribute.
Parameters
| Parameter | Type | Description |
|---|---|---|
$attribute | string | Attribute name. |
$label | string | Attribute label value. |
Returns
$this
Since
2.0.35
setAttributeLabels()
Section titled “setAttributeLabels() ”public function setAttributeLabels(string[] $labels = []): $thisSets the labels for all attributes.
Parameters
| Parameter | Type | Description |
|---|---|---|
$labels | string[] | Attribute labels. |
Returns
$this
Since
2.0.35
undefineAttribute()
Section titled “undefineAttribute() ”public function undefineAttribute(string $name): mixedUndefines an attribute.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The attribute name. |
Returns
mixed
validateData()
Section titled “validateData() ”public static function validateData(array $data, array $rules = []): staticValidates the given data with the specified validation rules.
This method will create a DynamicModel instance, populate it with the data to be validated, create the specified validation rules, and then validate the data using these rules.
Parameters
| Parameter | Type | Description |
|---|---|---|
$data | array | The data (name-value pairs) to be validated. |
$rules | array | The validation rules. Please refer to Model::rules() on the format of this parameter. |
Returns
static: The model instance that contains the data being validated.
Throws
InvalidConfigException: if a validation rule is not specified correctly.