Собственно вопрос в названии: есть модель, без связанных и вычисляемых полей, генерировалась через Gii. Если в фильтре по полю 'name' задать значение поиска, допустим "Квиллинг", то фильтр вместо того, чтобы отфильтровать, выдаёт "Значение «Квиллинг» для «Название» уже занято".
[['name'], 'safe']
в rules()
присутствует. Код стандартный, поэтому не выкладываю.
Как я понимаю, это отрабатывает валидатор. Но почему и зачем. Что именно его вызывает и как побороть?
Вот GridView
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'boxUnderTitle' => [
Html::a('Создать категорию', ['create'], ['class' => 'btn btn-success']),
],
'columns' => [
[
'headerOptions' => ['style' => 'width:5%'],
'class' => 'yii\grid\SerialColumn',
'headerOptions' => ['style' => ['width' => '3%']],
],
[
'attribute' => 'id',
'format' => 'raw',
'headerOptions' => ['style' => ['width' => '3%']],
'value' => function ($model) {
return $model->id;
},
],
[
'attribute' => 'parent_id',
'format' => 'raw',
'headerOptions' => ['style' => ['width' => '12%'], 'class' => 'small'],
'value' => function ($model) {
return $model->getName($model->parent_id).'<br>('.$model->parent_id.')';
},
],
[
'attribute' => 'name',
'format' => 'raw',
'value' => function ($model) {
return Html::a($model->name, yii::$app->params['mainhost'].'/categories/'.$model->alias,['target' => '_blank']);
},
],
[
'attribute' => 'countProducts',
'format' => 'raw',
'value' => function ($model) {
return Html::a($model->getCountProducts(), '/product/index?ProductSearch[category_id]='.$model->id,['target' => '_blank']);
},
],
// [
// 'attribute' => 'countPages',
// 'value' => function($model){
// $res = $model->getCountPages($model->id);
// return $res;
// }
// ],
// 'landings',
'meta_title',
'meta_keywords',
'meta_description',
'h1',
[
'attribute' => 'description',
'format' => 'raw',
'headerOptions' => ['style' => 'width:12%', 'class' => 'small'],
'contentOptions' => ['class' => 'middle'],
'value' => function($model){
if($model->description) : $res = '<span style="color:'.ColorHelper::STATUS_COMPLETED.'">description: есть</span>' ; else : $res = '<span style="color:'.ColorHelper::STATUS_DELETE.'">description: нет</span>'; endif;
if($model->description1) : $res1 = '<span style="color:'.ColorHelper::STATUS_COMPLETED.'">description1: есть</span>' ; else : $res1 = '<span style="color:'.ColorHelper::STATUS_DELETE.'">description1: нет</span>'; endif;
if($model->description2) : $res2 = '<span style="color:'.ColorHelper::STATUS_COMPLETED.'">description2: есть</span>' ; else : $res2 = '<span style="color:'.ColorHelper::STATUS_DELETE.'">description2: нет</span>'; endif;
if($model->description3) : $res3 = '<span style="color:'.ColorHelper::STATUS_COMPLETED.'">description3: есть</span>' ; else : $res3 = '<span style="color:'.ColorHelper::STATUS_DELETE.'">description3: нет</span>'; endif;
if($model->description4) : $res4 = '<span style="color:'.ColorHelper::STATUS_COMPLETED.'">description4: есть</span>' ; else : $res4 = '<span style="color:'.ColorHelper::STATUS_DELETE.'">description4: нет</span>'; endif;
if($model->description5) : $res5 = '<span style="color:'.ColorHelper::STATUS_COMPLETED.'">description5: есть</span>' ; else : $res5 = '<span style="color:'.ColorHelper::STATUS_DELETE.'">description5: нет</span>'; endif;
return $res.'<br>'.$res1.'<br>'.$res2.'<br>'.$res3.'<br>'.$res4.'<br>'.$res5;
}
],
[
// 'class' => 'yii\grid\CheckboxColumn',
'class' => 'yii\grid\ActionColumn',
'visibleButtons' => [
'view' => true,
'update' => true,
'delete' => function ($url,$model) {
/** @var $model common\models\Categories */
return Html::a('<span class="glyphicon glyphicon-trash"/>',Url::toRoute(['delete','id'=>$model->id]),['title'=>'Удалить']);
},
// 'delete'=>function ($model)use($searchModel) {
// /** @var $model common\models\Categories */
// $cat = $searchModel::findOne($model->id);
// return $cat->hasCategoryProduct($model->id);
// }
]
],
// [
// 'buttons' => [
// 'view' => function ($url,$model) {
// /** @var $model common\models\Categories */
// return Html::a('<span class="glyphicon glyphicon-eye-open"/>',Url::toRoute(['view',
// 'id'=>$model->id]),['title'=>'Просмотр']);
// },
// 'update' => function ($url,$model) {
// /** @var $model common\models\Categories */
// return Html::a('<span class="glyphicon glyphicon-pencil"/>',Url::toRoute(['update',
// 'id'=>$model->id]),['title'=>'Редактировать']);
// },
// 'delete' => function ($url,$model) {
// /** @var $model common\models\Categories */
// return Html::a('<span class="glyphicon glyphicon-trash"/>',Url::toRoute(['delete',
// 'id'=>$model->id]),['title'=>'Удалить']);
// },
// ],
// ],
],
]); ?>
Вот модель
<?php
namespace common\models;
use common\components\MenuTree;
use yii\behaviors\SluggableBehavior;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use common\models\LandingPagesCategories;
use yii;
/**
* Categories model
*
* @property integer $id
* @property integer $parent_id
* @property integer $fee_service
* @property integer $fee_seller
* @property string $alias
* @property string $name
* @property integer $created_at
* @property integer $updated_at
* @property integer $level
*/
class Categories extends \yii\db\ActiveRecord
{
const DEFAULT_CATEGORY = 'system';
const GROUP_YES = 1;
const GROUP_NO = 0;
public $level;
public $names = [];
public $min_price = 0;
public $landings = [];
public $isGroup = [
self::GROUP_YES => 'Групповая категория',
self::GROUP_NO => 'Категория для товара',
];
public function behaviors()
{
return [
[
'class' => SluggableBehavior::className(),
'attribute' => 'name',
'slugAttribute' => 'alias',
'immutable' => true,
'ensureUnique'=>true,
],
];
}
/**
* @return string
*/
public static function tableName()
{
return '{{%categories}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[
[
'id',
'parent_id',
'groups',
'fee_service',
'fee_seller',
'name',
'alias',
'created_at',
'updated_at',
'names',
'landings',
'meta_title',
'meta_keywords',
'meta_description',
'h1',
'description',
'description1',
'description2',
'description3',
'description4',
'description5',
// 'countProducts',
], 'safe'
],
['name','unique'],
// [['parent_id','name'],'required'],
[['meta_title', 'meta_description', 'meta_keywords', 'h1'], 'string'],
[['description','description1', 'description2','description3','description4','description5'], 'string'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => \Yii::t('app','ID'),
'parent_id' => \Yii::t('app','Родитель'),
'groups' => Yii::t('app','Содержит другие категории, не содержит товар'),
'fee_service' => \Yii::t('app','% Системы'),
'fee_seller' => \Yii::t('app','% Продавца'),
'alias' => \Yii::t('app','Алиас'),
'name' => \Yii::t('app','Название'),
'created_at' => \Yii::t('app','Создание'),
'updated_at' => \Yii::t('app','Обновление'),
'description' => Yii::t('app', 'Описание для страницы без page').' '.yii::t('app','count_symbols').': '.iconv_strlen(strip_tags($this->description)),
'description1' => Yii::t('app', 'Описание для page1').' '.yii::t('app','count_symbols').': '.iconv_strlen(strip_tags($this->description1)),
'description2' => Yii::t('app', 'Описание для page2').' '.yii::t('app','count_symbols').': '.iconv_strlen(strip_tags($this->description2)),
'description3' => Yii::t('app', 'Описание для page3').' '.yii::t('app','count_symbols').': '.iconv_strlen(strip_tags($this->description3)),
'description4' => Yii::t('app', 'Описание для page4').' '.yii::t('app','count_symbols').': '.iconv_strlen(strip_tags($this->description4)),
'description5' => Yii::t('app', 'Описание для page5').' '.yii::t('app','count_symbols').': '.iconv_strlen(strip_tags($this->description5)),
'countProducts' => Yii::t('app','Кол товаров'),
'meta_title' => Yii::t('app','meta_title').' '.yii::t('app','ValueForNumberPage'),
'meta_keywords' => Yii::t('app','meta_keywords').' '.yii::t('app','ValueForNumberPage'),
'meta_description' => Yii::t('app','meta_description').' '.yii::t('app','ValueForNumberPage'),
'h1' => Yii::t('app','h1').' '.yii::t('app','ValueForNumberPage'),
];
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Categories::find()->with(['products']);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'attributes' => [
'id',
'parent_id',
'groups',
'fee_service',
'fee_seller',
'name',
'alias',
'created_at',
'updated_at',
'names',
'landings',
'meta_title',
'meta_keywords',
'meta_description',
'h1',
'description',
'description1',
'description2',
'description3',
'description4',
'description5',
],
'defaultOrder' => ['id' => SORT_ASC]
]
]);
$this->load($params);
if (!$this->validate()) {
$query->joinWith(['products']);
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id
]);
$query->andFilterWhere(['like', 'parent_id', $this->parent_id])
->andFilterWhere(['like', 'fee_service', $this->fee_service])
->andFilterWhere(['like', 'fee_seller', $this->fee_seller])
->andFilterWhere(['like', 'name', $this->name])
// ->andFilterWhere(['like', 'alias', $this->alias])
->andFilterWhere(['like', 'created_at', strtotime($this->created_at)])
->andFilterWhere(['like', 'updated_at', strtotime($this->updated_at)]);
return $dataProvider;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUserCategories()
{
return $this->hasMany(UserCategories::className(), ['category_id' => 'id']);
}
public function getMainCategory(){
return self::findOne(['parent_id'=>$this->id]);
}
public function getParentCategory(){
return self::findOne(['id'=>$this->parent_id])->with('products.provider','products.user');
}
public function getProducts()
{
return $this->hasMany(Product::className(), ['category_id' => 'id']);
}
// public function getProductsCount()
// {
// return $this->hasMany(Product::className(), ['category_id' => 'id'])
// ->count();
// }
// public function getProductsCountVisible()
// {
// return $this->hasMany(Product::className(), ['category_id' => 'id'])
// ->Where(['visible' => 1])
// ->count();
// }
public function getCategoryFeeService(){
if($this->parent_id === 0){
$fee_service = $this->fee_service;
}else{
if($this->fee_service != null){
$fee_service = $this->fee_service;
}else{
$mainCategories = Categories::findOne($this->parent_id);
$fee_service = $mainCategories->fee_service;
}
}
return $fee_service;
}
public function getCategoryFeeSeller($order = false){
if($order && $order->provider->isOperationByPayment() && $order->provider->reward_percent!=0){
return $order->provider->reward_percent;
}else{
if($this->parent_id === 0){
$fee_seller = $this->fee_seller;
}else{
if($this->fee_seller != null){
$fee_seller = $this->fee_seller;
}else{
$mainCategories = Categories::findOne($this->parent_id);
$fee_seller = $mainCategories->fee_seller;
}
}
return $fee_seller;
}
}
public function getMainCategoriesForAdmin(){
$arr[0] = 'Главная';
foreach (Categories::find()->asArray()->all() as $v){
$arr[$v['id']] = $v['name'];
}
return $arr;
}
public function getMainCategories($createCat = false,$hasProduct = false,$target = null){
$catsIdWithoutProd = [];
$arrCats = Categories::find()->asArray()->all();
if($target != null) {
$categoryTree = new MenuTree($arrCats);
$categoryTree->build();
$tree = $categoryTree->getItemsTree();
$targetChain = [];
$targetChain = $this->find_node($tree,$target);
$kickIds[] = $target;
$kickIds = $this->find_node_keys($kickIds,$targetChain);
}
foreach ($arrCats as $index=>$value){
if($target != null) {
if (in_array($value['id'], $kickIds)) {
unset($arrCats[$index]);
continue;
}
}
if($hasProduct == true){
if(Product::find()->where(['category_id'=>$value['id']])->count() > 0 && !in_array($value['id'], $catsIdWithoutProd))
$catsIdWithoutProd[] = $value['id'];
}else {
if(Product::find()->where(['category_id'=>$value['id']])->count() == 0 && !in_array($value['id'], $catsIdWithoutProd))
$catsIdWithoutProd[] = $value['id'];
}
}
if($hasProduct != 'all')
$cats = Categories::find()->where(['id'=>$catsIdWithoutProd])->asArray()->all();
else
$cats = $arrCats;
//
$categoryTree = new MenuTree($cats);
$categoryTree->build();
$tree = $categoryTree->getItemsTree();
if($createCat) $result[0] = 'Главная';
// VarDumper::dump($tree,1000,true);die();
$result = $this->getBuildTreeList($result,'',$tree);
return $result;
}
public function getMainCategories2(){
$res = $this->find()->where(['!=' , 'groups', self::GROUP_NO])->asArray()->all();
$res = ArrayHelper::map($res, 'id', 'name');
$res[0] = '---';
return $res;
}
public function hasProducts(){
return Product::find()->where(['category_id'=>$this->id])->exists();
}
public function getBuildTreeList(&$result,$parentName = '',$categories) {
foreach ($categories as $i=>$cat){
if($cat['parent_id'] == 0 ) $parentName = $cat['name'];
$oldParentName = $parentName;
if(isset($cat['children']) && count($cat['children'])){
if($parentName == $cat['name'] && $cat['parent_id'] == 0) {
$result[$i] =$cat['name'];
}
elseif($parentName !== '' && $cat['parent_id'] !== 0) {
$parentName .= ' / '.$cat['name'];
$result[$i] = $parentName;
}
foreach ($cat['children'] as $id=>$child){
self::getBuildTreeList($result,$parentName,$cat['children']);
}
$parentName = $oldParentName;
}else{
if($parentName == $cat['name'])
$result[$i] =$cat['name'];
elseif($parentName !== '' && $parentName !== $cat['name'])
$result[$i] = $parentName.' / '.$cat['name'];
}
}
return $result;
}
public function getSubCategories(){
$result = $this->getMainCategories(false,'all');
$result[100000] = Yii::t('app', 'not-sel-cat');
foreach ($result as $id=>$cat ){
if(Categories::find()->where(['parent_id'=>$id])->exists())
unset($result[$id]);
}
// VarDumper::dump($result,1000,true);
return $result;
}
public function hasSubCategories(){
$categoryTree = new MenuTree(Categories::find()->asArray()->all());
$categoryTree->build();
$tree = $categoryTree->getItemsTree();
$targetChainProd = $this->find_node($tree,$this->id);
$productCatIds[] = $this->id;
$productCatIds = $this->find_node_keys($productCatIds,$targetChainProd);
// VarDumper::dump($productCatIds,100,true);die();
if (count($productCatIds) >1) {
return true;
}elseif(count($productCatIds) == 1){
return false;
}
// VarDumper::dump(count($productCatIds),100,true);die();
}
public function treeForAdminCategory(){
$categoryTree = new MenuTree(Categories::find()->asArray()->orderBy(['id'=>SORT_ASC])->all());
$categoryTree->build();
$tree = $categoryTree->getItemsTree();
$categories = [];
foreach (Categories::find()->orderBy(['id'=>SORT_ASC])->all() as $c){
$categories[$c->id] = $c;
}
$result = [];
$result = $this->getTreeForViewAdmin($result, $tree);
$r = [];
foreach ($result as $val){
$item = $categories[$val['id']];
$item->level = $val['level'];
$r[$val['id']] = $item;
}
return $r;
}
private function getTreeForViewAdmin(&$result,$dataset,$level = 1)
{
foreach ($dataset as $id => $child) {
$item = $child;
unset($item['children']);
$item['level'] = $level;
$result[] =[
'id'=>$item['id'],
'level'=>$level
];
if (isset($child['children']) && count($child['children'])){
$this->getTreeForViewAdmin($result,$child['children'],$level + 1);
}
}
return $result;
}
public function hasCategoryProduct($id)
{
$model = $this->findOne($id);
$categoryTree = new MenuTree(Categories::find()->asArray()->all());
$categoryTree->build();
$tree = $categoryTree->getItemsTree();
$targetChainProd = $this->find_node($tree,$model->id);
$productCatIds[] = $model->id;
$productCatIds = $this->find_node_keys($productCatIds,$targetChainProd);
$cats = Categories::findAll($productCatIds);
$userCats = [];
foreach ($cats as $cat){
$usrCats = $cat->userCategories;
foreach ($usrCats as $usrCat){
if(!in_array($usrCat->id,$userCats) && $usrCat->id !== null)
$userCats[] = $usrCat->id;
}
unset($usrCats);
}
if((count($productCatIds) == 1) && (Product::find()->where(['category_id'=>$productCatIds])->count() == 0) && (count($userCats) == 0)) {
return true;
}
else
return false;
}
public function findAllParentsCat(&$result,$dataset,$targetId){
if(isset($dataset[$targetId]['parent_id']) && $dataset[$targetId]['parent_id'] != 0 ){
foreach ($dataset as $cat){
if($cat['id'] == $targetId){
$result[] = $cat['parent_id'];
$this->findAllParentsCat($result,$dataset,$cat['parent_id']);
}
}
}
return $result;
}
public function find_node_keys(&$result,$dataset) {
if(isset($dataset['children']) && count($dataset['children'])){
foreach ($dataset['children'] as $id=>$child){
$result[] = $id;
self::find_node_keys($result,$child);
}
}else{
if(!in_array((int)$dataset['id'],$result))
$result[] = (int)$dataset['id'];
}
return $result;
}
public function find_node(&$dataset,$id) {
if(isset($dataset[$id])) return $dataset[$id];
foreach ($dataset as $value){
if (isset($value['children'])) {
$result=self::find_node($value['children'], $id);
if ($result) return $result;
}
}
return false;
}
public function getUrl()
{
return Url::toRoute(['categories/index', 'alias' => $this->alias]);
}
public function getParentCategoriesIds(){
$arr = [];
foreach (Categories::find()->asArray()->all() as $cat){
$arr[$cat['id']]['id'] = $cat['id'];
$arr[$cat['id']]['parent_id'] = $cat['parent_id'];
$arr[$cat['id']]['name'] = $cat['name'];
}
$list = [];
$list = self::findAllParentsCat($list,$arr,$this->id);
return $list;
}
public function save($runValidation = true, $attributeNames = null){
if (!empty($this->landings)) {
$all = ArrayHelper::index(LandingPagesCategories::find()->select(["landing_id"])->where(['category_id'=>$this->id])->asArray()->all(),'landing_id');
foreach($this->landings as $lend){
if(!LandingPagesCategories::find()->where(['category_id'=>$this->id,'landing_id'=>$lend])->exists()){
$new_prod = new LandingPagesCategories();
$new_prod->category_id = $this->id;
$new_prod->landing_id = $lend;
$new_prod->created_at = time();
$new_prod->save();
}
unset($all[$lend]);
}
foreach($all as $al){
LandingPagesCategories::find()->where(['category_id'=>$this->id,"landing_id"=>$al['landing_id']])->one()->delete();
}
}
return parent::save($runValidation, $attributeNames);
}
public function lendingList()
{
$this->landings = ArrayHelper::getColumn(LandingPagesCategories::find()->where(['category_id'=>$this->id])->asArray()->all(),'landing_id');
return \common\models\LandingPages::List();
}
public function getDefoultCategory(){
return self::findOne(['name'=>self::DEFAULT_CATEGORY])->id;
}
public function getCountProducts() {
$products = $this->products;
return ($products) ? count($products) : 0;
}
public function getName($id) {
$res = Categories::find()->where(['id' => $id])->one();
return $res->name;
}
}
Вот контроллер
public function actionSeo()
{
$searchModel = new Categories();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('seo', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}