Yii2: Ajax Dependent Dropdown with Dynamic Checkbox

hasil

Tutorial ini akan membahas tentang bagaimana membuat user interface untuk input data employee dengan hobbynya secara dinamis berbasis ajax. Intinya ketika user memilih employee maka checkbox hobby akan menyesuaikan..

Ada 3 tabel yang berkepentingan disini yaitu employee, hobbies dan employee_has_hobby, sebagai berikut:

tabel

Berikut ini langkah2nya:
1. Silahkan generate model dari ketiga tabel tsb menggunakan Gii tentunya
2. Buat controller baru misalnya yaitu TestController

<?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();
    }

}

3. Buat view baru misalnya yaitu 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);

Selesai

#Maaf lagi males mbikin penjelasan :)

 

Leave a Reply

Your email address will not be published. Required fields are marked *