title: How to save multiple values to database from Select2 Widget Yii2
body: <p>I am using the kartik - yii2-widget-select2 to allow the option to select multiple options while creating in form.</p>
  
  <p>I want to enter two or more rows to the database depending on the the number of options selected in the select2 widget.</p>
  
  <p>The select2 widget in the form is below.</p>
  
  <pre><code>&lt;?= $form-&gt;field($model, 'Assign_task_to')-&gt;widget(Select2::classname(), 
  //$data = ArrayHelper::map(Employee::find()-&gt;all(),'Employee_ID','employee_name'),
  [
  'data' =&gt; ArrayHelper::map(Employee::find()-&gt;all(),'Employee_ID','employee_name'),
  'language' =&gt; 'en',
  'options' =&gt; ['placeholder' =&gt; 'Select an employee ...', 'multiple' =&gt; true],
  'pluginOptions' =&gt; [
      'allowClear' =&gt; true
  ],
  ]); ?&gt;
  </code></pre>
  
  <p>The controller actionCreate is below.</p>
  
  <pre><code>public function actionCreate()
  {
  
      // set default values
      $empModel = new Tasksemp();
      $model = new Tasks();
      $model-&gt;priotiy_level = 'medium';
      $model-&gt;start_date = date('Y-m-d'); //to get default date
      if ($model-&gt;load(Yii::$app-&gt;request-&gt;post())) {
  
  
          //Check if field input is empty
  
          $model-&gt;file = UploadedFile::getInstance($model, 'upload_documents');
  
  
          if($model-&gt;file)
          {
              //get instance of uploaded file
              $fName = time();
              $model-&gt;file = UploadedFile::getInstance($model, 'upload_documents');
              $model-&gt;file-&gt;saveAs('uploads/'.$fName.'.'.$model-&gt;file-&gt;extension);
  
              $model-&gt;upload_documents = 'uploads/'.$fName.'.'.$model-&gt;file-&gt;extension;
          }
  
  
  
          $model-&gt;save();
  
          //to save in task_emp table
  
              $empModel-&gt;Task_ID = $model-&gt;Task_ID;   
              $empModel-&gt;Employee_ID = $model-&gt;Assign_task_to;  //&lt;---want to save multiple employee IDs with the same Task ID (multiple rows)
              $empModel-&gt;save(false);
              return $this-&gt;redirect(['view', 'id' =&gt; $model-&gt;Task_ID]);      
  
      } else {
          return $this-&gt;render('create', [
              'model' =&gt; $model,
              'emp' =&gt; $empModel,
          ]);
      }
  }
  </code></pre>
  
  <p>How can I save two or more values to database? How do I iterate or how do I know how many values are selected so that I can use a loop to insert?</p>
  
  <p>Can someone please help me or give any suggestions? Thank you</p>