V
V
Victor Umansky2017-08-22 12:03:54
Yii
Victor Umansky, 2017-08-22 12:03:54

Yii2 How to properly filter products with model search checkboxes?

Hello everyone, I don’t understand how to properly filter products by properties. I have yii2 advanced!
In the filter, I want to display at least a primitive one in order to understand how the search itself works.
I displayed the manufacturer's checkboxes and in the address bar I have

http://sportpit.alex-sport.com.ua/category/index?ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=62&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0&ProductPitSearch%5Bbrand_id%5D=0

ProductPitSearch
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\ProductPit;

/**
 * ProductPitSearch represents the model behind the search form about `common\models\ProductPit`.
 */
class ProductPitSearch extends ProductPit
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'status', 'new', 'hit', 'sale', 'stock', 'top_sales', 'top_ten', 'category_id', 'img_id', 'gallery_id', 'brand_id', 'country_id', 'quantity', 'quantity_product', 'packing', 'availability', 'created_at', 'updated_at'], 'integer'],
            [['title', 'content', 'composition', 'vendor_code', 'seo_keywords', 'seo_description'], 'safe'],
            [['old_price', 'price'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ProductPit::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'brand_id' => $this->brand_id,
            'country_id' => $this->country_id,
            'packing' => $this->packing,
        ]);

        $query->andFilterWhere(['like', 'brand_id', $this->brand_id])
            ->andFilterWhere(['like', 'country_id', $this->country_id])
            ->andFilterWhere(['like', 'packing', $this->packing]);

        return $dataProvider;
    }
}

CategoryController
<?php

namespace sportpit\controllers;

use Yii;
use common\models\ProductPit;
use common\models\ProductPitSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CategoryController implements the CRUD actions for ProductPit model.
 */
class CategoryController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ProductPit models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProductPitSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Finds the ProductPit model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ProductPit the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProductPit::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

_search
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\models\ProductPit;
use yii\helpers\ArrayHelper;

/* @var $this yii\web\View */
/* @var $model common\models\ProductPitSearch */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="product-pit-search">

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>


    <?php

    $manufactures = ArrayHelper::map(ProductPit::find()->all(), 'brand_id', 'id');

    foreach ($manufactures as $key => $value) {

        echo $form->field($model, 'brand_id')->checkbox(
            [
                'label' => ProductPit::getManufacturesTitle($value),
                'value' => $value
            ]
        );
        echo '<br/>';
    }

    ?>

    <?php // echo $form->field($model, 'country_id') ?>

    <?php // echo $form->field($model, 'packing') ?>

    <div class="form-group">
        <?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>
    </div>

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

</div>

index
<?php

use yii\helpers\Html;
use yii\widgets\ListView;
use yii\widgets\Pjax;

/* @var $this yii\web\View */
/* @var $searchModel common\models\ProductPitSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Product Pits');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="product-pit-index">

    <?php echo $this->render('_search', ['model' => $searchModel]); ?>

    <?php Pjax::begin(); ?>
    <?= ListView::widget([
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'item'],
        'itemView' => function ($model, $key, $index, $widget) {
            return $this->render('_all', ['model' => $model]);
        },
//        'itemView' => function ($model, $key, $index, $widget) {
//            return Html::a(Html::encode($model->title), ['view', 'id' => $model->id]);
//        },
    ]) ?>
    <?php Pjax::end(); ?>
</div>

_all
<?php

use yii\helpers\Html;
use yii\helpers\Url;
use common\models\ProductPit;
use common\models\CategoryPit;

?>

<div class="main_block">
    <?php if ($model['hit']) : ?>
        <div class="hit_product label label-success">Хит</div>
    <?php endif; ?>
    <?php if ($model['new']) : ?>
        <div class="new_product label label-primary">Новинка</div>
    <?php endif; ?>
    <?php if ($model['sale']) : ?>
        <div class="sale_product label label-danger">Распродажа</div>
    <?php endif; ?>
    <?php if ($model['stock']) : ?>
        <div class="sale_product label label-danger">Акция</div>
    <?php endif; ?>
    <div class="image_block">
        <a href="<?= Url::to(['product/view', 'id' => $model['id']]) ?>">
            <?php if ($model['img_id']) : ?>
                <?= Html::img('/web/uploads/products/' . ProductPit::getImageTitle($model['img_id']), ['width' => '105', 'height' => '150']) ?>
            <?php else: ?>
                <?= Html::img('/web/uploads/system/no-image.png', ['width' => '105', 'height' => '150']) ?>
            <?php endif; ?>
        </a>
    </div>
    <div class="title_block">
        <a href="<?= Url::to(['product/view', 'id' => $model['id']]) ?>">
            <h1>
                <?= $model['title'] ?>
            </h1>
        </a>
    </div>
    <div class="category_block"><?= CategoryPit::getTitleCategory($model['category_id']) ?></div>
    <div class="rating_block">*****</div>
    <div class="price_block"><?= $model['price'] ?> грн.</div>
    <div class="btn_buy_block">
        <a class="add-to-cart" data-id="<?= $model['id'] ?>"
           href="<?= Url::to(['product/view', 'id' => $model['id']]) ?>">Купить</a>
    </div>
</div>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question