All Projects → yii2tech → ar-search

yii2tech / ar-search

Licence: other
Provides unified search model for Yii ActiveRecord

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to ar-search

Ar Softdelete
Soft delete behavior for ActiveRecord
Stars: ✭ 188 (+506.45%)
Mutual labels:  activerecord, yii2, yii, yii2-extension
ar-dynattribute
Provide ActiveRecord dynamic attributes stored into the single field in serialized state
Stars: ✭ 43 (+38.71%)
Mutual labels:  activerecord, yii2, yii, yii2-extension
Ar Linkmany
ActiveRecord behavior for saving many-to-many relations
Stars: ✭ 83 (+167.74%)
Mutual labels:  activerecord, yii2, yii, yii2-extension
Ar Position
ActiveRecord behavior, which provides ability for custom records order setup
Stars: ✭ 107 (+245.16%)
Mutual labels:  activerecord, yii2, yii, yii2-extension
filedb
ActiveRecord for static data definitions based on files
Stars: ✭ 72 (+132.26%)
Mutual labels:  activerecord, yii2, yii, yii2-extension
ar-role
ActiveRecord behavior, which provides relation roles (table inheritance)
Stars: ✭ 34 (+9.68%)
Mutual labels:  activerecord, yii2, yii, yii2-extension
ar-variation
Variation behavior for ActiveRecord
Stars: ✭ 46 (+48.39%)
Mutual labels:  activerecord, yii2, yii, yii2-extension
Yii2 Schemadump
Generate the schema from an existing database.
Stars: ✭ 78 (+151.61%)
Mutual labels:  yii2, yii, yii2-extension
Csv Grid
Yii2 extension for CSV export
Stars: ✭ 83 (+167.74%)
Mutual labels:  yii2, yii, yii2-extension
Admin
Admin pack (actions, widgets, etc) for Yii2
Stars: ✭ 100 (+222.58%)
Mutual labels:  yii2, yii, yii2-extension
Config
Yii2 application runtime configuration support
Stars: ✭ 54 (+74.19%)
Mutual labels:  yii2, yii, yii2-extension
Yii2 Aws S3
An Amazon S3 component for Yii2
Stars: ✭ 86 (+177.42%)
Mutual labels:  yii2, yii, yii2-extension
install
basic script for project installation
Stars: ✭ 17 (-45.16%)
Mutual labels:  yii2, yii, yii2-extension
Sitemap
Site map creation support
Stars: ✭ 59 (+90.32%)
Mutual labels:  yii2, yii, yii2-extension
Balance
Balance accounting (bookkeeping) system based on debit and credit principle
Stars: ✭ 162 (+422.58%)
Mutual labels:  yii2, yii, yii2-extension
Yii2 Assets Auto Compress
Automatic compilation of js + css + html
Stars: ✭ 147 (+374.19%)
Mutual labels:  yii2, yii, yii2-extension
content
Content management system for Yii2
Stars: ✭ 54 (+74.19%)
Mutual labels:  yii2, yii, yii2-extension
yii2-presenter
Yii2 View Presenter
Stars: ✭ 13 (-58.06%)
Mutual labels:  yii2, yii, yii2-extension
yii2-facades
Facades for Yii 2
Stars: ✭ 21 (-32.26%)
Mutual labels:  yii2, yii, yii2-extension
File Storage
File storage abstraction for Yii2
Stars: ✭ 116 (+274.19%)
Mutual labels:  yii2, yii, yii2-extension

ActiveRecord Search Model Extension for Yii2


This extension provides unified search model for Yii ActiveRecord.

For license information check the LICENSE-file.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yii2tech/ar-search

or add

"yii2tech/ar-search": "*"

to the require section of your composer.json.

Usage

This extension provides unified search model for Yii ActiveRecord via special model class - \yii2tech\ar\search\ActiveSearchModel.

This model is able to fetch its attributes, validation rules and filtering logic from the 'slave' source ActiveRecord model specified via \yii2tech\ar\search\ActiveSearchModel::$model. Thus you do not need to declare a separated model class for searching and define a filter logic. For example:

<?php

use yii2tech\ar\search\ActiveSearchModel;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item'
]);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

ActiveSearchModel picks all 'safe' attributes of the 'slave' model and use them as own attributes. Thus you can use any attribute, which is marked as 'safe' in related ActiveRecord model in the scope of this class. For example:

<?php

namespace app\models;

// ActiveRecord to be searched:
class Item extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            [['name', 'status', 'price'], 'required'],
            ['name', 'string'],
            ['status', 'integer'],
            ['price', 'number'],
        ];
    }
}

use yii2tech\ar\search\ActiveSearchModel;

// Create search model for declared ActiveRecord:
$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item'
]);

// safe attributes of `Item` are inherited:
$searchModel->name = 'Paul';
$searchModel->price = 10.5;

Inherited attributes may be used while composing web forms, which should collect filter data. For example:

<?php
use yii2tech\ar\search\ActiveSearchModel;
use yii\widgets\ActiveForm;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item'
]);
?>
<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'name')->textInput() ?>
<?= $form->field($model, 'price')->textInput() ?>
...

<?php ActiveForm::end(); ?>

Attribute labels and hints are also inherited from the 'slave' model.

The main method of \yii2tech\ar\search\ActiveSearchModel is search(). It loads filter attributes from given data array, validates them an creates a \yii\data\ActiveDataProvider instance applying own attributes as a query filter condition.

ActiveSearchModel uses a sophisticated logic for the query filtering, based on the attribute types, specified by \yii2tech\ar\search\ActiveSearchModel::$searchAttributeTypes, which value is extracted from \yii2tech\ar\search\ActiveSearchModel::$model by default and filter operators list, specified via \yii2tech\ar\search\ActiveSearchModel::$filterOperators. By default \yii\db\QueryInterface::andFilterWhere() will be used for the filter composition. For the 'string' attributes it will be used with 'like' operator. For 'integer' and 'float' ('double') method andFilterCompare() will be used, if it is available.

Heads up! Do not abuse ActiveSearchModel usage. It has been designed to cover only the simplest cases, when search logic is trivial. You should always create a separated search model in case, it requires complex logic of composition of the search query.

Adjusting Data Provider

You may want to change some settings of the data provider, created by the search() method: change pagination or sort settings and so on. You can do this via \yii2tech\ar\search\ActiveSearchModel::$dataProvider. For example:

<?php

use yii2tech\ar\search\ActiveSearchModel;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item',
    'dataProvider' => [
        'class' => 'yii\data\ActiveDataProvider',
        'pagination' => [
            'defaultPageSize' => 40
        ],
    ],
]);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
echo $dataProvider->pagination->defaultPageSize; // outputs `40`

Adjusting Search Query

You may use \yii2tech\ar\search\ActiveSearchModel::EVENT_AFTER_CREATE_QUERY event to adjust the search query instance adding relation eager loading or permanent conditions. For example:

<?php

use yii2tech\ar\search\ActiveSearchModel;
use yii2tech\ar\search\ActiveSearchEvent;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item',
]);
$searchModel->on(ActiveSearchModel::EVENT_AFTER_CREATE_QUERY, function(ActiveSearchEvent $event) {
    $event->query
        ->with(['category'])
        ->andWhere(['status' => 1]);
});

You may also specify query object directly via \yii2tech\ar\search\ActiveSearchModel::$dataProvider. For example:

<?php

use yii2tech\ar\search\ActiveSearchModel;
use yii\data\ActiveDataProvider;
use app\models\Item;

$searchModel = new ActiveSearchModel([
    'model' => Item::className(),
    'dataProvider' => function () {
        $query = Item::find()
            ->with(['category'])
            ->andWhere(['status' => 1]);

        return ActiveDataProvider(['query' => $query]);
    },
]);

Filter Operators

You can control the operators to be used for the query filtering via \yii2tech\ar\search\ActiveSearchModel::$filterOperators. It defines a mapping between the attribute type and the operator to be used with \yii\db\QueryInterface::andFilterWhere(). Each value can be a scalar operator name or a PHP callback, accepting query instance, attribute name and value. For example:

<?php

use yii2tech\ar\search\ActiveSearchModel;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item',
    'filterOperators' => [
        ActiveSearchModel::TYPE_STRING => '=', // use strict comparison for the string attributes
        ActiveSearchModel::TYPE_INTEGER => function (\yii\db\ActiveQueryInterface $query, $attribute, $value) {
            if ($attribute === 'commentsCount') {
                $query->andHaving(['commentsCount' => $value]);
            } else {
                $query->andFilterWhere([$attribute => $value]);
            }
        },
    ],
]);

ActiveSearchModel allows filtering for the attributes using andFilterCompare() method of the query (for example: \yii\db\Query::andFilterCompare()), which allows specifying filter value in format: {operator}{value} (for example: >10, <=100 and so on). The list of attribute names, for which usage of such comparison is allowed is controlled by \yii2tech\ar\search\ActiveSearchModel::$compareAllowedAttributes. For example:

<?php

use yii2tech\ar\search\ActiveSearchModel;

$searchModel = new ActiveSearchModel([
    'model' => 'app\models\Item',
    'compareAllowedAttributes' => [
        'price' // allow compare for 'price' only, excluding such fields like 'categoryId', 'status' and so on.
    ],
]);

You can set compareAllowedAttributes to *, which indicates any float or integer attribute will be allowed for comparison.

Note: \yii2tech\ar\search\ActiveSearchModel::$filterOperators take precedence over \yii2tech\ar\search\ActiveSearchModel::$compareAllowedAttributes.

Working Without 'Slave' Model

Although in most cases setup of \yii2tech\ar\search\ActiveSearchModel::$model is a quickest way to configure ActiveSearchModel instance, it is not mandatory. You can avoid setup of the 'slave' model and configure all search related properties directly. For example:

<?php

use yii2tech\ar\search\ActiveSearchModel;
use yii\data\ActiveDataProvider;
use app\models\Item;

$searchModel = new ActiveSearchModel([
    'searchAttributeTypes' => [
        'id' => ActiveSearchModel::TYPE_INTEGER,
        'name' => ActiveSearchModel::TYPE_STRING,
        'price' => ActiveSearchModel::TYPE_FLOAT,
    ],
    'rules' => [
        ['id', 'integer'],
        ['name', 'string'],
        ['price', 'number'],
    ],
    'compareAllowedAttributes' => [],
    'dataProvider' => function () {
        $query = Item::find()
            ->with(['category'])
            ->andWhere(['status' => 1]);

        return ActiveDataProvider(['query' => $query]);
    },
]);
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].