forked from kartik-v/yii2-widget-depdrop
/
DepDropAction.php
137 lines (126 loc) · 3.24 KB
/
DepDropAction.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
namespace kartik\depdrop;
use Yii;
use yii\base\Action;
use yii\base\InvalidConfigException;
use yii\helpers\Json;
use yii\web\Response;
/**
* Class DepDropAction
* @package kartik\depdrop
*
*
*
* * A typical usage is like the following:
*
* ```php
*
* //inside controller
*
* public function actions()
* {
* return \yii\helpers\ArrayHelper::merge(parent::actions(), [
* 'subcategory' => [
* 'class' => \kartik\depdrop\DepDropAction::className(),
* 'outputFunction' => function ($selectedId, $params) {
* return [
* [
* 'id'=>1,
* 'name'=>'Car',
* ],
* [
* 'id'=>2,
* 'name'=>'bike',
* ],
* ];
*
* // return self::getSubCategory($selectedId);
*
*
*
* //with group
* return [
* 'group1'=>[
* ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
* ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
* ],
* 'group2'=>[
* ['id'=>'<sub-cat-id-3>', 'name'=>'<sub-cat-name3>'],
* ['id'=>'<sub-cat-id-4>', 'name'=>'<sub-cat-name4>']
* ]
* ];
* }
* ]
* ]);
* }
* ```
*
*
*/
class DepDropAction extends Action
{
/**
*
*/
const MAIN_PARAM = 'depdrop_parents';
/**
*
*/
const OTHER_PARAMS = 'depdrop_params';
/**
* @var
*/
public $outputFunction;
/**
* @var
*/
public $selectedFunction;
/**
* @throws InvalidConfigException
*/
public function init()
{
parent::init();
if (!is_callable($this->outputFunction)) {
throw new InvalidConfigException('outputFunction must be callable');
}
}
/**
* Runs the action.
*/
public function run()
{
Yii::$app->response->format = Response::FORMAT_JSON;
if ($selected = Yii::$app->getRequest()->post(self::MAIN_PARAM)) {
if ($selected) {
$selectedId = $selected[0];
$params = Yii::$app->getRequest()->post(self::OTHER_PARAMS, []);
return ['output' => $this->getOutput($selectedId,$params), 'selected' => $this->getSelected($selectedId,$params)];
}
}
return Json::encode(['output' => '', 'selected' => '']);
}
/**
* @param $id
* @param $params
* @return mixed
*/
private function getOutput($id, $params)
{
$outputFunction = $this->outputFunction;
return $outputFunction($id,$params);
}
/**
* @param $id
* @param $params
* @return string
*/
private function getSelected($id, $params)
{
$selectedFunction = $this->selectedFunction;
if (is_callable($selectedFunction)) {
return $selectedFunction($id,$params);
}
return '';
}
}