Search code examples
javascriptphpyii2yii-extensions

Saving kartik select2 widget data with a model


Am using kartik select2 widget and i would like it to save data to the database by passing it to the controller.

I have tried this
1. the select2 widget

   <?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
     <?php
        echo $form->field($model, 'unitid')->widget(Select2::classname(), [
        'data' => ArrayHelper::map($model2,'unitid','unitname'),
        'language' => 'de',
        'options' => ['multiple' => true, 'placeholder' => 'Select a Unit '],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
  ?>
  <?php ActiveForm::end(); ?>
  1. The javascript code to save data on form submit which is on the view:

    <?php 
      $script = <<< JS
    
     $('form#{$model->formName()}').on('beforeSubmit', function(e) 
    {
    var \$form = $(this);
     console.log(\$form.serialize());
    $.post(
    \$form.attr("action"), 
    \$form.serialize()
     )
    .done(function(result) {
     console.log("Succesifully saved" + result);
      }).fail(function(err) 
       {
        console.log("failed to save" + err);
       });
      return false;
      });
      JS;
     $this->registerJs($script);
     ?>
    

This generates this output on the console(for the serialized form output

_csrf=TGMzaDRINnEHFgM5RjIPICc2bBoZAWZAOBIGAnAeVSF4GUQteThUFw%
3D%3D&Unitslocation%5Bunitid%5D=&Unitslocation%5Bunitid%5D%5B%5D=9

the output is always passed as a string that is after trying

echo json_encode($model->unitid);

On the controller it returns a string instead of an integer that is

["5"]

How can i convert ($model->unitid) to integer for the post params


Solution

  • Just use

    $model->unitid = (int) $model->unitid;
    

    Thats all.