GridView зависимый от select
Re: GridView зависимый от select
Код GridView покажите с формой поиска
Re: GridView зависимый от select
_search
GridView
Код: Выделить всё
$js = <<< JS
$("#pjaxFilter").on("pjax:end", function() {
$.pjax.reload({container:"#pjaxContainer"});
});
JS;
$this->registerJs($js, yii\web\View::POS_READY);
?>
<?php yii\widgets\Pjax::begin(['id' => 'pjaxFilter']) ?>
<?php $form = ActiveForm::begin([
'options' => ['data-pjax' => true ],
'action' => ['index'],
'method' => 'get',
]);
?>
<?= $form->field($model, 'customers_id')
->label(false)
->widget(\kartik\select2\Select2::class, [
'data' => ArrayHelper::map(Customers::find()->all(), 'name', 'name'),
'options' => [
'placeholder' => 'Customers...',
'multiple' => true,
],
]) ?>
<div class="form-group">
<?= Html::submitButton('Искать', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end() ?>
Код: Выделить всё
<div class="row no-gutters filter-panel">
<?= $this->render('_search', [
'model' => $searchModel,
]) ?>
</div>
<?php Pjax::begin([
'id' => 'pjaxContainer'
]); ?>
<?php
try {
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'pjax' => true,
'columns' => [
'id',
[
'attribute' => 'products_id',
'label' => 'products_id',
],
[
'attribute' => 'products_id',
'label' => 'products.name',
],
],
]);
} catch (Exception $e) {
throw new RuntimeException($e -> getMessage());
}
?>
<?php Pjax::end(); ?>
Re: GridView зависимый от select
Вот так сходу я даже и не могу сказать, что у вас отправляется по коду
$("#pjaxFilter").on("pjax:end", function() {
$.pjax.reload({container:"#pjaxContainer"});
});
У вас два pjax, когда первый срабатывает, второй отправляется. Но вот отправляется куда и с какими данными... это надо смотреть в debug панели браузера и в соотвествии с той картиной вносить изменения в код. Возможно при отправки второго pjax не отправляются фильтры из первого pjax.
$("#pjaxFilter").on("pjax:end", function() {
$.pjax.reload({container:"#pjaxContainer"});
});
У вас два pjax, когда первый срабатывает, второй отправляется. Но вот отправляется куда и с какими данными... это надо смотреть в debug панели браузера и в соотвествии с той картиной вносить изменения в код. Возможно при отправки второго pjax не отправляются фильтры из первого pjax.
Re: GridView зависимый от select
Попробуйте обернуть это всё в один pjax.
Re: GridView зависимый от select
Код: Выделить всё
'data' => ArrayHelper::map(Customers::find()->all(), 'name', 'name'),
Код: Выделить всё
'data' => Customers::find()->select(['name', 'id'])->indexBy('id')->column(),
Re: GridView зависимый от select
Код: Выделить всё
<?php Pjax::begin([
'formSelector' => '#search'
]); ?>
<?php $form = ActiveForm::begin([
'id' => 'search',
'method' => 'get',
'action' => ['index', 'sort' => Yii::$app->request->get('sort')],
]) ?>
<?= $form->field($searchModel, 'dateRange', ['options' => ['class' => 'additionalFilter']]) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterSelector' => '.additionalFilter input',
// ...
]) ?>
<?php ActiveForm::end() ?>
<?php Pjax::end() ?>
Re: GridView зависимый от select
Привет,
в общем получилось сделать, ниже покажу код... Огромное спасибо за помощь!!!
yiijeka, можете еще подсказать как сделать обновление по выбору значения, без нажатия на submit. Пробовал обернуть в единый pjax, но все тоже самое.
_search
index
ordersSearch
orders
в общем получилось сделать, ниже покажу код... Огромное спасибо за помощь!!!
yiijeka, можете еще подсказать как сделать обновление по выбору значения, без нажатия на submit. Пробовал обернуть в единый pjax, но все тоже самое.
_search
Код: Выделить всё
<?php
$js = <<<JS
$("#pjaxFilter").on("pjax:end", function() {
$.pjax.reload({container:"#pjaxContainer"}); //Reload GridView
});
JS;
$this->registerJs($js, yii\web\View::POS_READY);
?>
<div class="orders-search">
<?php
Pjax::begin([
'id'=>'pjaxFilter',
]);
?>
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'options' => [
'data-pjax' => true,
],
]); ?>
<?= $form->field($model, 'customers')->widget(Select2::class, [
'data' => \app\models\Orders::getCustomersNames(),
'options'=>[
'multiple'=>true,
],
]) ?>
<div class="form-group">
<?= Html::submitButton('Искать', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Сбросить', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php
Pjax::end();
?>
</div>
Код: Выделить всё
<div class="orders-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class="filter-panel">
<?= $this->render('_search', ['model' => $searchModel]) ?>
</div>
<?php \yii\widgets\Pjax::begin([
'id'=>'pjaxContainer',
]); ?>
<?php
try {
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns'=>[
[
'attribute'=>'id',
],
[
'attribute' => 'products_id',
'label' => 'Games',
'value' => 'products.name',
],
[
'attribute' => 'products_id',
'label' => 'Description',
'value' => 'products.description',
],
'quantity',
],
]);
} catch (Exception $e) {
throw new RuntimeException($e->getMessage());
}
?>
<?php \yii\widgets\Pjax::end() ?>
</div>
Код: Выделить всё
class OrdersSearch extends Orders
{
/**
* @inheritdoc
*/
public $customers;
public function rules()
{
return [
[['id', 'quantity', 'products_id', 'customers_id'], 'integer'],
[['customers'], 'each', 'rule' => ['string','max' => 100]],
];
}
/**
* @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 = Orders::find();
$query ->joinWith('customers');
// 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([
'id' => $this->id,
'quantity' => $this->quantity,
'products_id' => $this->products_id,
'customers_id' => $this->customers_id,
]);
if ($this->customers !== null) {
$query->andFilterWhere(['in', 'name', $this->customers]);
}
return $dataProvider;
}
}
Код: Выделить всё
public static function getCustomersNames()
{
return Customers::find()->select(['name', 'id'])->indexBy('name')->column();
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProducts()
{
return $this->hasOne(Products::class, ['id' => 'products_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCustomers()
{
return $this->hasOne(Customers::class, ['id' => 'customers_id']);
}
Re: GridView зависимый от select
появилась ошибка при использовании обычных фильтров
Код: Выделить всё
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous
The SQL being executed was: SELECT COUNT(*) FROM `orders` LEFT JOIN `customers` ON `orders`.`customers_id` = `customers`.`id` WHERE (`id`='2') AND (`name` IN ('Alex', 'Micha', 'Андрей'))
Re: GridView зависимый от select
насчет ошибки:
-------------------------
Код: Выделить всё
$query = Orders::find()->alias('orders');
$query ->joinWith('customers customers');
...
$query->andFilterWhere([
'orders.id' => $this->id,
'orders.quantity' => $this->quantity,
'orders.products_id' => $this->products_id,
'orders.customers_id' => $this->customers_id,
]);
if ($this->customers !== null) {
$query->andFilterWhere(['in', 'customers.name', $this->customers]);
}
посмотрите на мой пример выше с акцентом на:
Код: Выделить всё
'filterSelector' => '.additionalFilter input, .additionalFilter select',
Re: GridView зависимый от select
Спасибо, буду вечером дома, попробую...
еще вопрос короткий, почему он мне рисует урл с дополнительным массивом?
index?OrdersSearch[Customers]=&OrdersSearch[Customers][]=Alex&OrdersSearch[Customers][]=Vasya&
еще вопрос короткий, почему он мне рисует урл с дополнительным массивом?
index?OrdersSearch[Customers]=&OrdersSearch[Customers][]=Alex&OrdersSearch[Customers][]=Vasya&
Re: GridView зависимый от select
multiple потому что
Re: GridView зависимый от select
Попробуйте так, 'customers[]'
Код: Выделить всё
<?= $form->field($model, 'customers[]')->widget(Select2::class, [
'data' => \app\models\Orders::getCustomersNames(),
'options'=>[
'multiple'=>true,
],
]) ?>
Re: GridView зависимый от select
Всем спасибо за помощь!