Переопределяем базовый метод `BaseActiveRecord` чтобы в момент построения GridView
все получаемые модели были не объектами текущего класса, а конктретного класса наследника

@inheritdoc
964340
public static function instantiate($row)
    {
        $entityId = (int)$row['entity_id'];
        $className = Entity::getEntityClassForId($entityId);
        return Yii::createObject($className);
    }
997218
public function getParentRecord()
    {
        //brak parenta
        if (!$this->parentId) {
            return;
        }
        //próba pobrania rodzica z cache
        if (null === $parent = \App\Registry::$cache->load($cacheKey = 'category-' . $this->parentId)) {
            //pobieranie rodzica
            \App\Registry::$cache->save($parent = (new \Cms\Orm\CmsCategoryQuery)
                ->withType()
                ->findPk($this->parentId), $cacheKey, 0);
        }
        //zwrot rodzica
        return $parent;
    }
1030445
public function actionSearch($query = null)
    {
        $this->checkAccess('search');
        
        if (empty($query)) {
            $query = Yii::$app->request->post('query');
        }
        
        $find = $this->model->ngRestFullQuerySearch($query);
        
        return new ActiveDataProvider([
            'query' => $find->with($this->getWithRelation('search')),
            'pagination' => $this->pagination,
            'sort' => [
                'attributes' => $this->generateSortAttributes($this->model->getNgRestConfig()),
            ]
        ]);
    }
623002
public function main()
    {
        $mainPageHTML = '';
        $dbMaterials = array();

        // Получим все материалы
        if (
        dbQuery('samsoncms\api\Material')
            ->join('user')
            ->cond('Active', 1)
            ->cond('Draft', 0)
            ->order_by('Created', 'DESC')
            ->cond('Name', "", dbRelation::NOT_EQUAL)
            ->limit(5)
            ->exec($dbMaterials)
        ) {
            // Render material rows
            $rowsHTML = '';
            foreach ($dbMaterials as $dbMaterial) {
                $rowsHTML .= $this->view('main/row')
                    ->set($dbMaterial, 'material')
                    ->set(isset($dbMaterial->onetoone['_user']) ? $dbMaterial->onetoone['_user'] : array(), 'user')
                    ->output();
            }

            for ($i = sizeof($dbMaterials); $i < 5; $i++) {
                $rowsHTML .= $this->view('main/row')->output();
            }

            // Render main template
            $mainPageHTML = $this->view('main/index')->set($rowsHTML, 'rows')->output();
        }

        // Return material block HTML on main page
        return $mainPageHTML;
    }
1037560
public function run()
	{
		DB::table('page_lang')->insert([
			'id' => 1,
			'lang_id' => 1,
			'uri' => '/',
			'title' => 'Начало',
			'text' => 'Начало',
			'heading' => '',
			'content' => '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque mattis tempus nisl consequat sollicitudin. Duis commodo porttitor nunc, at dignissim sem mattis sed. Donec lorem massa, placerat quis iaculis ut, tristique sed sem. Nam id vulputate sem. Ut quis felis interdum, malesuada libero a, aliquet ipsum. Vestibulum vitae ex blandit, dictum neque ut, dictum sem. Proin tempor est at nibh convallis euismod.</p>',
			'meta_title' => 'Начало',
			'meta_keywords' => 'Начало',
			'meta_description' => 'Начало',
			'created_at' => date("Y-m-d H:i:s"),
			'updated_at' => date("Y-m-d H:i:s")
		]);
		DB::table('page_lang')->insert([
			'id' => 1,
			'lang_id' => 2,
			'uri' => '/',
			'title' => 'Home',
			'text' => 'Home',
			'heading' => '',
			'content' => '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque mattis tempus nisl consequat sollicitudin. Duis commodo porttitor nunc, at dignissim sem mattis sed. Donec lorem massa, placerat quis iaculis ut, tristique sed sem. Nam id vulputate sem. Ut quis felis interdum, malesuada libero a, aliquet ipsum. Vestibulum vitae ex blandit, dictum neque ut, dictum sem. Proin tempor est at nibh convallis euismod.</p>',
			'meta_title' => 'Home',
			'meta_keywords' => 'Home',
			'meta_description' => 'Home',
			'created_at' => date("Y-m-d H:i:s"),
			'updated_at' => date("Y-m-d H:i:s")
		]);		
	}
1327452
public function findWithBase($baseRecords)
	{
		if(!is_array($baseRecords))
			$baseRecords=array($baseRecords);
		if(is_string($this->_table->primaryKey))
		{
			foreach($baseRecords as $baseRecord)
				$this->records[$baseRecord->{$this->_table->primaryKey}]=$baseRecord;
		}
		else
		{
			foreach($baseRecords as $baseRecord)
			{
				$pk=array();
				foreach($this->_table->primaryKey as $name)
					$pk[$name]=$baseRecord->$name;
				$this->records[serialize($pk)]=$baseRecord;
			}
		}

		$query=new CJoinQuery($this);
		$this->buildQuery($query);
		if(count($query->joins)>1)
			$this->runQuery($query);
		foreach($this->children as $child)
			$child->find();

		foreach($this->stats as $stat)
			$stat->query();
	}
1258112
public function find()
    {
        if ($this->owner->isNewRecord === false && SeoSlug::getDb()->getSchema()->getTableSchema(SeoSlug::tableName(), true) !== null) {
            //Сначала попробуем найти запись в кеше
            $this->_slugModel = $this->_cache->get($this->owner);
            if (is_null($this->_slugModel)) {
                $this->_slugModel = SeoSlug::find()
                    ->where([
                        'AND',
                        ['=', 'model', $this->owner->className()],
                        ['=', 'model_id', $this->owner->getPrimaryKey()],
                    ])
                    ->orderBy(['id' => SORT_DESC])
                    ->one();
                //Если запись найдена положим найденную запись в кеш
                if ($this->_slugModel) {
                    $this->_cache->set($this->owner, $this->_slugModel);
                }
            }
            //Если запись найдена и указано поле в родительской модели то присвоем ему значение этого алиаса
            if ($this->_slugModel && $this->slugAttribute) {
                $this->owner->{$this->slugAttribute} = $this->_slugModel->slug;
            }
        }
    }
324996
protected function _initAutoFilters()
    {
        //Если автоопределение колонок не включено
        if (!$this->isEnabledAutoFilters) {
            return $this;
        }

        if (!$this->dataProvider) {
            return $this;
        }

        $dataProvider = clone $this->dataProvider;
        $models = $dataProvider->getModels();


        /**
         * @var $model Model
         * @var $model ActiveRecord
         */
        $model = reset($models);

        if (!$model) {
            $modelClass = $dataProvider->query->modelClass;
            $model = new $modelClass();
        }

        $result = [];

        $result['attributeDefines'] = [];
        if (method_exists($model, 'attributes')) {
            $result['attributeDefines'] = $model->attributes();
        }

        $result['attributeLabels'] = [];
        if (method_exists($model, 'attributeLabels')) {
            $result['attributeLabels'] = $model->attributeLabels();
        }


        $rules = [];
        $fields = [];

        if ($model instanceof ActiveRecord) {
            foreach ($model::getTableSchema()->columns as $key => $column) {
                if (in_array($column->type, ['string', 'text'])) {
                    $fields[(string)$key] = [
                        'class' => StringFilterField::class,
                    ];

                    $rules[] = [(string)$key, 'safe'];
                } else if (in_array($column->type, ['integer', 'decimal'])) {

                    $realKey = $key;
                    if (!empty($key) && strcasecmp($key, 'id')) {
                        if (substr_compare($key, 'id', -2, 2, true) === 0) {
                            $key = rtrim(substr($key, 0, -2), '_');
                        } elseif (substr_compare($key, 'id', 0, 2, true) === 0) {
                            $key = ltrim(substr($key, 2, strlen($key)), '_');
                        }
                    }

                    $keyMany = Inflector::pluralize($key);

                    $keyName = lcfirst(Inflector::id2camel($key, '_'));
                    $keyManyName = lcfirst(Inflector::id2camel($keyMany, '_'));


                    if ($relation = $model->getRelation($keyName, false)) {
                        if ($relation->modelClass && $relation->link) {

                            $arr = array_keys($relation->link);
                            $idName = $arr[0];
                            $modelClassName = $relation->modelClass;

                            $query = $modelClassName::find();

                            if ($query->count() > 1000) {
                                $fields[(string)$realKey] = [
                                    'class' => NumberFilterField::class,
                                ];
                            } else {
                                $fields[(string)$realKey] = [
                                    'class'             => NumberFilterField::class,
                                    'isAllowChangeMode' => false,
                                    'field'             => [
                                        'class'    => SelectField::class,
                                        'items'    => function () use ($idName, $query) {

                                            return ArrayHelper::map(
                                                $query->all(),
                                                $idName,
                                                'asText'
                                            );
                                        },
                                        'multiple' => true,
                                    ],
                                ];
                            }

                        }

                    }

                    if (!isset($fields[(string)$realKey])) {
                        $fields[(string)$realKey] = [
                            'class' => NumberFilterField::class,
                        ];
                    }

                    $rules[] = [(string)$realKey, 'safe'];

                } else {
                    $fields[(string)$key] = [
                        'class' => StringFilterField::class,
                    ];

                    $rules[] = [(string)$key, 'safe'];
                }

            }
        } elseif (is_array($model) || is_object($model)) {
            foreach ($model as $name => $value) {
                if ($value === null || is_scalar($value) || is_callable([$value, '__toString'])) {
                    $fields[(string)$name] = [
                        'class' => StringFilterField::class,
                    ];

                    $rules[] = [(string)$name, 'safe'];
                }
            }
        }

        $result['rules'] = $rules;
        $result['fields'] = $fields;
        $this->_autoDynamicModelData = $result;

        return $this;
    }
20709
protected function active()
    {
        if( empty($activeDatabaseList = $this->getActiveDatabaseList()) )
        {
            return false;
        }

        $this->setActiveDatabaseEncoding($encoding);

        $status = false;

        $tableKeyColumnDesignData = $this->getTableKeyColumnDesignData();
        
        foreach( $activeDatabaseList as $database )
        {
            $this->forge->createDatabase($database, $encoding);

            if( ! empty($activeTableList = $this->getTableListByActiveDatabase($database)) )
            {
                $dbForge = $this->getDBForgeDifferentConnectionByDatabaseName($database);
                $db      = $this->getDBDifferentConnectionByDatabaseName($database);

                foreach( $activeTableList as $table )
                {
                    $activeTableColumnSchema = $this->getActiveTableColumnSchema($database, $table);

                    $this->addIdColumnToActiveTableIfNotExists($activeTableColumnSchema);

                    $activeTableColumns = $this->getActiveTableColumns($table = $this->getTableNameWithoutExtension($table), $db);

                    $this->getActiveTableKeyAndColumns($activeTableColumns, $activeTableKey, $activeTableColumns);

                    $currentTableKey = $this->getCurrentTableKey($table, $activeTableColumnSchema);

                    if( ! empty($activeTableColumns) )
                    {
                        $columnsMerge = array_merge(array_flip($activeTableColumns), $activeTableColumnSchema);

                        foreach( $columnsMerge as $key => $val )
                        {
                            if( is_numeric($val) )
                            {
                                $this->dropColumnFromActiveTable($table, $key, $dbForge, $status);
                            }
                            elseif( in_array($key, $activeTableColumns) )
                            {
                                $this->modifyColumnFromActiveTable($table, $key, $val, $dbForge, $status, $activeTableKey, $currentTableKey);
                            }
                            else
                            {
                                $this->addColumnFromActiveTable($table, $key, $val, $dbForge, $status);
                            }
                        }

                        if( $status === true )
                        {
                            $this->addTableToArchive($database, $table);
                        }
                    }
                    else
                    {
                        $activeTableColumnSchema[$currentTableKey] = $tableKeyColumnDesignData;

                        $dbForge->createTable($table, $activeTableColumnSchema);
                    }
                }
            }
        }
    }
746143
function prop_join($class_name, $conditions = array())
	{
		$conditions['id IN'] = $this->keys();
		// Ищем все присоединяемые объекты с такими же ID, как у нас
		foreach(b2::find($class_name, $conditions)->all() as $x)
		{
			if($obj = $this->get($x->id()))
				$obj->_set_prop_joined($x);
		}
	}
224008
public function getCMSFields()
    {
        // PHP 5.3 only
        $self = $this;
        $this->beforeUpdateCMSFields(function (FieldList $fields) use ($self) {
            $fields->removeFieldsFromTab(
                'Root.Main',
                array('KeyValuePairs', 'SortBy', 'SortByDirection')
            );
            // Don't put the GridField for documents in until the set has been created
            if (!$self->isInDB()) {
                $fields->addFieldToTab(
                    'Root.Main',
                    LiteralField::create(
                        'GridFieldNotice',
                        '<p class="message warning">' . _t(
                            'DMSDocumentSet.GRIDFIELD_NOTICE',
                            'Managing documents will be available once you have created this document set.'
                        ) . '</p>'
                    ),
                    'Title'
                );
            } else {
                $fields->removeByName('DocumentSetSort');
                // Document listing
                $gridFieldConfig = GridFieldConfig::create()
                    ->addComponents(
                        new GridFieldButtonRow('before'),
                        new GridFieldToolbarHeader(),
                        new GridFieldFilterHeader(),
                        new GridFieldSortableHeader(),
                        new GridFieldDataColumns(),
                        new DMSGridFieldEditButton(),
                        // Special delete dialog to handle custom behaviour of unlinking and deleting
                        new GridFieldDeleteAction(true),
                        new GridFieldDetailForm()
                    );

                if (class_exists('GridFieldPaginatorWithShowAll')) {
                    $paginatorComponent = new GridFieldPaginatorWithShowAll(15);
                } else {
                    $paginatorComponent = new GridFieldPaginator(15);
                }
                $gridFieldConfig->addComponent($paginatorComponent);

                if (class_exists('GridFieldSortableRows')) {
                    $gridFieldConfig->addComponent(new GridFieldSortableRows('DocumentSort'));
                } elseif (class_exists('GridFieldOrderableRows')) {
                    $gridFieldConfig->addComponent(new GridFieldOrderableRows('DocumentSort'));
                }

                // Don't show which page this is if we're already editing within a page context
                if (Controller::curr() instanceof CMSPageEditController) {
                    $fields->removeByName('PageID');
                } else {
                    $fields->fieldByName('Root.Main.PageID')->setTitle(_t('DMSDocumentSet.SHOWONPAGE', 'Show on page'));
                }

                // Don't show which page this is if we're already editing within a page context
                if (Controller::curr() instanceof CMSPageEditController) {
                    $fields->removeByName('PageID');
                } else {
                    $fields->fieldByName('Root.Main.PageID')->setTitle(_t('DMSDocumentSet.SHOWONPAGE', 'Show on page'));
                }

                $gridFieldConfig->getComponentByType('GridFieldDataColumns')
                    ->setDisplayFields($self->getDocumentDisplayFields())
                    ->setFieldCasting(array('LastEdited' => 'Datetime->Ago'))
                    ->setFieldFormatting(
                        array(
                            'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\''
                                . ' href=\'$Link\'>$FilenameWithoutID</a>',
                            'ManuallyAdded' => function ($value) {
                                if ($value) {
                                    return _t('DMSDocumentSet.MANUAL', 'Manually');
                                }
                                return _t('DMSDocumentSet.QUERYBUILDER', 'Query Builder');
                            }
                        )
                    );

                // Override delete functionality with this class
                $gridFieldConfig->getComponentByType('GridFieldDetailForm')
                    ->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
                $gridField = GridField::create(
                    'Documents',
                    false,
                    $self->Documents(),
                    $gridFieldConfig
                );
                $gridField->setModelClass('DMSDocument');
                $gridField->addExtraClass('documents');

                $gridFieldConfig->addComponent(
                    $addNewButton = new DMSGridFieldAddNewButton('buttons-before-left'),
                    'GridFieldExportButton'
                );
                $addNewButton->setDocumentSetId($self->ID);

                $fields->removeByName('Documents');
                $fields->addFieldsToTab(
                    'Root.Main',
                    array(
                        $gridField,
                        HiddenField::create('DMSShortcodeHandlerKey', false, DMS::inst()->getShortcodeHandlerKey())
                    )
                );
                $self->addQueryFields($fields);
            }
        });
        $this->addRequirements();
        return parent::getCMSFields();
    }
454951
public function buildElementsQuery(\yii\db\ActiveQuery $activeQuery)
    {
        $where = [];

        //Нужно учитывать связанные дополнительные данные
        if ($this->enabledElementProperties == Cms::BOOL_Y) {
            $activeQuery->joinWith('cmsContentElementProperties');

            //Нужно учитывать настройки связанные дополнительные данных
            if ($this->enabledElementPropertiesSearchable == Cms::BOOL_Y) {
                $activeQuery->joinWith('cmsContentElementProperties.property');

                $where[] = [
                    'and',
                    ['like', CmsContentElementProperty::tableName() . ".value", '%' . $this->searchQuery . '%', false],
                    //[CmsContentProperty::tableName() . ".searchable" => Cms::BOOL_Y]
                ];
            } else {
                $where[] = [
                    'like',
                    CmsContentElementProperty::tableName() . ".value",
                    '%' . $this->searchQuery . '%',
                    false
                ];
            }
        }

        //Поиск по основному набору полей
        if ($this->searchElementFields) {
            foreach ($this->searchElementFields as $fieldName) {
                $where[] = [
                    'like',
                    CmsContentElement::tableName() . "." . $fieldName,
                    '%' . $this->searchQuery . '%',
                    false
                ];
            }
        }

        if ($where) {
            $where = array_merge(['or'], $where);
            $activeQuery->andWhere($where);
        }

        //Отфильтровать только конкретный тип
        if ($this->searchElementContentIds) {
            $activeQuery->andWhere([
                CmsContentElement::tableName() . ".content_id" => (array)$this->searchElementContentIds
            ]);
        }

        return $this;
    }
805743
public function getForm(GridField $grid, DataObjectInterface $record)
    {
        $fields = $this->getFields($grid, $record);

        $form = new Form($grid, null, $fields, new FieldList());
        $form->loadDataFrom($record);

        $form->setFormAction(Controller::join_links(
            $grid->Link(),
            'editable/form',
            $record->ID
        ));

        return $form;
    }
711546
public function __HANDLER()
    {
        // Create query to get users
        $query = dbQuery('user')->Active(1)->order_by('UserID');

        // Create generic table for users
        $table = new Table($query);

        // Установим представление
        m()->view('main/index')->title(t('Пользователи системы', true))
            ->all_materials(true)
            // Установим шаблон таблицы пользователей
            ->user_table($table->render());
    }
262112
public function updateDB()
    {
        if (($fileName = $this->getArchive()) === false) {
            throw new Exception('Ошибка загрузки архива.');
        }
        $zip = new \ZipArchive;
        if ($zip->open($fileName) !== true) {
            @unlink($fileName);
            throw new Exception('Ошибка распаковки.');
        }

        $this->generateIpTable($zip);
        $this->generateCityTables($zip);
        $zip->close();
        @unlink($fileName);
    }
1047230
public function get_active_method() {
        global $DB;

        $this->ensure_isset(array('context', 'component', 'area'));

        // get the current grading area record if it exists
        if (is_null($this->areacache)) {
            $this->areacache = $DB->get_record('grading_areas', array(
                'contextid' => $this->context->id,
                'component' => $this->component,
                'areaname'  => $this->area),
            '*', IGNORE_MISSING);
        }

        if ($this->areacache === false) {
            // no area record yet
            return null;
        }

        return $this->areacache->activemethod;
    }
1223102
static function save_object($object, $content, $ttl = false)
	{
		$object_id = $object->id();

		$file = $object->static_file();
		if(!$file) // TODO: отловить
		{
			bors_debug::syslog('static-file-notice', "empty static_file() for ".$object->debug_title());
			return;
		}

		if(preg_match('/,new/', $file))
			bors_debug::syslog('static-file-logic-error', "New page for ".$object->debug_title());

		//TODO: отловить кеш-запись постов при добавлении нового сообщения. (class_id = 1)
		bors()->changed_save();

		// Если это просто обновление кеша, то у нас тут будет найденная запись из ::drop
		if(config('cache_database'))
		{
			if(!($cache = $object->attr('static_recreate_object')))
				$cache = bors_load_ex('cache_static', $file, array('no_load_cache' => true));
		}
		else
			$cache = NULL;

		$object_uri = $object->url_ex($object->page());
		$original_uri = $object->called_url();

		if(!$original_uri)
			$original_uri = $object_uri;

//		if($object->class_name() == 'balancer_board_topic' || $object->class_name() == 'forum_topic')
//			bors_debug::syslog('__cache_file_register', "file=".$file."\nobject=".$object->debug_title()."\npage=".$object->page()."\ncache=".($cache?'yes':'no'));

		$expire_time = time() + ($ttl === false ? $object->cache_static() : $ttl);
//		bors_debug::syslog('00time', "o={$object->debug_title()}; ttl=$ttl, cs=".$object->cache_static()."; mt=".date("r", $object->modify_time())."; expired=".date('r', $expire_time));

		if(($ic=config('internal_charset')) != ($oc=config('output_charset')))
			$content = iconv($ic, $oc.'//translit', $content);

		bors_function_include('fs/file_put_contents_lock');

		mkpath($dir = dirname($file), 0777);

		if(is_writable($dir))
		{
			file_put_contents_lock($file, $content);
			if(is_file($file))
			{
				// Скрываем, т.к. файл может не принадлежать нашему пользователю.
				@chmod($file, 0666);

				if(!($mt = $object->modify_time()))
					$mt = time();

				@touch($file, $mt, $expire_time);
			}
		}

		if(!file_exists($file) || !is_file($file))
			bors_debug::syslog('warning-filesystem', "Can't create static file.\n
	object: {$object}\n
	file: {$file} (fe=".file_exists($file)
		.';isf='.is_file($file)
		.';isw='.is_writable($dir).")");

		if(config('cache_database'))
		{
			if($cache)
			{
//				echo "Update $file<br/>\n";
				$cache->set_target_class_name($object->class_name(), true);
				$cache->set_target_class_id($object->class_id(), true);
				$cache->set_target_id($object->id(), true);
				$cache->set_target_page($object->page(), true);
				$cache->set_last_compile(time(), true);
				$cache->set_expire_time($expire_time, true);
				$cache->set_recreate($object->cache_static_recreate(), true);

				if($original_uri)
					$cache->set('original_uri', $original_uri, true);

				$cache->store();
			}
			else
			{
				$cache = bors_new('cache_static', array(
					'id' => $file,
					'original_uri' => $original_uri,
					'target_class_name' => $object->class_name(),
					'target_class_id' => $object->class_id(),
					'target_id' => $object->id(),
					'target_page' => $object->page(),
					'last_compile' => time(),
					'expire_time' => $expire_time,
					'recreate' => $object->cache_static_recreate(),
//					'bors_site' => BORS_SITE,
				));

//				config_set('debug_mysql_queries_log', false);

//				if($object->class_name() == 'balancer_board_topic' || $object->class_name() == 'forum_topic')
//					bors_debug::syslog('__cache_file_register2', "file=".$file."\nobject=".$object->debug_title()."\npage=".$object->page()."\ncache_id=".$cache->id()."\ncache_page=".$cache->target_page());
			}

			foreach(explode(' ', $object->cache_depends_on()) as $group_name)
				if($group_name)
					cache_group::register($group_name, $object);

			foreach($object->cache_parents() as $parent_object)
				cache_group::register($parent_object->internal_uri_ascii(), $object);

//			$object->set_was_cleaned(false);
		}

	}