Class yii\base\DynamicModel
Inheritance | yii\base\DynamicModel » yii\base\Model » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface |
Uses Traits | yii\base\ArrayableTrait, yii\base\StaticInstanceTrait |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/base/DynamicModel.php |
DynamicModel is a model class primarily 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 yii\base\Model::validate().
You can check the validation result by 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();
DynamicModel implements the above ad-hoc data validation feature by supporting the so-called "dynamic attributes". It basically allows an attribute to be defined dynamically through its constructor or defineAttribute().
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$activeValidators | yii\validators\Validator[] | The validators applicable to the current $scenario. This property is read-only. | yii\base\Model |
$attributes | array | Attribute values (name => value). | yii\base\Model |
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component. This property is read-only. | yii\base\Component |
$errors | array | An array of errors for all attributes. Empty array is returned if no error. The result is a two-dimensional array. See getErrors() for detailed description. This property is read-only. | yii\base\Model |
$firstErrors | array | The first errors. The array keys are the attribute names, and the array values are the corresponding error messages. An empty array will be returned if there is no error. This property is read-only. | yii\base\Model |
$iterator | ArrayIterator | An iterator for traversing the items in the list. This property is read-only. | yii\base\Model |
$scenario | string | The scenario that this model is in. Defaults to SCENARIO_DEFAULT. | yii\base\Model |
$validators | ArrayObject|yii\validators\Validator[] | All the validators declared in the model. This property is read-only. | yii\base\Model |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__clone() | This method is called after the object is created by cloning an existing one. | yii\base\Component |
__construct() | Constructors. | yii\base\DynamicModel |
__get() | Returns the value of a component property. | yii\base\DynamicModel |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\base\DynamicModel |
__set() | Sets the value of a component property. | yii\base\DynamicModel |
__unset() | Sets a component property to be null. | yii\base\DynamicModel |
activeAttributes() | Returns the attribute names that are subject to validation in the current scenario. | yii\base\Model |
addError() | Adds a new error to the specified attribute. | yii\base\Model |
addErrors() | Adds a list of errors. | yii\base\Model |
addRule() | Adds a validation rule to this model. | yii\base\DynamicModel |
afterValidate() | This method is invoked after validation ends. | yii\base\Model |
attachBehavior() | Attaches a behavior to this component. | yii\base\Component |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\base\Component |
attributeHints() | Returns the attribute hints. | yii\base\Model |
attributeLabels() | {@inheritDoc} | yii\base\DynamicModel |
attributes() | Returns the list of attribute names. | yii\base\DynamicModel |
beforeValidate() | This method is invoked before validation starts. | yii\base\Model |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\base\Component |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\base\DynamicModel |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\base\DynamicModel |
className() | Returns the fully qualified name of this class. | yii\base\BaseObject |
clearErrors() | Removes errors for all attributes or a single attribute. | yii\base\Model |
createValidators() | Creates validator objects based on the validation rules specified in rules(). | yii\base\Model |
defineAttribute() | Defines an attribute. | yii\base\DynamicModel |
detachBehavior() | Detaches a behavior from the component. | yii\base\Component |
detachBehaviors() | Detaches all behaviors from the component. | yii\base\Component |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
extraFields() | Returns the list of fields that can be expanded further and returned by toArray(). | yii\base\ArrayableTrait |
fields() | Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. | yii\base\ArrayableTrait |
formName() | Returns the form name that this model class should use. | yii\base\Model |
generateAttributeLabel() | Generates a user friendly attribute label based on the give attribute name. | yii\base\Model |
getActiveValidators() | Returns the validators applicable to the current $scenario. | yii\base\Model |
getAttributeHint() | Returns the text hint for the specified attribute. | yii\base\Model |
getAttributeLabel() | Returns the text label for the specified attribute. | yii\base\Model |
getAttributes() | Returns attribute values. | yii\base\Model |
getBehavior() | Returns the named behavior object. | yii\base\Component |
getBehaviors() | Returns all behaviors attached to this component. | yii\base\Component |
getErrorSummary() | Returns the errors for all attributes as a one-dimensional array. | yii\base\Model |
getErrors() | Returns the errors for all attributes or a single attribute. | yii\base\Model |
getFirstError() | Returns the first error of the specified attribute. | yii\base\Model |
getFirstErrors() | Returns the first error of every attribute in the model. | yii\base\Model |
getIterator() | Returns an iterator for traversing the attributes in the model. | yii\base\Model |
getScenario() | Returns the scenario that this model is used in. | yii\base\Model |
getValidators() | Returns all the validators declared in rules(). | yii\base\Model |
hasAttribute() | Returns a value indicating whether the model has an attribute with the specified name. | yii\base\DynamicModel |
hasErrors() | Returns a value indicating whether there is any validation error. | yii\base\Model |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\base\Component |
hasMethod() | Returns a value indicating whether a method is defined. | yii\base\Component |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
init() | Initializes the object. | yii\base\BaseObject |
instance() | Returns static class instance, which can be used to obtain meta information. | yii\base\StaticInstanceTrait |
isAttributeActive() | Returns a value indicating whether the attribute is active in the current scenario. | yii\base\Model |
isAttributeRequired() | Returns a value indicating whether the attribute is required. | yii\base\Model |
isAttributeSafe() | Returns a value indicating whether the attribute is safe for massive assignments. | yii\base\Model |
load() | Populates the model with input data. | yii\base\Model |
loadMultiple() | Populates a set of models with the data from end user. | yii\base\Model |
off() | Detaches an existing event handler from this component. | yii\base\Component |
offsetExists() | Returns whether there is an element at the specified offset. | yii\base\Model |
offsetGet() | Returns the element at the specified offset. | yii\base\Model |
offsetSet() | Sets the element at the specified offset. | yii\base\Model |
offsetUnset() | Sets the element value at the specified offset to null. | yii\base\Model |
on() | Attaches an event handler to an event. | yii\base\Component |
onUnsafeAttribute() | This method is invoked when an unsafe attribute is being massively assigned. | yii\base\Model |
rules() | Returns the validation rules for attributes. | yii\base\Model |
safeAttributes() | Returns the attribute names that are safe to be massively assigned in the current scenario. | yii\base\Model |
scenarios() | Returns a list of scenarios and the corresponding active attributes. | yii\base\Model |
setAttributeLabel() | Sets a label for an attribute. | yii\base\DynamicModel |
setAttributeLabels() | Sets the attribute labels in a massive way. | yii\base\DynamicModel |
setAttributes() | Sets the attribute values in a massive way. | yii\base\Model |
setScenario() | Sets the scenario for the model. | yii\base\Model |
toArray() | Converts the model into an array. | yii\base\ArrayableTrait |
trigger() | Triggers an event. | yii\base\Component |
undefineAttribute() | Undefines an attribute. | yii\base\DynamicModel |
validate() | Performs the data validation. | yii\base\Model |
validateData() | Validates the given data with the specified validation rules. | yii\base\DynamicModel |
validateMultiple() | Validates multiple models. | yii\base\Model |
Protected Methods
Method | Description | Defined By |
---|---|---|
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". | yii\base\ArrayableTrait |
extractRootFields() | Extracts the root field names from nested fields. | yii\base\ArrayableTrait |
resolveFields() | Determines which fields can be returned by toArray(). | yii\base\ArrayableTrait |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_AFTER_VALIDATE | yii\base\Event | An event raised at the end of validate() | yii\base\Model |
EVENT_BEFORE_VALIDATE | yii\base\ModelEvent | An event raised at the beginning of validate(). | yii\base\Model |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
SCENARIO_DEFAULT | 'default' | The name of the default scenario. | yii\base\Model |
Method Details
Constructors.
public void __construct ( array $attributes = [], $config = [] ) | ||
$attributes | array | The dynamic attributes (name-value pairs, or names) being defined |
$config | array | The configuration array to be applied to this object. |
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;
.
public mixed __get ( $name ) | ||
$name | string | The property name |
return | mixed | The property value or the value of a behavior's property |
---|---|---|
throws | yii\base\UnknownPropertyException | if the property is not defined |
throws | yii\base\InvalidCallException | if the property is write-only. |
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)
.
public boolean __isset ( $name ) | ||
$name | string | The property name or the event name |
return | boolean | Whether the named property is set |
---|
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;
.
public void __set ( $name, $value ) | ||
$name | string | The property name or the event name |
$value | mixed | The property value |
throws | yii\base\UnknownPropertyException | if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException | if the property is read-only. |
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)
.
public void __unset ( $name ) | ||
$name | string | The property name |
throws | yii\base\InvalidCallException | if the property is read only. |
---|
Adds a validation rule to this model.
You can also directly manipulate $validators to add or remove validation rules. This method provides a shortcut.
public $this addRule ( $attributes, $validator, $options = [] ) | ||
$attributes | string|array | The attribute(s) to be validated by the rule |
$validator | string|yii\validators\Validator|Closure | The validator. This can be either:
|
$options | array | The options (name-value pairs) to be applied to the validator |
return | $this | The model itself |
---|
{@inheritDoc}
public void attributeLabels ( ) |
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.
public array attributes ( ) | ||
return | array | List of attribute names. |
---|
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).
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string | The property name |
$checkVars | boolean | Whether to treat member variables as properties |
$checkBehaviors | boolean | Whether to treat behaviors' properties as properties of this component |
return | boolean | Whether the property can be read |
---|
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).
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string | The property name |
$checkVars | boolean | Whether to treat member variables as properties |
$checkBehaviors | boolean | Whether to treat behaviors' properties as properties of this component |
return | boolean | Whether the property can be written |
---|
Defines an attribute.
public void defineAttribute ( $name, $value = null ) | ||
$name | string | The attribute name |
$value | mixed | The attribute value |
Returns a value indicating whether the model has an attribute with the specified name.
public boolean hasAttribute ( $name ) | ||
$name | string | The name of the attribute |
return | boolean | Whether the model has an attribute with the specified name. |
---|
public $this setAttributeLabel ( $attribute, $label ) | ||
$attribute | string | Attribute name |
$label | string | Attribute label value |
public $this setAttributeLabels ( array $labels = [] ) | ||
$labels | array | Array of attribute labels |
Undefines an attribute.
public void undefineAttribute ( $name ) | ||
$name | string | The attribute name |
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.
public static static validateData ( array $data, $rules = [] ) | ||
$data | array | The data (name-value pairs) to be validated |
$rules | array | The validation rules. Please refer to yii\base\Model::rules() on the format of this parameter. |
return | static | The model instance that contains the data being validated |
---|---|---|
throws | yii\base\InvalidConfigException | if a validation rule is not specified correctly. |
Signup or Login in order to comment.