最新消息: 新版网站上线了!!!

yii2 Ajax 实现下拉Dropdown 和复选框Checkbox

效果如下

代码的实现控制器

<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\Employee;
use app\models\EmployeeHasHobby;
use app\models\Hobby;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;

class TestController extends Controller
{
    public function actionIndex()
    {
        $model = new \yii\base\DynamicModel([
            'employees', 'hobbies'
        ]);
        $employees = Employee::find()->all();
        $employees = ArrayHelper::map($employees, 'id', 'name');
        $hobbies = Hobby::find()->all();
        $hobbies = ArrayHelper::map($hobbies, 'id', 'name');
        return $this->render('index', [
            'model' => $model,
            'employees' => $employees,
            'hobbies' => $hobbies,
        ]);
    }

    public function actionGetHobbies($employee_id)
    {
        $datas = EmployeeHasHobby::find()->where(['employee_id'=>$employee_id])->all();
        $data = ArrayHelper::map($datas, 'hobby_id', 'hobby_id');
        echo Json::encode($data);
    }

    public function actionSetHobby($employee_id, $hobby_id)
    {
        $model = new EmployeeHasHobby([
            'employee_id'=>$employee_id,
            'hobby_id'=>$hobby_id,
        ]);
        $model->save();
    }

    public function actionUnsetHobby($employee_id, $hobby_id)
    {
        $model = EmployeeHasHobby::find()->where([
            'employee_id'=>$employee_id,
            'hobby_id'=>$hobby_id,
        ])->one();
        $model->delete();
    }

}

视图 app\views\test\index

<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\ActiveForm;
?>
<h1>Employee Has Hobby</h1>
<div class="col-md-3">
<?php $form = ActiveForm::begin(); ?>
<?php
echo $form->field($model, 'employees')->dropDownList($employees,['prompt'=>'Select employee']);
echo $form->field($model, 'hobbies')->checkboxList($hobbies);
?>
</div>
<?php ActiveForm::end(); ?>

<?php
$script = <<< JS

var current_employee_id = 0;
$("select").change(function() {
    current_employee_id = $(this).val()

    $('input[type=checkbox]').each(function () {
        $(this).prop('checked', false);
    });

    $.ajax({
        url: 'index.php?r=test/get-hobbies&employee_id='+current_employee_id,
        dataType: "json",
        success: function(data) {
          $.each(data, function(key, value){
            $('input[type=checkbox]').each(function () {
                if($(this).val()==key){
                  $(this).prop('checked', true);
                }
            });
          });
        }
    })
});

$("input[type=checkbox]").change(function() {
    if(this.checked) {
      $.post("index.php?r=test/set-hobby&employee_id="+current_employee_id+"&hobby_id="+$(this).val())
    }
    else{
      $.post("index.php?r=test/unset-hobby&employee_id="+current_employee_id+"&hobby_id="+$(this).val())
    }
});

JS;
$this->registerJs($script);

转载请注明:谷谷点程序 » yii2 Ajax 实现下拉Dropdown 和复选框Checkbox