cant get value from dynamic checkboxlist

hello guys,

i have some problem when using checkboxlist. this checkboxlist was dependent with dropdownlist.

checkboxlist generate when i choose one value in dropdownlist.

then checkboxlist will generate by ID.

the problem is when i save the form, i cant get the value from the that generated checkboxlist.

this the code from view and my controller




- region view 

   <?= $form->field($model, 'cp_countrytarget')->dropDownList(

        ArrayHelper::map(\app\models\Countries::find()->all(), 'countries_id', 'name'),

        [

          'prompt' => 'Select Country',

          'class' => 'dependent-input form-control',

          'onchange' => '$.get("index.php?r=tbcampaign/countries&id='.'"+$(this).val(), function(data) {

            $("#tbcampaign-cp_statetarget").html(data);

          });'

        ]); ?>


         <?=

            $form->field($model, 'cp_statetarget[]')->checkboxlist([],

            [

             //'onclick' => "$(this).val($('input:checkbox:checked').val()); ",

             //'onclick' => "alert($('input[type=checkbox]').val()); ",

            ]);

          ?>


-region controller


  public function actionCountries($id)

  {

    $states = States::find()->where(['country_id' => $id])->all();


    foreach ($states as $state)

    {

      return Html::checkboxList('Tbcampaign[cp_citiestarget][]',[],ArrayHelper::map($states, 'name', 'name'), []);

    }




but if i generate checkboxlist like this i can save the form normally to database, but thats not dynamically.




- view

<div class="container" style="overflow-y:scroll; width:auto; height:250px;">

        <?php $datacities = ArrayHelper::map(\app\models\States::find()->all(), 'name', 'name');

        ?>

        <?= $form->field($model, [cp_citiestarget][]')->checkboxList$datacities [

              'separator' => '',

              'itemOptions' => [

              'class' => 'cities'

             ]

             ]);

            ?>

            <?=   $this->registerJs("jQuery('#checkAll').change(function(){jQuery('.cities').prop('disabled',this.checked?'checked':'');


            })");?>

        </div>



whats wrong with that my dynamically checkboxlist?

*sorry for my bad english

thankyou :)

Hi shotokhaw, welcome to the forum.

Can you show us your model for the form and the controller code that saves the user input?

I mean, I’d like to see how you handles the array values of the checkbox list.

BTW, please take some time to look at the following wiki:

How to create/update a model with its related items using Listbox or CheckboxList

The article explains how to create a model that handles the array values returned by checkboxlist.

hai softark, sorry for late reply i was left my laptop in office.

okay this is my model from the form


<?php

namespace app\models;


use Yii;


class Tbcampaign extends \yii\db\ActiveRecord

{

    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'tbcampaign';

    }


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['client_name','client_id', 'cp_name','cp_adult'], 'required'],

            [['client_name','cp_name','cp_tag','cp_adult'], 'string', 'max' => 25],

            [['cp_startdate','cp_enddate','client_id'], 'integer'],

            [['cp_pricingoffer'], 'string', 'max' => 25],

            [['gambar','cp_devicetarget','cp_ostarget','cp_browser','cp_language','cp_timetarget','cp_iptarget'], 'string', 'max' => 50],

            [['cp_activate'], 'string', 'max' => 1],

            [['cp_pricingmodel'], 'string', 'max' => 3],

            [['cp_budget'],'integer'],

            [['cp_countrytarget','cp_statetarget'],'safe'],

        ];

    }


    public function attributeLabels()

    {

        return [

            'client_name' => 'Client Name',

            'client_id' => 'Client ID',

            'cp_name' => 'Name',

            'cp_tag' => 'Tag',

            'cp_startdate' => 'Campaign Start Date',

            'cp_enddate' => 'Campaign End Date',

            'cp_activate' => 'Activate Campaign After Create',

            'cp_budget' => 'Total Budget for This Campaign',

            'cp_adult' => 'Campaign Adult Target',

            'cp_countrytarget' => 'Country Target',

            'cp_statetarget' => 'State Target',

        ];

    }

}



and then this is my controller code for save the data


<?php

namespace frontend\controllers;


use Yii;

use app\models\Tbcampaign;

use app\models\Countries;

use app\models\Cities;

use app\models\States;

use yii\web\Controller;

use yii\helpers\Json;

use yii\helpers\ArrayHelper;

use yii\helpers\Html;


/**

 * manual CRUD

 **/

class TbcampaignController extends Controller

{

    /**

     * Create

     */




    public function actionCreate()

    {

        $model = new tbcampaign();


        if ($model->load(Yii::$app->request->post())) {


            $id = $model->cp_countrytarget;

            echo $id ."<br/>";


            $getCountry = ArrayHelper::map(Countries::find()->where(['countries_id'=>$id])->all(),'name','name');


            foreach ($getCountry as $items) {


              $model->cp_countrytarget = $items;

            }


            if($model->save()){

              echo '1'; //success

            }else {

              echo '0'; //failed save

            }


        } else {

          // $model->cp_countrytarget = explode(',',$model->cp_countrytarget);

          // $model->cp_statetarget = explode(',',$model->cp_statetarget);


          $this->layout="adminlte";

          return $this->render('create', [

            'model' => $model,


          ]);

        }

    }




  public function actionCountries($id)

  {

    $states = States::find()->where(['country_id' => $id])->all();


    foreach ($states as $state)

    {

   

      return Html::checkboxList('Tbcampaign[cp_citiestarget][]',[],ArrayHelper::map($states, 'name', 'name'), []);

    

    }


  }

 }

 ?>



thankyou :)

How do you define ‘cp_statetarget’ in your database table? Is it a text?

If it’s a text(string), then you have to convert it to and from an array of values for the checkboxlist.

i must be use the implode method like this? $model->cp_statetarget = implode(",", $model->cp_statetarget);

my problem is i cant get the value from this dynamic checkboxlist


<?=

            $form->field($model, 'cp_statetarget[]')->checkboxlist([],

            [


            ]); ?>



if i push the states from controller.


but if i use this condition not dynamic checkboxlist and at the controller i add $model->cp_statetarget = implode(",", $model->cp_statetarget);

i can save succesfully.


  

<div class="col-lg-2">

        <?php $datastates = ArrayHelper::map(\app\models\States::find()->where(['country_id'=>102])->all(), 'name', 'name');

        ?>

        <div>

        <label class="control-label">States</label>

        </div>

        <div>

        <label><input type="checkbox" id="checkAll">Check All</label>

        </div>

        <div class="container" style="overflow-y:scroll; width:auto; height:250px;">

        <?= $form->field($model, 'cp_statetarget[]')->checkboxList($datastates, [

            'separator' => '',

            'itemOptions' => [

            'class' => 'states'

           ]

           ])->label('');

          ?>

          <?=   $this->registerJs("jQuery('#checkAll').change(function(){jQuery('.states').prop('disabled',this.checked?'checked':'');


          })");?>


      </div>



I think that you are adding an unnecessary ‘[]’ to ‘cp_statetarget’ when naming the input.

view




    <?php /* echo $form->field($model, 'cp_statetarget[]')->checkboxlist([]); */ ?>

    <?php echo $form->field($model, 'cp_statetarget')->checkboxlist([]); ?>



controller




    public function actionCountries($id)

    {

        $states = States::find()->where(['country_id' => $id])->all();

        return Html::checkboxList('Tbcampaign[cp_citiestarget]',[], ArrayHelper::map($states, 'name', 'name'), []);

    }



i put some code for makesure that cp_statetarget can get value.

but still same result if i remove “[]” or without remove “[]” :unsure:


  

if ($model->load(Yii::$app->request->post())) {


            $id = $model->cp_countrytarget;

            $model->cp_countrytarget = null;


//----region display state when save. but still didnt get value 

            $displayState = $model->cp_statetarget;


            echo $displayState;

//-----


            $getCountry = ArrayHelper::map(Countries::find()->where(['countries_id'=>$id])->all(),'name','name');


            foreach ($getCountry as $items) {

              $model->cp_countrytarget = $items;

            }


            if($model->cp_statetarget != null){

              $model->cp_statetarget = implode(",", $model->cp_statetarget);

            }else {

              $model->cp_statetarget = 'All';

            }


            if($model->cp_timetarget != null){

              $model->cp_timetarget = implode(",", $model->cp_timetarget);

            }else {

              $model->cp_timetarget = 'All';

            }


            if($model->save()){

              echo '1';

            }else {

              echo '0';

            }


        }



Would you please write a simplified minimized version of your code that illustrates your issue? The model, the controller and the view altogether. It’s very hard for me to tell what’s wrong with your code.

:D sorry sorry.

okay let my try.

i want to display dynamic checkbox (named cp_statetarget) depends from this dropdownlist (named cp_countrytarget).

  • the view




<?= $form->field($model, 'cp_countrytarget')->dropDownList(

        ArrayHelper::map(\app\models\Countries::find()->all(), 'countries_id', 'name'),

        [

          'prompt' => 'Select Country',

          'class' => 'dependent-input form-control',

          'onchange' => '$.get("index.php?r=tbcampaign/countries&id='.'"+$(this).val(), function(data) {

            $("#tbcampaign-cp_statetarget").html(data);

          });'

        ]); ?>


  $form->field($model, 'cp_statetarget')->checkboxlist([],

    [


    ]); ?>



  • the controller






public function actionCreate()

{

    $model = new tbcampaign();


      if ($model->load(Yii::$app->request->post())) {


          //region state

          if($model->cp_statetarget != null){

            $model->cp_statetarget = implode(",", $model->cp_statetarget);

          }else {

            $model->cp_statetarget = 'All';

          }

          //end region state

          if($model->save()){

          echo '1';

          }else {

            echo '0';

          }


      } else {


        $model->cp_statetarget = explode(',',$model->cp_statetarget);


        $this->layout="adminlte";

        return $this->render('create', [

          'model' => $model,


        ]);

      }

}




public function actionCountries($id)

  {

    $states = States::find()->where(['country_id' => $id])->all();


    foreach ($states as $state)

    {

      return Html::checkboxList('Tbcampaign[cp_citiestarget]',[],ArrayHelper::map($states, 'name', 'name'), []);

  }



-the models




public function rules()

    {

        return [

            [['cp_countrytarget','cp_statetarget','cp_timetarget'],'safe'],

        ];

    }


    public function attributeLabels()

    {

        return [

            'cp_statetarget' => 'State Targeting',

        ];

    }



my issue is why i cant get value from cp_statetarget if i use checkboxlist that depend on dropdownlist.

but if i use like this (i can get the value cp_statetarget successfully) :

-the view




  <?php $datastates = ArrayHelper::map(\app\models\States::find()->where(['country_id'=>102])->all(), 'name', 'name');

  ?>


    <?= $form->field($model, 'cp_statetarget[]')->checkboxList($datastates, [

      'separator' => '',

      'itemOptions' => [

        'class' => 'states'

      ]

      ])->label('');

      ?>

      <?=   $this->registerJs("jQuery('#checkAll').change(function(){jQuery('.states').prop('disabled',this.checked?'checked':'');


      })");?>



Is your dynamic checkboxlist generated as expected? I mean, does it change dynamically when you select the country?

yup thats working properly.

i was attached the screenshoot

:)

Do you enable the ajax validation of the form? If so, please try disabling it and see what will happen.

yes i was enable the ajax validation.

then i try to disabling like this




<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);

 // <php $form = ActiveForm::begin();['enableAjaxValidation'=>false],



still got nothing :-[

I’m sorry, but I have no idea now.

If I were you, I would use XDebug in my IDE and trace the execution of the program in order to see what’s happening.