phparraysyii2jquery-select2kartik-v

How to post actual primary keys of records from table and not indexes of an array in php Yii2 if I use select2 widget?


My function inside controller is as follows:

public function actionProjects($id)
    {
        $model = $this->findModel($id);
        $projects = Project::find()->all();
        $projectIds = Yii::$app->request->post('projects');
        if (Yii::$app->request->isPost) {
            Yii::$app->session->setFlash('success');
            $model->unlinkAll('projects');
            if ($projectIds) {
                foreach ($projectIds as $projectId) {
                    $project = Project::findOne(abs((int)$projectId));
                    if ($project) {
                        $model->link('projects', $project);
                    }
                }
            }
        }
        print_r($projectIds);
        return $this->render('projects', ['projects' => $projects, 'model' => $model]);
    }

My view is as follows:

<?php
...
function sortArray($a, $b)
{
    return strcmp($a, $b);
}

$projects = ArrayHelper::map($projects, 'id', 'title');
usort($projects, 'sortArray');
?>
<div class="application-create x_panel">

    <div class="x_title"><h3><?= Html::encode($this->title) ?></h3></div>

    <div class="x_content">
        <?php $form = ActiveForm::begin(); ?>
        <div class="form-group">
            <?= Select2::widget([
                'name' => 'projects[]',
                'options' => ['placeholder' => 'Выберите проект...'],
                'language' => 'ru',
                'value' => array_keys(ArrayHelper::map($model->projects, 'id', 'title')),
                'data' => $projects,
                'pluginOptions' => [
                    'allowClear' => true,
                    'multiple' => true
                ],
            ]) ?>
        </div>
        <div class="form-group">
            <?= Html::submitButton('Обновить', ['class' => 'btn btn-primary']) ?>
        </div>
        <?php ActiveForm::end() ?>
    </div>

</div>

When I select single or multiple items from select2, and click update button - this code:

$projectIds = Yii::$app->request->post('projects');

posts array like this: Array ( [0] => 0 [1] => 1 [2] => 2 )

the data sent to the server is the array of indexes of items and not actual indexes (primary keys) from the table. (I have 3 items in db table - their indexes are 5,6 and 7)

How to sent primary keys of selected items? I cannot find hidden rat that causes my problem. It seems that everything is correct in code. But actually not.


Solution

  • The problem is in the usort() call. That function removes the indexes in your $projects array. You have to use uasort() instead which is designed to maintain indexes in associative arrays.