Hi.
I’m stuck with next problem: I have some array:
$resultData = [
'4' => ['id' => 4, 'key' => 'dictionary_email', 'value' => 'Email', 'description' => '//email comment'],
'5' => ['id' => 5, 'key' => 'dictionary_username', 'value' => 'Name', 'description' => '//name comment'],
'6' => ['id' => 6, 'key' => 'dictionary_new-password', 'value' => 'New password', 'description' => '//new password comment'],
'7' => ['id' => 7, 'key' => 'dictionary_current-password', 'value' => 'Current password', 'description' => '//current password'],
]
I want to create GridView with filters from this data. My controller:
$filtersForm = new FiltersForm;
if (isset($_GET['FiltersForm'])) {
$filtersForm->filters = $_GET['FiltersForm'];
}
$resultData = $filtersForm->filter($resultData);
return $this->render('about', [
'filtersForm' => $filtersForm,
'resultData' => $resultData,
]);
FiltersModel:
namespace common\models;
use yii\base\Model;
class FiltersForm extends Model
{
public $filters = array();
/**
* Override magic getter for filters
*/
public function __get($name)
{
if(!array_key_exists($name, $this->filters))
$this->filters[$name] = null;
return $this->filters[$name];
}
/**
* Filter input array by key value pairs
* @param array $data rawData
* @return array filtered data array
*/
public function filter(array $data)
{
foreach($data AS $rowIndex => $row) {
foreach($this->filters AS $key => $value) {
// unset if filter is set, but doesn't match
if(array_key_exists($key, $row) AND !empty($value)) {
if(stripos($row[$key], $value) === false)
unset($data[$rowIndex]);
}
}
}
return $data;
}
}
my view:
$dataProvider = new ArrayDataProvider([
'allModels' => $resultData,
'sort' => [
'attributes' => ['id', 'key', 'value', 'description'],
],
'pagination' => [
'pageSize' => 10,
],
]);
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $filtersForm,
'layout' => "{items}\n{pager}",
'columns' => [
'id',
'key',
'value',
'description',
],
]);
DataGrid is shown, but there is no filters.