search.php 1.89 KB
Newer Older
Qiang Xue committed
1
<?php
Qiang Xue committed
2 3 4

use yii\helpers\StringHelper;

Qiang Xue committed
5
/**
Qiang Xue committed
6 7 8 9
 * This is the template for generating a CRUD controller class file.
 *
 * @var yii\base\View $this
 * @var yii\gii\generators\crud\Generator $generator
Qiang Xue committed
10
 */
Qiang Xue committed
11 12 13 14 15 16 17 18 19 20 21

$modelClass = StringHelper::basename($generator->modelClass);
$searchModelClass = StringHelper::basename($generator->searchModelClass);
$rules = $generator->generateSearchRules();
$labels = $generator->generateSearchLabels();
$searchAttributes = $generator->getSearchAttributes();
$searchConditions = $generator->generateSearchConditions();

echo "<?php\n";
?>

22
namespace <?=StringHelper::dirname(ltrim($generator->searchModelClass, '\\')); ?>;
Qiang Xue committed
23 24 25

use yii\base\Model;
use yii\data\ActiveDataProvider;
26
use <?=ltrim($generator->modelClass, '\\'); ?>;
Qiang Xue committed
27 28

/**
29
 * <?=$searchModelClass; ?> represents the model behind the search form about <?=$modelClass; ?>.
Qiang Xue committed
30
 */
31
class <?=$searchModelClass; ?> extends Model
Qiang Xue committed
32
{
33
	public $<?=implode(";\n\tpublic $", $searchAttributes); ?>;
Qiang Xue committed
34 35 36

	public function rules()
	{
Alexander Makarov committed
37
		return [
38
			<?=implode(",\n\t\t\t", $rules); ?>,
Alexander Makarov committed
39
		];
Qiang Xue committed
40 41 42 43 44 45 46
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
Alexander Makarov committed
47
		return [
Qiang Xue committed
48
<?php foreach ($labels as $name => $label): ?>
49
			<?="'$name' => '" . addslashes($label) . "',\n"; ?>
Qiang Xue committed
50
<?php endforeach; ?>
Alexander Makarov committed
51
		];
Qiang Xue committed
52 53 54 55
	}

	public function search($params)
	{
56
		$query = <?=$modelClass; ?>::find();
Alexander Makarov committed
57
		$dataProvider = new ActiveDataProvider([
Qiang Xue committed
58
			'query' => $query,
Alexander Makarov committed
59
		]);
Qiang Xue committed
60 61 62 63 64

		if (!($this->load($params) && $this->validate())) {
			return $dataProvider;
		}

65
		<?=implode("\n\t\t", $searchConditions); ?>
Qiang Xue committed
66 67 68 69 70 71 72 73 74 75 76

		return $dataProvider;
	}

	protected function addCondition($query, $attribute, $partialMatch = false)
	{
		$value = $this->$attribute;
		if (trim($value) === '') {
			return;
		}
		if ($partialMatch) {
Alexander Makarov committed
77 78
			$value = '%' . strtr($value, ['%'=>'\%', '_'=>'\_', '\\'=>'\\\\']) . '%';
			$query->andWhere(['like', $attribute, $value]);
Qiang Xue committed
79
		} else {
Alexander Makarov committed
80
			$query->andWhere([$attribute => $value]);
Qiang Xue committed
81 82 83
		}
	}
}