Saltern
Saltern

Reputation: 1383

yii2: how to add if for checked or unchecked checkbox in _form.php

i want add if or else for checkbox in _formCreate.php

this is my checkbox:

   <div class="col-lg-6 height3">
         <p class="col-lg-8">سرگرمی</p>
<?= $form->field($model, 'c2')->input('checkbox', ['id' => '', 'value'=> '2', 'class' => 'col-lg-4 chb'])->label('') ?>

    </div>
            <div class="col-lg-6 height3">
                <p class="col-lg-8">خدماتی</p>
<?= $form->field($model, 'c3')->input('checkbox', ['id' => '', 'value' => '3', 'class' => 'col-lg-4 chb'])->label('') ?>

            </div>

i have this variable in this form $checkBox with this data:

array(3) { [0]=> array(1) { ["project_type_id"]=> string(1) "2" } [1]=> array(1) { ["project_type_id"]=> string(1) "3" } [2]=> array(1) { ["project_type_id"]=> string(1) "5" } } 

how to add if for <?= $form->field... and check that with my array and checked the checkbox!

Upvotes: 0

Views: 1261

Answers (2)

Yerke
Yerke

Reputation: 2215

If I get you right, then you can write logic for checkbox (model's attribute) in the beginning of the View. For example, if your model's name is 'Yii', then checkbox should be automatically checked, in code I would write it this way:

<?php

/* @var $this yii\web\View */
/* @var $model SomeModel */

if($model->name == 'Yii') $model->c2 = true;

?>

Then in Form:

<div class="col-lg-6 height3">
  <p class="col-lg-8">سرگرمی</p>
    <?= $form->field($model, 'c2')->checkbox()->label('') ?>
</div>
<div class="col-lg-6 height3">
  <p class="col-lg-8">خدماتی</p>
    <?= $form->field($model, 'c3')->checkbox()->label('') ?>
</div>

Upvotes: 1

Vitaly
Vitaly

Reputation: 1281

If model attribute set and model attribute value == checkbox value, then checkbox will checked

<?php 
if(in_array('2', ArrayHelper::map($checkBox, 'project_type_id', 'project_type_id'))) $model->c2 = '2';
if(in_array('3', ArrayHelper::map($checkBox, 'project_type_id', 'project_type_id'))) $model->c3 = '3';
?>

<?= $form->field($model, 'c2')->input('checkbox', [
    'id' => '', 
    'value' => '2', 
    'class' => 'col-lg-4 chb'
])->label('') ?>

<?= $form->field($model, 'c3')->input('checkbox', [
    'id' => '', 
    'value' => '3', 
    'class' => 'col-lg-4 chb'
])->label('') ?>

Upvotes: 0

Related Questions