Answer the question
In order to leave comments, you need to log in
Where can I take out the repeating code from the search model?
The search model in the admin panel has filtering by status in the database for the subsequent display of filtered data in the template. Here is an example model GameSearch
:
public function search(array $params)
{
/** @var \yii\db\ActiveQuery $query */
$query = Game::find();
// Фильтры по статусу в базе
if ($params && $params['GameSearch']) {
if (!isset($params['GameSearch']['all'])) {
/** @var string|array $value */
foreach ($params['GameSearch'] as $key => $value) {
if (!empty($value)) {
$query->where([$key => $params['GameSearch'][$key]]);
break;
}
}
}
unset($params['GameSearch']);
}
// остальной код
Answer the question
In order to leave comments, you need to log in
Create a trait add the `fillGameSearch` method to it and include it where necessary:
trait GameSearchStatus
{
public function fillGameSearch(ActiveQuery $query, array $params)
{
$gameSearch = $params['GameSearch'] ?? null;
if (is_array($gameSearch) && !isset($gameSearch['all'])) {
foreach ($gameSearch as $key => $value) {
if (!empty($value)) {
$query->where([
$key => $value,
]);
break;
}
}
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question