没有命名空间的类 yii yii\base yii\behaviors yii\caching yii\captcha yii\console yii\console\controllers yii\console\widgets yii\data yii\db yii\db\conditions yii\db\cubrid yii\db\cubrid\conditions yii\db\mssql yii\db\mssql\conditions yii\db\mysql yii\db\oci yii\db\oci\conditions yii\db\pgsql yii\db\sqlite yii\db\sqlite\conditions yii\di yii\filters yii\filters\auth yii\grid yii\helpers yii\i18n yii\log yii\mail yii\mutex yii\rbac yii\rest yii\test yii\validators yii\web yii\widgets

Class yii\data\DataFilter

继承yii\data\DataFilter » yii\base\Model » yii\base\Component » yii\base\BaseObject
实现ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface
使用 Traitsyii\base\ArrayableTrait, yii\base\StaticInstanceTrait
子类yii\data\ActiveDataFilter
可用版本自2.0.13
源码 https://github.com/yiichina/yii2/blob/api/framework/data/DataFilter.php

DataFilter 是用于处理查询过滤规范的特殊 yii\base\Model。 它可以通过请求验证并建立一个过滤条件。

过滤器示例:

{
    "or": [
        {
            "and": [
                {
                    "name": "some name",
                },
                {
                    "price": "25",
                }
            ]
        },
        {
            "id": {"in": [2, 5, 9]},
            "price": {
                "gt": 10,
                "lt": 50
            }
        }
    ]
}

在实际请求中,过滤器要指定一个和 $filterAttributeName 一致的键名。如,实际的 HTTP 请求 body 如下:

{
    "filter": {"or": {...}},
    "page": 2,
    ...
}

原始过滤器值应该被分配到模型的属性 $filter。 可以通过 load() 方法来填充 DataFilter:

use yii\data\DataFilter;

$dataFilter = new DataFilter();
$dataFilter->load(Yii::$app->request->getBodyParams());

要使用 DataFilter,我们需要通过 $searchModel 来指定搜索 model。这个搜索模型应该声明 所有可用的搜索属性和这些属性的验证规则。例如:

class SearchModel extends \yii\base\Model
{
    public $id;
    public $name;

    public function rules()
    {
        return [
            [['id', 'name'], 'trim'],
            ['id', 'integer'],
            ['name', 'string'],
        ];
    }
}

为了减少类数量,我们可以使用 yii\base\DynamicModel 实例作为 $searchModel。 在这里,我们可以使用 PHP callable 作为 $searchModel

function () {
    return (new \yii\base\DynamicModel(['id' => null, 'name' => null]))
        ->addRule(['id', 'name'], 'trim')
        ->addRule('id', 'integer')
        ->addRule('name', 'string');
}

我们可以使用 validate() 方法来校验过滤值是否可用。如果校验失败,我们可以使用 getErrors() 方法来获取真实的错误信息。

我们可以使用 build() 方法来获取合适的获取数据的过滤条件。

Note: 该类是个基类。该类的 build() 方法的简单实现返回了标准的 $filter 值。 我们应该使用恰当的实现了 buildInternal() 方法的子类来将过滤器转化为特定的 格式。

参见 yii\data\ActiveDataFilter.

公共属性

隐藏继承的属性

属性类型描述被定义在
$activeValidators yii\validators\Validator[] The validators applicable to the current $scenario. yii\base\Model
$attributeMap array 在搜索条件中实际使用的属性名称,格式如:[filterAttribute => actualAttribute]。 例如,在使用表连接搜索查询的案例中,属性映射可以像下面这样: `php [ 'authorName' => '{{author}}. yii\data\DataFilter
$attributes array Attribute values (name => value). yii\base\Model
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$conditionValidators array 过滤器条件关键字和校验方法的映射。 这些方法被 validateCondition() 方法使用以校验原始过滤条件。 yii\data\DataFilter
$errorMessages array 错误信息,格式如:[errorKey => message] yii\data\DataFilter
$errors array Errors for all attributes or the specified attribute. yii\base\Model
$filter mixed 原始过滤器值 yii\data\DataFilter
$filterAttributeLabel string 通过 $filterAttributeName 指定的过滤器属性标签。 将在错误消息合成中使用。 yii\data\DataFilter
$filterAttributeName string 处理过滤器值的属性名称。 这个名字用于通过 load() 方法加载数据。 yii\data\DataFilter
$filterControls array 在过滤器中可能用到的关键字和表达式。 数组键是从用户请求中获取的在原始过滤器值中使用的表达式。 数组值是在该类方法中使用的内部构建的关键字。 任何未指定的关键字将不被识别为过滤器控件,同时都将被视为 属性名。因此我们应该避免过滤器控件关键字和属性名称之间的冲突。 如:我们指定了过滤器控件关键字 'like',同时也有一个属性叫做 'like',类似于这种属性指定条件是 不会生效的。 我们可以为同一个过滤器构建关键字指定一些关键字,创建多个别名。例如: `php [ 'eq' => '=', '=' => '=', '==' => '=', '===' => '=', // . yii\data\DataFilter
$firstErrors array The first errors. yii\base\Model
$iterator ArrayIterator An iterator for traversing the items in the list. yii\base\Model
$multiValueOperators array 可接受多个值的操作符关键字列表。 yii\data\DataFilter
$operatorTypes array 指定每个操作符支持的搜索属性类型的列表。 这个字段应该使用这种格式:'operatorKeyword' => ['type1', 'type2' . yii\data\DataFilter
$scenario string The scenario that this model is in. yii\base\Model
$searchAttributeTypes array 搜索属性类型映射。 yii\data\DataFilter
$searchModel yii\base\Model 模型实例。 yii\data\DataFilter
$validators ArrayObject|yii\validators\Validator[] All the validators declared in the model. yii\base\Model

公共方法

隐藏继承的方法

方法描述被定义在
__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() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\data\DataFilter
__isset() Checks if a property is set, i.e. defined and not null. yii\data\DataFilter
__set() Sets the value of a component property. yii\data\DataFilter
__unset() Sets a component property to be null. yii\data\DataFilter
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
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() Returns the attribute labels. yii\data\DataFilter
attributes() Returns the list of attribute names. yii\data\DataFilter
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
build() $filter 值构建实际的过滤器规范。 yii\data\DataFilter
canGetProperty() Returns a value indicating whether a property can be read. yii\data\DataFilter
canSetProperty() Returns a value indicating whether a property can be set. yii\data\DataFilter
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
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\data\DataFilter
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
getErrorMessages() yii\data\DataFilter
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
getFilter() yii\data\DataFilter
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
getSearchAttributeTypes() yii\data\DataFilter
getSearchModel() yii\data\DataFilter
getValidators() Returns all the validators declared in rules(). yii\base\Model
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() 返回静态类实例,该实例可用于获取 meta 信息 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
normalize() 格式化过滤器质,根据 $filterControls$attributeMap 方法替换原始关键字。 yii\data\DataFilter
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\data\DataFilter
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
setAttributes() Sets the attribute values in a massive way. yii\base\Model
setErrorMessages() 设置验证结构过滤的错误信息响应列表,格式如:[errorKey => message]。 消息包含根据消息上下文填充的占位符。 对于每条消息,{filter} 占位符是可用的,参见 $filterAttributeName 属性标签 yii\data\DataFilter
setFilter() yii\data\DataFilter
setScenario() Sets the scenario for the model. yii\base\Model
setSearchAttributeTypes() yii\data\DataFilter
setSearchModel() yii\data\DataFilter
toArray() Converts the model into an array. yii\base\ArrayableTrait
trigger() Triggers an event. yii\base\Component
validate() Performs the data validation. yii\base\Model
validateFilter() 验证过滤器属性值以匹配过滤器条件规范。 yii\data\DataFilter
validateMultiple() Validates multiple models. yii\base\Model

受保护的方法

隐藏继承的方法

方法描述被定义在
buildInternal() 执行实际的过滤器构建。 默认情况下,此方法返回 normalize() 方法的返回值。 子类可以重写此方法,提供更具体的实现。 yii\data\DataFilter
defaultErrorMessages() $errorMessages 返回的默认值。 yii\data\DataFilter
detectSearchAttributeType() 按照传入的 validator 检测属性类型 yii\data\DataFilter
detectSearchAttributeTypes() $searchModel 验证规则中为 $searchAttributeTypes 合成默认值。 yii\data\DataFilter
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
filterAttributeValue() $searchModel 中验证属性值,如果有属性过滤器的话,可以使用属性过滤器。 yii\data\DataFilter
parseErrorMessage() $errorMessages 中解析消息内容,特别是消息关键字。 yii\data\DataFilter
resolveFields() Determines which fields can be returned by toArray(). yii\base\ArrayableTrait
validateAttributeCondition() 验证特定属性的搜索条件。 yii\data\DataFilter
validateAttributeValue() \yii\data\model 中验证属性值。 yii\data\DataFilter
validateBlockCondition() 验证包含单个条件的块条件。 包括 not 这样的操作符。 yii\data\DataFilter
validateCondition() 验证过滤器条件。 yii\data\DataFilter
validateConjunctionCondition() 验证包含多个独立条件的连接条件。 包括 andor 这样的操作符。 yii\data\DataFilter
validateOperatorCondition() 验证操作符条件。 yii\data\DataFilter

Events

隐藏继承的事件

事件类型描述被定义在
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

常量

隐藏继承的常量

常量描述被定义在
SCENARIO_DEFAULT 'default' The name of the default scenario. yii\base\Model
TYPE_ARRAY 'array' yii\data\DataFilter
TYPE_BOOLEAN 'boolean' yii\data\DataFilter
TYPE_DATE 'date' yii\data\DataFilter
TYPE_DATETIME 'datetime' yii\data\DataFilter
TYPE_FLOAT 'float' yii\data\DataFilter
TYPE_INTEGER 'integer' yii\data\DataFilter
TYPE_STRING 'string' yii\data\DataFilter
TYPE_TIME 'time' yii\data\DataFilter

属性详情

$attributeMap 公共 属性

在搜索条件中实际使用的属性名称,格式如:[filterAttribute => actualAttribute]。 例如,在使用表连接搜索查询的案例中,属性映射可以像下面这样:

[
    'authorName' => '{{author}}.[[name]]'
]

属性映射将在 normalize() 方法中被提交到过滤器条件。

public array $attributeMap = []
$conditionValidators 公共 属性

过滤器条件关键字和校验方法的映射。 这些方法被 validateCondition() 方法使用以校验原始过滤条件。

public array $conditionValidators = ['AND' => 'validateConjunctionCondition''OR' => 'validateConjunctionCondition''NOT' => 'validateBlockCondition''<' => 'validateOperatorCondition''>' => 'validateOperatorCondition''<=' => 'validateOperatorCondition''>=' => 'validateOperatorCondition''=' => 'validateOperatorCondition''!=' => 'validateOperatorCondition''IN' => 'validateOperatorCondition''NOT IN' => 'validateOperatorCondition''LIKE' => 'validateOperatorCondition']
$errorMessages 公共 属性

错误信息,格式如:[errorKey => message]

public array getErrorMessages ( )
public void setErrorMessages ( $errorMessages )
$filter 公共 属性

原始过滤器值

public mixed getFilter ( )
public void setFilter ( $filter )
$filterAttributeLabel 公共 属性

通过 $filterAttributeName 指定的过滤器属性标签。 将在错误消息合成中使用。

$filterAttributeName 公共 属性

处理过滤器值的属性名称。 这个名字用于通过 load() 方法加载数据。

public string $filterAttributeName 'filter'
$filterControls 公共 属性

在过滤器中可能用到的关键字和表达式。 数组键是从用户请求中获取的在原始过滤器值中使用的表达式。 数组值是在该类方法中使用的内部构建的关键字。

任何未指定的关键字将不被识别为过滤器控件,同时都将被视为 属性名。因此我们应该避免过滤器控件关键字和属性名称之间的冲突。 如:我们指定了过滤器控件关键字 'like',同时也有一个属性叫做 'like',类似于这种属性指定条件是 不会生效的。

我们可以为同一个过滤器构建关键字指定一些关键字,创建多个别名。例如:

[
    'eq' => '=',
    '=' => '=',
    '==' => '=',
    '===' => '=',
    // ...
]

Note: 在指定过滤器控件时,请记住 API 使用的实际数据交换格式。 确保每一个指定的控件关键字的格式是合法的。如,在 XML 标签名字中只能 以字母字符开头,因此,像 >,'=' 或者 $gt 控件将破坏 XML 模式规范。

public array $filterControls = ['and' => 'AND''or' => 'OR''not' => 'NOT''lt' => '<''gt' => '>''lte' => '<=''gte' => '>=''eq' => '=''neq' => '!=''in' => 'IN''nin' => 'NOT IN''like' => 'LIKE']
$multiValueOperators 公共 属性

可接受多个值的操作符关键字列表。

public array $multiValueOperators = ['IN''NOT IN']
$operatorTypes 公共 属性

指定每个操作符支持的搜索属性类型的列表。 这个字段应该使用这种格式:'operatorKeyword' => ['type1', 'type2' ...]。 支持的类型列表被指定为 * 时,表示操作支持所有类型。 任何未指定的关键字都不会被认为是验证操作符。

public array $operatorTypes = ['<' => [self::TYPE_INTEGERself::TYPE_FLOATself::TYPE_DATETIMEself::TYPE_DATEself::TYPE_TIME], '>' => [self::TYPE_INTEGERself::TYPE_FLOATself::TYPE_DATETIMEself::TYPE_DATEself::TYPE_TIME], '<=' => [self::TYPE_INTEGERself::TYPE_FLOATself::TYPE_DATETIMEself::TYPE_DATEself::TYPE_TIME], '>=' => [self::TYPE_INTEGERself::TYPE_FLOATself::TYPE_DATETIMEself::TYPE_DATEself::TYPE_TIME], '=' => '*''!=' => '*''IN' => '*''NOT IN' => '*''LIKE' => [self::TYPE_STRING]]
$searchAttributeTypes 公共 属性

搜索属性类型映射。

public array getSearchAttributeTypes ( )
public void setSearchAttributeTypes ( $searchAttributeTypes )
$searchModel 公共 属性

模型实例。

public yii\base\Model getSearchModel ( )
public void setSearchModel ( $model )

方法详情

__get() 公共 方法

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.

__isset() 公共 方法

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

__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.

__unset() 公共 方法

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.

attributeLabels() 公共 方法

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().

public array attributeLabels()
return array

Attribute labels (name => label)

attributes() 公共 方法

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.

build() 公共 方法

$filter 值构建实际的过滤器规范。

public mixed|false build($runValidation true)
$runValidation boolean

是否执行验证(validate() 执行的时候) 在构建过滤器之前,默认值是 true。如果验证失败,没有过滤器 被构建,并且这个方法将返回 false

return mixed|false

以构建的实际过滤器值,验证失败返回 false

buildInternal() 受保护 方法

执行实际的过滤器构建。 默认情况下,此方法返回 normalize() 方法的返回值。 子类可以重写此方法,提供更具体的实现。

protected mixed buildInternal()
return mixed

被构建的实际的过滤器值。

canGetProperty() 公共 方法

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

canSetProperty() 公共 方法

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

defaultErrorMessages() 受保护 方法

$errorMessages 返回的默认值。

protected array defaultErrorMessages()
return array

[errorKey => message] 格式的默认错误信息。

detectSearchAttributeType() 受保护 方法 (自版本 2.0.14 可用)

按照传入的 validator 检测属性类型

protected string|null detectSearchAttributeType(yii\validators\Validator $validator)
$validator
return string|null

检测出来的属性类型

detectSearchAttributeTypes() 受保护 方法

$searchModel 验证规则中为 $searchAttributeTypes 合成默认值。

protected array detectSearchAttributeTypes()
return array

属性类型映射。

filterAttributeValue() 受保护 方法

$searchModel 中验证属性值,如果有属性过滤器的话,可以使用属性过滤器。

protected mixed filterAttributeValue($attribute, $value)
$attribute string

属性名字。

$value mixed

属性值。

return mixed

过滤的属性值。

formName() 公共 方法

Returns the form name that this model class should use.

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.

public string formName()
return string

The form name of this model class.

throws yii\base\InvalidConfigException

when form is defined with anonymous class and formName() method is not overridden.

getErrorMessages() 公共 方法

public array getErrorMessages()
return array

错误信息,格式如:[errorKey => message]

getFilter() 公共 方法

public mixed getFilter()
return mixed

原始过滤器值

getSearchAttributeTypes() 公共 方法

public array getSearchAttributeTypes()
return array

搜索属性类型映射。

getSearchModel() 公共 方法

public yii\base\Model getSearchModel()
return yii\base\Model

模型实例。

throws yii\base\InvalidConfigException

在配置校验中。

normalize() 公共 方法

格式化过滤器质,根据 $filterControls$attributeMap 方法替换原始关键字。

public array|boolean normalize($runValidation true)
$runValidation boolean

是否执行验证(validate() 执行的时候) 在格式化过滤器之前。默认值是 true。如果验证失败,没有过滤器 被执行并且这个方法会返回 false

return array|boolean

格式化过滤器值,验证失败将返回 false

parseErrorMessage() 受保护 方法

$errorMessages 中解析消息内容,特别是消息关键字。

protected string parseErrorMessage($messageKey, $params = [])
$messageKey string

消息关键字。

$params array

解析成消息的参数。

return string

合成的消息字符串。

rules() 公共 方法

Returns the validation rules for attributes.

Validation rules are used by validate() to check if attribute values are valid. Child classes may override this method to declare different validation rules.

Each rule is an array with the following structure:

[
    ['attribute1', 'attribute2'],
    'validator type',
    'on' => ['scenario1', 'scenario2'],
    //...other parameters...
]

where

  • attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
  • validator type: required, specifies the validator to be used. It can be a built-in validator name, a method name of the model class, an anonymous function, or a validator class name.
  • on: optional, specifies the scenarios array in which the validation rule can be applied. If this option is not set, the rule will apply to all scenarios.
  • additional name-value pairs can be specified to initialize the corresponding validator properties. Please refer to individual validator class API for possible properties.

A validator can be either an object of a class extending yii\validators\Validator, or a model class method (called inline validator) that has the following signature:

// $params refers to validation parameters given in the rule
function validatorName($attribute, $params)

In the above $attribute refers to the attribute currently being validated while $params contains an array of validator configuration options such as max in case of string validator. The value of the attribute currently being validated can be accessed as $this->$attribute. Note the $ before attribute; this is taking the value of the variable $attribute and using it as the name of the property to access.

Yii also provides a set of built-in validators. Each one has an alias name which can be used when specifying a validation rule.

Below are some examples:

[
    // built-in "required" validator
    [['username', 'password'], 'required'],
    // built-in "string" validator customized with "min" and "max" properties
    ['username', 'string', 'min' => 3, 'max' => 12],
    // built-in "compare" validator that is used in "register" scenario only
    ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
    // an inline validator defined via the "authenticate()" method in the model class
    ['password', 'authenticate', 'on' => 'login'],
    // a validator of class "DateRangeValidator"
    ['dateRange', 'DateRangeValidator'],
];

Note, in order to inherit rules defined in the parent class, a child class needs to merge the parent rules with child rules using functions such as array_merge().

public array rules()
return array

Validation rules

setErrorMessages() 公共 方法

设置验证结构过滤的错误信息响应列表,格式如:[errorKey => message]。 消息包含根据消息上下文填充的占位符。 对于每条消息,{filter} 占位符是可用的,参见 $filterAttributeName 属性标签

public void setErrorMessages($errorMessages)
$errorMessages array|Closure

[errorKey => message] 格式的错误新,或者一个返回相同格式的 PHP callback。

setFilter() 公共 方法

public void setFilter($filter)
$filter mixed

原始过滤器值。

setSearchAttributeTypes() 公共 方法

public void setSearchAttributeTypes($searchAttributeTypes)
$searchAttributeTypes array|null

搜索属性类型映射。

setSearchModel() 公共 方法

public void setSearchModel($model)
$model yii\base\Model|array|string|callable

模型实例或它的 di 兼容配置。

throws yii\base\InvalidConfigException

在验证配置的时候。

validateAttributeCondition() 受保护 方法

验证特定属性的搜索条件。

protected void validateAttributeCondition($attribute, $condition)
$attribute string

搜索属性名称。

$condition mixed

搜索条件。

validateAttributeValue() 受保护 方法

\yii\data\model 中验证属性值。

protected void validateAttributeValue($attribute, $value)
$attribute string

属性名字。

$value mixed

属性值。

validateBlockCondition() 受保护 方法

验证包含单个条件的块条件。 包括 not 这样的操作符。

protected void validateBlockCondition($operator, $condition)
$operator string

原始操作符控制关键字。

$condition mixed

原始条件。

validateCondition() 受保护 方法

验证过滤器条件。

protected void validateCondition($condition)
$condition mixed

原始过滤器条件。

validateConjunctionCondition() 受保护 方法

验证包含多个独立条件的连接条件。 包括 andor 这样的操作符。

protected void validateConjunctionCondition($operator, $condition)
$operator string

原始操作符控制关键字。

$condition mixed

原始条件。

validateFilter() 公共 方法

验证过滤器属性值以匹配过滤器条件规范。

public void validateFilter()
validateOperatorCondition() 受保护 方法

验证操作符条件。

protected void validateOperatorCondition($operator, $condition, $attribute null)
$operator string

原始操作符控制关键字。

$condition mixed

属性条件。

$attribute string

属性名字。