phpyii2kartik-v

Add subtitle in kartik Select2 yii2


I have a db table with fields like this

posts table

'id'
'group_id'
'name'

I display this table as a list in kartik Select2 widget

$form->field($model, 'post')
    ->widget(
        \kartik\select2\Select2::className(),
        [
            'data' => ArrayHelper::map(Post::find()->all(), 'id', 'name'),
            'options' => [
                'placeholder' => \Yii::t('modules', 'Choose post'),
                'multiple' => true
            ],
            'pluginOptions' => [
                'allowClear' => true,
            ],
        ]
    )->label('');

Now I have in the list all posts in a row from the table are displayed

But I have a group_id field in this table, and the corresponding groups table

'id'
'name'

How can I make it so that the name field from the groups table is displayed as a subtitle in the select and all records are respectively divided into groups depending on the group_id with the corresponding subtitle?

I try something like this but end up with the same group name and the same post name multiple times in the list

$result = [];

$posts = ArrayHelper::map(Post::find()->all(), 'id', 'name');
$groups = Group::find()->all();

foreach ($posts as $post) {
    $groups = $groups[$post->group_id] ?? null;
    if (is_null($groups)) {
        $result[$post->id] = $post->name;
    } else {
        $line = [];
        foreach ($groups as $group) {
            $line[$post->group_id . '-' . $group->id] = $group->name;
        }
        $result[$post->name] = $line;
    }
}

Solution

  • $result = [];
    $posts = Post::find()->with('group')->all();
    foreach($posts as $post){
      $group = $post->group;
      $key = $group->id . '-' . $group->name;
      $result[$key][$post->id] = $post->id . '-' . $post->name;
    }
    
    $form = ActiveForm::begin();
    echo $form->field($model, 'post')->widget(\kartik\select2\Select2::class, [
      'data'          => $result,
      'options'       => [
        'placeholder' => \Yii::t('modules', 'Choose post'),
        'multiple'    => true,
      ],
      'pluginOptions' => [
        'allowClear' => true,
      ],
    ]);
    ActiveForm::end();
    

    Post model should have Group foreign key relation