Last active
September 28, 2023 13:40
-
-
Save tguruslan/3cc60f4f1f7d346fad03067ac353619a to your computer and use it in GitHub Desktop.
universal select2 callback function for yii2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace @app\your\namespace\controllers; | |
use Yii; | |
use yii\web\Controller; | |
use yii\filters\VerbFilter; | |
use yii\web\Response; | |
use yii\helpers\Json; | |
class FunctionsController extends Controller | |
{ | |
public function behaviors() | |
{ | |
return [ | |
'verbs' => [ | |
'class' => VerbFilter::className(), | |
'actions' => [ | |
'select' => ['post'], | |
], | |
], | |
]; | |
} | |
public static function actionSelect() | |
{ | |
$request = Yii::$app->request; | |
Yii::$app->response->format = Response::FORMAT_JSON; | |
$req = Json::decode(Json::encode($request->post()),false); | |
$id=$req->columns->id; | |
$text=$req->columns->text; | |
$model='@app\path\to\models\\'.$req->model; | |
$query = $model::find(); | |
$all = filter_var($req->all,FILTER_VALIDATE_BOOLEAN); | |
if ($all){$query->where(['<>',$text,'']);} // needed to bypass the override of the find function | |
$query->select([$id,$text]); | |
if ($req->q){$query->andFilterWhere(['like',$text,$req->q]);} | |
if (count((array)$req->filters)){ | |
foreach ((array)$req->filters as $key=>$val){ | |
$query->andFilterWhere([$key=>$val]); | |
} | |
} | |
$query->orderBy([$text => SORT_ASC]); | |
$resp=[]; | |
foreach($query->all() as $entry){ | |
$resp[] = ['id'=>$entry->$id,'text'=>$entry->$text]; | |
} | |
return $resp; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?= $form->field($model, 'teacher_tmp')->widget(Select2::classname(), [ | |
'options' => ['placeholder' => 'Some text...'], | |
'pluginOptions' => [ | |
'ajax' => [ | |
'url' => '/your/url/functions/select', | |
'dataType' => 'json', | |
'method'=>'post', | |
'data' => new JsExpression(' function(params) { return { | |
q:params.term, | |
model:"Modelname", | |
columns:{id:"id",text:"titleColumn"}, | |
all:$("#all").prop("checked"), | |
filters:{ | |
123:$("#123").val(), | |
456:$("#456").val(), | |
} | |
};}'), | |
'processResults' => new JsExpression('function (data) {return {results: data};}'), | |
], | |
], | |
'addon' => [ | |
'prepend' => [ | |
'content' => Html::checkbox('all', false, ['id'=>'all','title' => 'show all']) | |
], | |
] | |
]) ?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment