简体   繁体   中英

Checked items in Yii2 checkboxList

I've got a dummy problem with checkboxList in ActiveForm.

So I've got two models (I cut off irrelevant code):

Object model:

class Object extends ActiveRecord
{
    public $oFacilities = array();

    public static function tableName()
    {
        return 'objects';
    }

    public function getObjectFacilities(){
        return $this->hasMany(Facility::className(),['id' => 'facilityId'])->viaTable('objectsfacilities', ['objectId' => 'id']);
    }
}

Facility model:

class Facility extends ActiveRecord
{
    public static function tableName()
    {
        return 'facilities';
    }

    public static function forWidget(){
        $facilities =static::find()->select(['id','name'])->where(['type' => static::TYPE_OBJECT])
                                   ->orderBy('name')
                                   ->asArray()
                                   ->all();

        return ArrayHelper::map($facilities, 'id', 'name');
    }

    public function getObjectsWithFacility(){
        return $this->hasMany(Object::className(), ['id' => 'objectId'])->viaTable('objectsfacilities', ['facilityId' => 'id']);
    }
}

And I've got two actions in my ObjectController:

class ObjectController extends Controller
{
    public function actionCreate(){
        $model = new Object();
        if($model->load(Yii::$app->request->post()) && $model->validate()){
            $model->save();
            foreach($model->oFacilities as $id){
                $facility = Facility::findOne($id);
                $model->link('objectFacilities', $facility);
            }
            Yii::$app->session->setFlash('alert', 'object-created');
            return $this->redirect('index');
        }
        return $this->render('create', ['model' => $model]);
    }

    public function actionUpdate($id){
    /* This action is complete - for now I just want to render a form */
        if($model = Object::find()->where(['id' => $id])->with(['objectFacilities'])->one()){
            foreach($model->objectFacilities as $facility) array_push($model->oFacilities, $facility->id);

            return $this->render('update', ['model' => $model]);
        }
    }
}

Both action use partial view called _form.php

<?php $form = ActiveForm::begin([
    'id' => 'object-form',
    'options' => ['class' => 'form-horizontal'],
    'fieldConfig' => [
        'template' => "{label}\n<div class=\"col-lg-9\">{input}</div>\n<div class=\"col-lg-9 col-lg-offset-3\">{error}</div>",
        'labelOptions' => ['class' => 'col-lg-3 control-label'],
    ],
]); ?>

    <?= $form->field($model, 'oFacilities')->checkboxList(Facility::forWidget(),[
    'item' => function($index, $label, $name, $checked, $value) {
        return "<label class='checkbox col-md-4' style='font-weight: normal;'><input type='checkbox' {$checked} name='{$name}' value='{$value}'>{$label}</label>";
    }
]) ?>

    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton($model->isNewRecord ? 'Create object' : 'Save changes', ['class' => 'btn btn-primary', 'name' => 'object-button']) ?>
        </div>
    </div>

<?php ActiveForm::end(); ?>

Create action works fine (both render and save), but I've got an issue with rendering checkbox list based on junktion table - none of checkobxes is checked. Could you tell what I'm doing wrong?

Kind regards, Kamil

UPDATE

I located the problem - when I change the code which render chckboxList like this:

<?= $form->field($model, 'oFacilities')->checkboxList(Facility::forWidget()) ?>

chosen earlier checkboxes are checked. But then my checkboxList isn't divded to three columns.

The {checked} part of your item functions outputs a 1 or a 0 in the input element.

Change the value to an actual 'checked' string to fix your problem.

<?=
    $form->field($model, 'oFacilities')->checkboxList(Facility::forWidget(),[
        'item' => function($index, $label, $name, $checked, $value) {
            $checked = $checked ? 'checked' : '';
            return "<label class='checkbox col-md-4' style='font-weight: normal;'><input type='checkbox' {$checked} name='{$name}' value='{$value}'>{$label}</label>";
        }
    ])
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM