S
S
Sergey Erin2021-07-30 18:36:04
Yii
Sergey Erin, 2021-07-30 18:36:04

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']);
    }

// остальной код

This block is present in many search models.
Can you tell me where I can put this code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-07-30
@artalexs

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 question

Ask a Question

731 491 924 answers to any question