SearchRequest
extends Model
in package
Model is the base class for data models.
Model implements the following commonly used features:
- attribute declaration: by default, every public class member is considered as a model attribute
- attribute labels: each attribute may be associated with a label for display purpose
- massive attribute assignment
- scenario-based validation
Model also raises the following events when performing data validation:
- [[EVENT_BEFORE_VALIDATE]]: an event raised at the beginning of [[validate()]]
- [[EVENT_AFTER_VALIDATE]]: an event raised at the end of [[validate()]]
You may directly use Model to store model data, or extend it with customization.
For more details and usage information on Model, see the guide article on models.
Table of Contents
Constants
- DATE_FORMAT = 'short'
- EVENT_AFTER_VALIDATE = 'afterValidate'
- EVENT_BEFORE_VALIDATE = 'beforeValidate'
- ORDER_BY_CREATION_DATE = 'content.created_at'
- ORDER_BY_SCORE = 'score'
- SCENARIO_DEFAULT = 'default'
- The name of the default scenario.
Properties
- $activeValidators : array<string|int, Validator>
- $attributes : array<string|int, mixed>
- $author : array<string|int, mixed>
- $behaviors : array<string|int, Behavior>
- $contentContainer : mixed
- $contentType : mixed
- $dateFrom : string|null
- $dateTo : string|null
- $errors : array<string|int, mixed>
- $firstErrors : array<string|int, mixed>
- $keyword : string
- $orderBy : mixed
- $page : mixed
- $pageSize : int
- $scenario : string
- $searchQuery : SearchQuery|null
- $space : array<string|int, mixed>
- $topic : array<string|int, mixed>
- $user : User|null
- $validators : ArrayObject|array<string|int, Validator>
- $_behaviors : array<string|int, Behavior>|null
- $_errors : array<string|int, mixed>
- $_events : array<string|int, mixed>
- $_eventWildcards : array<string|int, mixed>
- $_instances : array<string|int, static>
- $_scenario : string
- $_validators : ArrayObject
Methods
- __call() : mixed
- Calls the named method which is not a class method.
- __clone() : mixed
- This method is called after the object is created by cloning an existing one.
- __construct() : mixed
- Constructor.
- __get() : mixed
- Returns the value of a component property.
- __isset() : bool
- Checks if a property is set, i.e. defined and not null.
- __set() : mixed
- Sets the value of a component property.
- __unset() : mixed
- Sets a component property to be null.
- activeAttributes() : array<string|int, string>
- Returns the attribute names that are subject to validation in the current scenario.
- addError() : mixed
- Adds a new error to the specified attribute.
- addErrors() : mixed
- Adds a list of errors.
- afterValidate() : mixed
- This method is invoked after validation ends.
- attachBehavior() : Behavior
- Attaches a behavior to this component.
- attachBehaviors() : mixed
- Attaches a list of behaviors to the component.
- attributeHints() : array<string|int, mixed>
- Returns the attribute hints.
- attributeLabels() : array<string|int, mixed>
- Returns the attribute labels.
- attributes() : array<string|int, string>
- Returns the list of attribute names.
- beforeValidate() : bool
- This method is invoked before validation starts.
- behaviors() : array<string|int, mixed>
- Returns a list of behaviors that this component should behave as.
- canGetProperty() : bool
- Returns a value indicating whether a property can be read.
- canSetProperty() : bool
- Returns a value indicating whether a property can be set.
- className() : string
- Returns the fully qualified name of this class.
- clearErrors() : mixed
- Removes errors for all attributes or a single attribute.
- createValidators() : ArrayObject
- Creates validator objects based on the validation rules specified in [[rules()]].
- detachBehavior() : Behavior|null
- Detaches a behavior from the component.
- detachBehaviors() : mixed
- Detaches all behaviors from the component.
- ensureBehaviors() : mixed
- Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
- extraFields() : array<string|int, mixed>
- Returns the list of fields that can be expanded further and returned by [[toArray()]].
- fields() : array<string|int, mixed>
- Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are specified.
- formName() : string
- Returns the form name that this model class should use.
- generateAttributeLabel() : string
- Generates a user friendly attribute label based on the give attribute name.
- getActiveValidators() : array<string|int, Validator>
- Returns the validators applicable to the current [[scenario]].
- getAttributeHint() : string
- Returns the text hint for the specified attribute.
- getAttributeLabel() : string
- Returns the text label for the specified attribute.
- getAttributes() : array<string|int, mixed>
- Returns attribute values.
- getBehavior() : Behavior|null
- Returns the named behavior object.
- getBehaviors() : array<string|int, Behavior>
- Returns all behaviors attached to this component.
- getContentTypes() : array<string|int, mixed>
- getErrors() : array<string|int, mixed>
- Returns the errors for all attributes or a single attribute.
- getErrorSummary() : array<string|int, mixed>
- Returns the errors for all attributes as a one-dimensional array.
- getFirstError() : string|null
- Returns the first error of the specified attribute.
- getFirstErrors() : array<string|int, mixed>
- Returns the first error of every attribute in the model.
- getIterator() : ArrayIterator
- Returns an iterator for traversing the attributes in the model.
- getKeywords() : array<string|int, mixed>
- getScenario() : string
- Returns the scenario that this model is used in.
- getSearchQuery() : SearchQuery
- getValidators() : ArrayObject|array<string|int, Validator>
- Returns all the validators declared in [[rules()]].
- hasErrors() : bool
- Returns a value indicating whether there is any validation error.
- hasEventHandlers() : bool
- Returns a value indicating whether there is any handler attached to the named event.
- hasMethod() : bool
- Returns a value indicating whether a method is defined.
- hasProperty() : bool
- Returns a value indicating whether a property is defined for this component.
- init() : mixed
- Initializes the object.
- instance() : static
- Returns static class instance, which can be used to obtain meta information.
- isAttributeActive() : bool
- Returns a value indicating whether the attribute is active in the current scenario.
- isAttributeRequired() : bool
- Returns a value indicating whether the attribute is required.
- isAttributeSafe() : bool
- Returns a value indicating whether the attribute is safe for massive assignments.
- load() : bool
- Populates the model with input data.
- loadMultiple() : bool
- Populates a set of models with the data from end user.
- off() : bool
- Detaches an existing event handler from this component.
- offsetExists() : bool
- Returns whether there is an element at the specified offset.
- offsetGet() : mixed
- Returns the element at the specified offset.
- offsetSet() : mixed
- Sets the element at the specified offset.
- offsetUnset() : mixed
- Sets the element value at the specified offset to null.
- on() : mixed
- Attaches an event handler to an event.
- onUnsafeAttribute() : mixed
- This method is invoked when an unsafe attribute is being massively assigned.
- rules() : array<string|int, mixed>
- Returns the validation rules for attributes.
- safeAttributes() : array<string|int, string>
- Returns the attribute names that are safe to be massively assigned in the current scenario.
- scenarios() : array<string|int, mixed>
- Returns a list of scenarios and the corresponding active attributes.
- setAttributes() : mixed
- Sets the attribute values in a massive way.
- setScenario() : mixed
- Sets the scenario for the model.
- toArray() : array<string|int, mixed>
- Converts the model into an array.
- trigger() : mixed
- Triggers an event.
- validate() : bool
- Performs the data validation.
- validateMultiple() : bool
- Validates multiple models.
- extractFieldsFor() : array<string|int, mixed>
- 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() : array<string|int, mixed>
- Extracts the root field names from nested fields.
- normalizeDate() : mixed
- resolveFields() : array<string|int, mixed>
- Determines which fields can be returned by [[toArray()]].
- attachBehaviorInternal() : Behavior
- Attaches a behavior to this component.
Constants
DATE_FORMAT
public
mixed
DATE_FORMAT
= 'short'
EVENT_AFTER_VALIDATE
public
mixed
EVENT_AFTER_VALIDATE
= 'afterValidate'
Tags
EVENT_BEFORE_VALIDATE
public
mixed
EVENT_BEFORE_VALIDATE
= 'beforeValidate'
Tags
ORDER_BY_CREATION_DATE
public
mixed
ORDER_BY_CREATION_DATE
= 'content.created_at'
ORDER_BY_SCORE
public
mixed
ORDER_BY_SCORE
= 'score'
SCENARIO_DEFAULT
The name of the default scenario.
public
mixed
SCENARIO_DEFAULT
= 'default'
Properties
$activeValidators read-only
public
array<string|int, Validator>
$activeValidators
The validators applicable to the current [[scenario]].
$attributes
public
array<string|int, mixed>
$attributes
Attribute values (name => value).
$author
public
array<string|int, mixed>
$author
= []
$behaviors read-only
public
array<string|int, Behavior>
$behaviors
List of behaviors attached to this component.
$contentContainer
public
mixed
$contentContainer
= []
$contentType
public
mixed
$contentType
= ''
$dateFrom
public
string|null
$dateFrom
= null
$dateTo
public
string|null
$dateTo
= null
$errors read-only
public
array<string|int, mixed>
$errors
Errors for all attributes or the specified attribute. Empty array is returned
if no error. See [[getErrors()]] for detailed description. Note that when returning errors for all attributes,
the result is a two-dimensional array, like the following: php [ 'username' => [ 'Username is required.', 'Username must contain only word characters.', ], 'email' => [ 'Email address is invalid.', ] ]
.
$firstErrors read-only
public
array<string|int, mixed>
$firstErrors
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.
$keyword
public
string
$keyword
= ''
$orderBy
public
mixed
$orderBy
= self::ORDER_BY_CREATION_DATE
$page
public
mixed
$page
= 1
$pageSize
public
int
$pageSize
= 25
$scenario
public
string
$scenario
The scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
$searchQuery
public
SearchQuery|null
$searchQuery
= null
$space
public
array<string|int, mixed>
$space
= []
$topic
public
array<string|int, mixed>
$topic
= []
$user
public
User|null
$user
= null
$validators read-only
public
ArrayObject|array<string|int, Validator>
$validators
All the validators declared in the model.
$_behaviors
private
array<string|int, Behavior>|null
$_behaviors
the attached behaviors (behavior name => behavior). This is null
when not initialized.
$_errors
private
array<string|int, mixed>
$_errors
validation errors (attribute name => array of errors)
$_events
private
array<string|int, mixed>
$_events
= []
the attached event handlers (event name => handlers)
$_eventWildcards
private
array<string|int, mixed>
$_eventWildcards
= []
the event handlers attached for wildcard patterns (event name wildcard => handlers)
Tags
$_instances
private
static array<string|int, static>
$_instances
= []
static instances in format: [className => object]
$_scenario
private
string
$_scenario
= self::SCENARIO_DEFAULT
current scenario
$_validators
private
ArrayObject
$_validators
list of validators
Methods
__call()
Calls the named method which is not a class method.
public
__call(string $name, array<string|int, mixed> $params) : mixed
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
Parameters
- $name : string
-
the method name
- $params : array<string|int, mixed>
-
method parameters
Tags
Return values
mixed —the method return value
__clone()
This method is called after the object is created by cloning an existing one.
public
__clone() : mixed
__construct()
Constructor.
public
__construct([array<string|int, mixed> $config = [] ]) : mixed
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call [[init()]].
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
Parameters
- $config : array<string|int, mixed> = []
-
name-value pairs that will be used to initialize the object properties
__get()
Returns the value of a component property.
public
__get(string $name) : mixed
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
- $name : string
-
the property name
Tags
Return values
mixed —the property value or the value of a behavior's property
__isset()
Checks if a property is set, i.e. defined and not null.
public
__isset(string $name) : bool
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
- $name : string
-
the property name or the event name
Tags
Return values
bool —whether the named property is set
__set()
Sets the value of a component property.
public
__set(string $name, mixed $value) : mixed
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
- $name : string
-
the property name or the event name
- $value : mixed
-
the property value
Tags
__unset()
Sets a component property to be null.
public
__unset(string $name) : mixed
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
- $name : string
-
the property name
Tags
activeAttributes()
Returns the attribute names that are subject to validation in the current scenario.
public
activeAttributes() : array<string|int, string>
Return values
array<string|int, string> —safe attribute names
addError()
Adds a new error to the specified attribute.
public
addError(string $attribute[, string $error = '' ]) : mixed
Parameters
- $attribute : string
-
attribute name
- $error : string = ''
-
new error message
addErrors()
Adds a list of errors.
public
addErrors(array<string|int, mixed> $items) : mixed
Parameters
- $items : array<string|int, mixed>
-
a list of errors. The array keys must be attribute names. The array values should be error messages. If an attribute has multiple errors, these errors must be given in terms of an array. You may use the result of [[getErrors()]] as the value for this parameter.
Tags
afterValidate()
This method is invoked after validation ends.
public
afterValidate() : mixed
Tags
attachBehavior()
Attaches a behavior to this component.
public
attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.
Parameters
- $name : string
-
the name of the behavior.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior configuration. This can be one of the following:
- a [[Behavior]] object
- a string specifying the behavior class
- an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
Return values
Behavior —the behavior object
attachBehaviors()
Attaches a list of behaviors to the component.
public
attachBehaviors(array<string|int, mixed> $behaviors) : mixed
Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.
Parameters
- $behaviors : array<string|int, mixed>
-
list of behaviors to be attached to the component
Tags
attributeHints()
Returns the attribute hints.
public
attributeHints() : array<string|int, mixed>
Attribute hints are mainly used for display purpose. For example, given an attribute
isPublic
, we can declare a hint Whether the post should be visible for not logged in users
,
which provides user-friendly description of the attribute meaning and can be displayed to end users.
Unlike label hint will not be generated, if its explicit declaration is omitted.
Note, in order to inherit hints defined in the parent class, a child class needs to
merge the parent hints with child hints using functions such as array_merge()
.
Tags
Return values
array<string|int, mixed> —attribute hints (name => hint)
attributeLabels()
Returns the attribute labels.
public
attributeLabels() : array<string|int, mixed>
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()
.
Tags
Return values
array<string|int, mixed> —attribute labels (name => label)
attributes()
Returns the list of attribute names.
public
attributes() : array<string|int, string>
By default, this method returns all public non-static properties of the class. You may override this method to change the default behavior.
Return values
array<string|int, string> —list of attribute names.
beforeValidate()
This method is invoked before validation starts.
public
beforeValidate() : bool
The default implementation raises a beforeValidate
event.
You may override this method to do preliminary checks before validation.
Make sure the parent implementation is invoked so that the event can be raised.
Return values
bool —whether the validation should be executed. Defaults to true. If false is returned, the validation will stop and the model is considered invalid.
behaviors()
Returns a list of behaviors that this component should behave as.
public
behaviors() : array<string|int, mixed>
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 [[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).
Return values
array<string|int, mixed> —the behavior configurations.
canGetProperty()
Returns a value indicating whether a property can be read.
public
canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
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
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be read
canSetProperty()
Returns a value indicating whether a property can be set.
public
canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
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
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be written
className()
Returns the fully qualified name of this class.
public
static className() : string
Tags
Return values
string —the fully qualified name of this class.
clearErrors()
Removes errors for all attributes or a single attribute.
public
clearErrors([string|null $attribute = null ]) : mixed
Parameters
- $attribute : string|null = null
-
attribute name. Use null to remove errors for all attributes.
createValidators()
Creates validator objects based on the validation rules specified in [[rules()]].
public
createValidators() : ArrayObject
Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
Tags
Return values
ArrayObject —validators
detachBehavior()
Detaches a behavior from the component.
public
detachBehavior(string $name) : Behavior|null
The behavior's [[Behavior::detach()]] method will be invoked.
Parameters
- $name : string
-
the behavior's name.
Return values
Behavior|null —the detached behavior. Null if the behavior does not exist.
detachBehaviors()
Detaches all behaviors from the component.
public
detachBehaviors() : mixed
ensureBehaviors()
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
public
ensureBehaviors() : mixed
extraFields()
Returns the list of fields that can be expanded further and returned by [[toArray()]].
public
extraFields() : array<string|int, mixed>
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).
Tags
Return values
array<string|int, mixed> —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.
public
fields() : array<string|int, mixed>
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.
Tags
Return values
array<string|int, mixed> —the list of field names or field definitions.
formName()
Returns the form name that this model class should use.
public
formName() : string
The form name is mainly used by [[\yii\widgets\ActiveForm]] to determine how to name the input fields for the attributes in a model. If the form name is "A" and an attribute name is "b", then the corresponding input name would be "A[b]". If the form name is an empty string, then the input name would be "b".
The purpose of the above naming schema is that for forms which contain multiple different models, the attributes of each model are grouped in sub-arrays of the POST-data and it is easier to differentiate between them.
By default, this method returns the model class name (without the namespace part) as the form name. You may override it when the model is used in different forms.
Tags
Return values
string —the form name of this model class.
generateAttributeLabel()
Generates a user friendly attribute label based on the give attribute name.
public
generateAttributeLabel(string $name) : string
This is done by replacing underscores, dashes and dots with blanks and changing the first letter of each word to upper case. For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
Parameters
- $name : string
-
the column name
Return values
string —the attribute label
getActiveValidators()
Returns the validators applicable to the current [[scenario]].
public
getActiveValidators([string|null $attribute = null ]) : array<string|int, Validator>
Parameters
- $attribute : string|null = null
-
the name of the attribute whose applicable validators should be returned. If this is null, the validators for ALL attributes in the model will be returned.
Return values
array<string|int, Validator> —the validators applicable to the current [[scenario]].
getAttributeHint()
Returns the text hint for the specified attribute.
public
getAttributeHint(string $attribute) : string
Parameters
- $attribute : string
-
the attribute name
Tags
Return values
string —the attribute hint
getAttributeLabel()
Returns the text label for the specified attribute.
public
getAttributeLabel(string $attribute) : string
Parameters
- $attribute : string
-
the attribute name
Tags
Return values
string —the attribute label
getAttributes()
Returns attribute values.
public
getAttributes([array<string|int, mixed>|null $names = null ][, array<string|int, mixed> $except = [] ]) : array<string|int, mixed>
Parameters
- $names : array<string|int, mixed>|null = null
-
list of attributes whose value needs to be returned. Defaults to null, meaning all attributes listed in [[attributes()]] will be returned. If it is an array, only the attributes in the array will be returned.
- $except : array<string|int, mixed> = []
-
list of attributes whose value should NOT be returned.
Return values
array<string|int, mixed> —attribute values (name => value).
getBehavior()
Returns the named behavior object.
public
getBehavior(string $name) : Behavior|null
Parameters
- $name : string
-
the behavior name
Return values
Behavior|null —the behavior object, or null if the behavior does not exist
getBehaviors()
Returns all behaviors attached to this component.
public
getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior> —list of behaviors attached to this component
getContentTypes()
public
static getContentTypes() : array<string|int, mixed>
Return values
array<string|int, mixed>getErrors()
Returns the errors for all attributes or a single attribute.
public
getErrors([string|null $attribute = null ]) : array<string|int, mixed>
Parameters
- $attribute : string|null = null
-
attribute name. Use null to retrieve errors for all attributes.
Tags
Return values
array<string|int, mixed> —errors for all attributes or the specified attribute. Empty array is returned if no error. See [[getErrors()]] for detailed description. Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
[
'username' => [
'Username is required.',
'Username must contain only word characters.',
],
'email' => [
'Email address is invalid.',
]
]
getErrorSummary()
Returns the errors for all attributes as a one-dimensional array.
public
getErrorSummary(bool $showAllErrors) : array<string|int, mixed>
Parameters
- $showAllErrors : bool
-
boolean, if set to true every error message for each attribute will be shown otherwise only the first error message for each attribute will be shown.
Tags
Return values
array<string|int, mixed> —errors for all attributes as a one-dimensional array. Empty array is returned if no error.
getFirstError()
Returns the first error of the specified attribute.
public
getFirstError(string $attribute) : string|null
Parameters
- $attribute : string
-
attribute name.
Tags
Return values
string|null —the error message. Null is returned if no error.
getFirstErrors()
Returns the first error of every attribute in the model.
public
getFirstErrors() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed> —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.
getIterator()
Returns an iterator for traversing the attributes in the model.
public
getIterator() : ArrayIterator
This method is required by the interface [[\IteratorAggregate]].
Attributes
Return values
ArrayIterator —an iterator for traversing the items in the list.
getKeywords()
public
getKeywords() : array<string|int, mixed>
Return values
array<string|int, mixed>getScenario()
Returns the scenario that this model is used in.
public
getScenario() : string
Scenario affects how validation is performed and which attributes can be massively assigned.
Return values
string —the scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
getSearchQuery()
public
getSearchQuery() : SearchQuery
Return values
SearchQuerygetValidators()
Returns all the validators declared in [[rules()]].
public
getValidators() : ArrayObject|array<string|int, Validator>
This method differs from [[getActiveValidators()]] in that the latter only returns the validators applicable to the current [[scenario]].
Because this method returns an ArrayObject object, you may manipulate it by inserting or removing validators (useful in model behaviors). For example,
$model->validators[] = $newValidator;
Return values
ArrayObject|array<string|int, Validator> —all the validators declared in the model.
hasErrors()
Returns a value indicating whether there is any validation error.
public
hasErrors([string|null $attribute = null ]) : bool
Parameters
- $attribute : string|null = null
-
attribute name. Use null to check all attributes.
Return values
bool —whether there is any error.
hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public
hasEventHandlers(string $name) : bool
Parameters
- $name : string
-
the event name
Return values
bool —whether there is any handler attached to the event.
hasMethod()
Returns a value indicating whether a method is defined.
public
hasMethod(string $name[, bool $checkBehaviors = true ]) : bool
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkBehaviors : bool = true
-
whether to treat behaviors' methods as methods of this component
Return values
bool —whether the method is defined
hasProperty()
Returns a value indicating whether a property is defined for this component.
public
hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property is defined if:
- the class has a getter or 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 property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property is defined
init()
Initializes the object.
public
init() : mixed
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
instance()
Returns static class instance, which can be used to obtain meta information.
public
static instance([bool $refresh = false ]) : static
Parameters
- $refresh : bool = false
-
whether to re-create static instance even, if it is already cached.
Return values
static —class instance.
isAttributeActive()
Returns a value indicating whether the attribute is active in the current scenario.
public
isAttributeActive(string $attribute) : bool
Parameters
- $attribute : string
-
attribute name
Tags
Return values
bool —whether the attribute is active in the current scenario
isAttributeRequired()
Returns a value indicating whether the attribute is required.
public
isAttributeRequired(string $attribute) : bool
This is determined by checking if the attribute is associated with a [[\yii\validators\RequiredValidator|required]] validation rule in the current [[scenario]].
Note that when the validator has a conditional validation applied using
[[\yii\validators\RequiredValidator::$when|$when]] this method will return
false
regardless of the when
condition because it may be called be
before the model is loaded with data.
Parameters
- $attribute : string
-
attribute name
Return values
bool —whether the attribute is required
isAttributeSafe()
Returns a value indicating whether the attribute is safe for massive assignments.
public
isAttributeSafe(string $attribute) : bool
Parameters
- $attribute : string
-
attribute name
Tags
Return values
bool —whether the attribute is safe for massive assignments
load()
Populates the model with input data.
public
load(array<string|int, mixed> $data[, string|null $formName = null ]) : bool
This method provides a convenient shortcut for:
if (isset($_POST['FormName'])) {
$model->attributes = $_POST['FormName'];
if ($model->save()) {
// handle success
}
}
which, with load()
can be written as:
if ($model->load($_POST) && $model->save()) {
// handle success
}
load()
gets the 'FormName'
from the model's [[formName()]] method (which you may override), unless the
$formName
parameter is given. If the form name is empty, load()
populates the model with the whole of $data
,
instead of $data['FormName']
.
Note, that the data being populated is subject to the safety check by [[setAttributes()]].
Parameters
- $data : array<string|int, mixed>
-
the data array to load, typically
$_POST
or$_GET
. - $formName : string|null = null
-
the form name to use to load the data into the model, empty string when form not use. If not set, [[formName()]] is used.
Return values
bool —whether load()
found the expected form in $data
.
loadMultiple()
Populates a set of models with the data from end user.
public
static loadMultiple(array<string|int, mixed> $models, array<string|int, mixed> $data[, string|null $formName = null ]) : bool
This method is mainly used to collect tabular data input.
The data to be loaded for each model is $data[formName][index]
, where formName
refers to the value of [[formName()]], and index
the index of the model in the $models
array.
If [[formName()]] is empty, $data[index]
will be used to populate each model.
The data being populated to each model is subject to the safety check by [[setAttributes()]].
Parameters
- $models : array<string|int, mixed>
-
the models to be populated. Note that all models should have the same class.
- $data : array<string|int, mixed>
-
the data array. This is usually
$_POST
or$_GET
, but can also be any valid array supplied by end user. - $formName : string|null = null
-
the form name to be used for loading the data into the models. If not set, it will use the [[formName()]] value of the first model in
$models
. This parameter is available since version 2.0.1.
Return values
bool —whether at least one of the models is successfully populated.
off()
Detaches an existing event handler from this component.
public
off(string $name[, callable|null $handler = null ]) : bool
This method is the opposite of [[on()]].
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
Parameters
- $name : string
-
event name
- $handler : callable|null = null
-
the event handler to be removed. If it is null, all handlers attached to the named event will be removed.
Tags
Return values
bool —if a handler is found and detached
offsetExists()
Returns whether there is an element at the specified offset.
public
offsetExists(string $offset) : bool
This method is required by the SPL interface [[\ArrayAccess]].
It is implicitly called when you use something like isset($model[$offset])
.
Parameters
- $offset : string
-
the offset to check on.
Attributes
Return values
bool —whether or not an offset exists.
offsetGet()
Returns the element at the specified offset.
public
offsetGet(string $offset) : mixed
This method is required by the SPL interface [[\ArrayAccess]].
It is implicitly called when you use something like $value = $model[$offset];
.
Parameters
- $offset : string
-
the offset to retrieve element.
Attributes
Return values
mixed —the element at the offset, null if no element is found at the offset
offsetSet()
Sets the element at the specified offset.
public
offsetSet(string $offset, mixed $value) : mixed
This method is required by the SPL interface [[\ArrayAccess]].
It is implicitly called when you use something like $model[$offset] = $value;
.
Parameters
- $offset : string
-
the offset to set element
- $value : mixed
-
the element value
Attributes
offsetUnset()
Sets the element value at the specified offset to null.
public
offsetUnset(string $offset) : mixed
This method is required by the SPL interface [[\ArrayAccess]].
It is implicitly called when you use something like unset($model[$offset])
.
Parameters
- $offset : string
-
the offset to unset element
Attributes
on()
Attaches an event handler to an event.
public
on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an [[Event]] object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
Parameters
- $name : string
-
the event name
- $handler : callable
-
the event handler
- $data : mixed = null
-
the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]].
- $append : bool = true
-
whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.
Tags
onUnsafeAttribute()
This method is invoked when an unsafe attribute is being massively assigned.
public
onUnsafeAttribute(string $name, mixed $value) : mixed
The default implementation will log a warning message if YII_DEBUG is on. It does nothing otherwise.
Parameters
- $name : string
-
the unsafe attribute name
- $value : mixed
-
the attribute value
rules()
Returns the validation rules for attributes.
public
rules() : array<string|int, mixed>
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 [[scenario|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 [[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 [[Validator::builtInValidators|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()
.
Return values
array<string|int, mixed> —validation rules
safeAttributes()
Returns the attribute names that are safe to be massively assigned in the current scenario.
public
safeAttributes() : array<string|int, string>
Return values
array<string|int, string> —safe attribute names
scenarios()
Returns a list of scenarios and the corresponding active attributes.
public
scenarios() : array<string|int, mixed>
An active attribute is one that is subject to validation in the current scenario. The returned array should be in the following format:
[
'scenario1' => ['attribute11', 'attribute12', ...],
'scenario2' => ['attribute21', 'attribute22', ...],
...
]
By default, an active attribute is considered safe and can be massively assigned.
If an attribute should NOT be massively assigned (thus considered unsafe),
please prefix the attribute with an exclamation character (e.g. '!rank'
).
The default implementation of this method will return all scenarios found in the [[rules()]] declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes found in the [[rules()]]. Each scenario will be associated with the attributes that are being validated by the validation rules that apply to the scenario.
Return values
array<string|int, mixed> —a list of scenarios and the corresponding active attributes.
setAttributes()
Sets the attribute values in a massive way.
public
setAttributes(array<string|int, mixed> $values[, bool $safeOnly = true ]) : mixed
Parameters
- $values : array<string|int, mixed>
-
attribute values (name => value) to be assigned to the model.
- $safeOnly : bool = true
-
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]].
Tags
setScenario()
Sets the scenario for the model.
public
setScenario(string $value) : mixed
Note that this method does not check if the scenario exists or not. The method [[validate()]] will perform this check.
Parameters
- $value : string
-
the scenario that this model is in.
toArray()
Converts the model into an array.
public
toArray([array<string|int, mixed> $fields = [] ][, array<string|int, mixed> $expand = [] ][, bool $recursive = true ]) : array<string|int, mixed>
This method will first identify which fields to be included in the resulting array by calling [[resolveFields()]].
It will then turn the model into an array with these fields. If $recursive
is true,
any embedded objects will also be converted into arrays.
When embedded objects are [[Arrayable]], their respective nested fields will be extracted and passed to [[toArray()]].
If the model implements the [[Linkable]] interface, the resulting array will also have a _link
element
which refers to a list of links as specified by the interface.
Parameters
- $fields : array<string|int, mixed> = []
-
the fields being requested. If empty or if it contains '*', all fields as specified by [[fields()]] will be returned. Fields can be nested, separated with dots (.). e.g.: item.field.sub-field
$recursive
must be true for nested fields to be extracted. If$recursive
is false, only the root fields will be extracted. - $expand : array<string|int, mixed> = []
-
the additional fields being requested for exporting. Only fields declared in [[extraFields()]] will be considered. Expand can also be nested, separated with dots (.). e.g.: item.expand1.expand2
$recursive
must be true for nested expands to be extracted. If$recursive
is false, only the root expands will be extracted. - $recursive : bool = true
-
whether to recursively return array representation of embedded objects.
Return values
array<string|int, mixed> —the array representation of the object
trigger()
Triggers an event.
public
trigger(string $name[, Event|null $event = null ]) : mixed
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
Parameters
- $name : string
-
the event name
- $event : Event|null = null
-
the event instance. If not set, a default [[Event]] object will be created.
validate()
Performs the data validation.
public
validate([array<string|int, string>|string|null $attributeNames = null ][, bool $clearErrors = true ]) : bool
This method executes the validation rules applicable to the current [[scenario]]. The following criteria are used to determine whether a rule is currently applicable:
- the rule must be associated with the attributes relevant to the current scenario;
- the rules must be effective for the current scenario.
This method will call [[beforeValidate()]] and [[afterValidate()]] before and after the actual validation, respectively. If [[beforeValidate()]] returns false, the validation will be cancelled and [[afterValidate()]] will not be called.
Errors found during the validation can be retrieved via [[getErrors()]], [[getFirstErrors()]] and [[getFirstError()]].
Parameters
- $attributeNames : array<string|int, string>|string|null = null
-
attribute name or list of attribute names that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated.
- $clearErrors : bool = true
-
whether to call [[clearErrors()]] before performing validation
Tags
Return values
bool —whether the validation is successful without any error.
validateMultiple()
Validates multiple models.
public
static validateMultiple(array<string|int, mixed> $models[, array<string|int, mixed>|null $attributeNames = null ]) : bool
This method will validate every model. The models being validated may be of the same or different types.
Parameters
- $models : array<string|int, mixed>
-
the models to be validated
- $attributeNames : array<string|int, mixed>|null = null
-
list of attribute names that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated.
Return values
bool —whether all models are valid. False will be returned if one or multiple models have validation error.
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".
protected
extractFieldsFor(array<string|int, mixed> $fields, string $rootField) : array<string|int, mixed>
Parameters
- $fields : array<string|int, mixed>
-
The fields requested for extraction
- $rootField : string
-
The root field for which we want to extract the nested fields
Tags
Return values
array<string|int, mixed> —nested fields extracted for the given field
extractRootFields()
Extracts the root field names from nested fields.
protected
extractRootFields(array<string|int, mixed> $fields) : array<string|int, mixed>
Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "item".
Parameters
- $fields : array<string|int, mixed>
-
The fields requested for extraction
Tags
Return values
array<string|int, mixed> —root fields extracted from the given nested fields
normalizeDate()
protected
normalizeDate(string $dateFieldName) : mixed
Parameters
- $dateFieldName : string
resolveFields()
Determines which fields can be returned by [[toArray()]].
protected
resolveFields(array<string|int, mixed> $fields, array<string|int, mixed> $expand) : array<string|int, mixed>
This method will first extract the root fields from the given fields. Then it will check the requested root fields against those declared in [[fields()]] and [[extraFields()]] to determine which fields can be returned.
Parameters
- $fields : array<string|int, mixed>
-
the fields being requested for exporting
- $expand : array<string|int, mixed>
-
the additional fields being requested for exporting
Return values
array<string|int, mixed> —the list of fields to be exported. The array keys are the field names, and the array values are the corresponding object property names or PHP callables returning the field values.
attachBehaviorInternal()
Attaches a behavior to this component.
private
attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
- $name : string|int
-
the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior to be attached
Return values
Behavior —the attached behavior.