Skip to content
PHP Ecosystem
Explore

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();
PropertyTypeDescriptionDefined by
$activeValidators read-onlyyii\validators\Validator[]The validators applicable to the current $scenario.Model
$attributeLabels write-onlystring[]Attribute labels.DynamicModel
$attributesarray<string, mixed>Attribute values (name => value).Model
$behaviors read-onlyarray<Behavior<static>>List of behaviors attached to this component.Component
$errors read-onlyarray<string, string[]>Errors for all attributes.Model
$firstErrors read-onlyarray<string, string>The first errors.Model
$iterator read-onlyArrayIterator<string, mixed>An iterator for traversing the items in the list.Model
$scenariostringThe scenario that this model is in.Model
$validators read-onlyArrayObject<int, yii\validators\Validator>|yii\validators\Validator[]All the validators declared in the model.Model
MethodDescriptionDefined 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() staticReturns 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() staticReturns 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() staticPopulates 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() staticValidates the given data with the specified validation rules.DynamicModel
validateMultiple() staticValidates multiple models.Model
extractFieldsFor() protectedExtract 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() protectedExtracts the root field names from nested fields.ArrayableTrait
resolveFields() protectedDetermines which fields can be returned by toArray().ArrayableTrait
EventTypeDescriptionDefined by
EVENT_BEFORE_VALIDATEModelEventAn event raised at the beginning of validate(). Event name: 'beforeValidate'.Model
EVENT_AFTER_VALIDATEEventAn event raised at the end of validate() Event name: 'afterValidate'.Model
ConstantValueDescriptionDefined by
SCENARIO_DEFAULT'default'The name of the default scenario.Model
public function __construct(array<string, mixed>|string[] $attributes = [], array<string, mixed> $config = [])

Constructor.

Parameters

ParameterTypeDescription
$attributesarray<string, mixed>|string[]The attributes (name-value pairs, or names) being defined.
$configarray<string, mixed>The configuration array to be applied to this object.
public function __get(mixed $name): mixed

Returns 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

ParameterTypeDescription
$namemixedThe property name

Returns

mixed: The property value or the value of a behavior’s property

Throws

public function __isset(mixed $name): bool

Checks 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 false for 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

ParameterTypeDescription
$namemixedThe property name or the event name

Returns

bool: Whether the named property is set

public function __set(mixed $name, mixed $value): mixed

Sets 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

ParameterTypeDescription
$namemixedThe property name or the event name
$valuemixedThe property value

Returns

mixed

Throws

public function __unset(mixed $name): mixed

Sets 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

ParameterTypeDescription
$namemixedThe property name

Returns

mixed

Throws

public function addRule(string|array $attributes, string|yii\validators\Validator|Closure $validator, array $options = []): $this

Adds a validation rule to this model.

You can also directly manipulate $validators to add or remove validation rules. This method provides a shortcut.

Parameters

ParameterTypeDescription
$attributesstring|arrayThe attribute(s) to be validated by the rule.
$validatorstring|yii\validators\Validator|ClosureThe 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.
$optionsarrayThe options (name-value pairs) to be applied to the validator.

Returns

$this

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)

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.

public function canGetProperty(mixed $name, mixed $checkVars = true, mixed $checkBehaviors = true): bool

Returns 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 $checkVars is true);
  • an attached behavior has a readable property of the given name (when $checkBehaviors is true).

Parameters

ParameterTypeDescription
$namemixedThe property name
$checkVarsmixedWhether to treat member variables as properties
$checkBehaviorsmixedWhether to treat behaviors’ properties as properties of this component

Returns

bool: Whether the property can be read

public function canSetProperty(mixed $name, mixed $checkVars = true, mixed $checkBehaviors = true): bool

Returns 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 $checkVars is true);
  • an attached behavior has a writable property of the given name (when $checkBehaviors is true).

Parameters

ParameterTypeDescription
$namemixedThe property name
$checkVarsmixedWhether to treat member variables as properties
$checkBehaviorsmixedWhether to treat behaviors’ properties as properties of this component

Returns

bool: Whether the property can be written

public function defineAttribute(string $name, mixed $value = null): mixed

Defines an attribute.

Parameters

ParameterTypeDescription
$namestringThe attribute name.
$valuemixedThe attribute value.

Returns

mixed

public function hasAttribute(string $name): bool

Returns a value indicating whether the model has an attribute with the specified name.

Parameters

ParameterTypeDescription
$namestringThe name of the attribute.

Returns

bool: Whether the model has an attribute with the specified name.

Since

2.0.16

public function setAttributeLabel(string $attribute, string $label): $this

Sets a label for a single attribute.

Parameters

ParameterTypeDescription
$attributestringAttribute name.
$labelstringAttribute label value.

Returns

$this

Since

2.0.35

public function setAttributeLabels(string[] $labels = []): $this

Sets the labels for all attributes.

Parameters

ParameterTypeDescription
$labelsstring[]Attribute labels.

Returns

$this

Since

2.0.35

public function undefineAttribute(string $name): mixed

Undefines an attribute.

Parameters

ParameterTypeDescription
$namestringThe attribute name.

Returns

mixed

public static function validateData(array $data, array $rules = []): static

Validates 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

ParameterTypeDescription
$dataarrayThe data (name-value pairs) to be validated.
$rulesarrayThe 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