1
votes

I would like to render JQuery UI sortable list (I am using Yii2 JUI widget), to be populated with data from database table. I am passing data from database to the view and have it in a variable. The item HTML structure looks like this:

<div class="row row-item dist simple-border">
  <div class="col-md-4">
    <img alt="Bootstrap Image Preview" src="<IMAGE_PATH>" />
  </div>
    <div class="col-md-8">
      <h4>
        <ITEM DESCRIPTION>
      </h4>
    </div>
</div>

My question is: What is the best way to populate items inside the Widget, as it is impossible to execute php code within.

<?= yii\jui\Sortable::widget([
    'items' => [
     ------<expected foreach php loop for each model>------
       ['content' =>
         <This is where one HTML item goes>
       ],
     ------<end foreach>------
     ],
     'options' => ['class' => 'connectedSortable',],
     'clientOptions' => ['cursor' => 'move', 'connectWith' => '.connectedSortable']
]) ?>

My first idea was to create a function that returns item content as a string, but it doesn't seem like a good, efficient practice. Any ideas would be greatly appreciated. Regards.

EDIT: So far, I have created a function, which renders mentioned above items by concatenation. Still, I don't think this is the proper way to do it. I am still new to Yii and would be thankful for any tips. Regards.

1

1 Answers

1
votes

I have found such solution for my problem, feel free to review and improve it.

Controller

public function actionIndex()
{
    $searchModel = new Exchange();
    $dataProvider = $searchModel->getOwnerItems(Yii::$app->request->queryParams);
    $ownerItems = $this->getOwnerItems($dataProvider);

    return $this->render('index', [
        'ownerItems' => $ownerItems,
    ]);

}

protected function getOwnerItems($dataProvider){
    $items=array();
    foreach($dataProvider->models as $model){
        $item=array('content' => '<div class="row row-item dist simple-border"> <div class="col-md-4"> <img alt="Bootstrap Image Preview" src="uploads/'.$model->image.'" /> </div> <div class="col-md-8"> <h4>'. $model->name .'</h4> </div> </div>');
        array_push($items,$item);
    }
    return $items;
}

View

<?= yii\jui\Sortable::widget([
   'items' => $ownerItems,
   'options' => ['class' => 'connectedSortable',],
   'clientOptions' => ['cursor' => 'move', 'connectWith' => '.connectedSortable']
]) ?>

I am aware of possible imperfection of this solution, but I have no other ideas at the moment. Regards