M
M
MaikMain2019-10-06 13:44:54
Yii
MaikMain, 2019-10-06 13:44:54

Problem with checkboxlist. Yii2?

Good afternoon, I have such a problem.
I have a regular CRUD. And I need to add an entry to the database with the sizes of the goods. To do this, I created a memory file for myself (SizeOneHelper):

SizeOneHelper
class SizeOneHelper
{
    public static function typeList(): array
    {
        return [
            'S (55/56)',
            'M (57/58)',
            'L (59/60)',
            'XL (61/62)',
        ];
    }
    public static function typeName($drive): string
    {
        return ArrayHelper::getValue(self::typeList(), $drive);
    }
    public static function typeLabel($drive): string
    {
        return Html::tag('span', ArrayHelper::getValue(self::typeList(), $drive));
    }
}

In view I output it like this:
<?= $form->field($model, 'size')->checkboxList(SizeOneHelper::typeList()) ?>

I save it to the database like this:
Controller

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->size =  implode(', ',$model->size);
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        }
        return $this->render('update', [
            'model' => $model,
        ]);
    }


Accordingly, in the database I now have: "0, 2" The
question is, how can I make the checkboxList show which elements I have selected. And how to display it correctly in DetailView.
Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2019-10-06
@MaikMain

Your size data is not stored very conveniently.
For now, this is how you can do it.

// Ваш статический метод в модели SizeOneHelper
    public static function getSizeList(): array
    {
        return [
            'S (55/56)',
            'M (57/58)',
            'L (59/60)',
            'XL (61/62)',
        ];
    }

// если в $model->size данные хранятся в виде строки, то надо привести к массиву и передать в checkboxList()
$select = explode(',', $model->size);
echo $form->field($model, 'size')->checkboxList(SizeOneHelper::getSizeList(),[
   'item' => function($index, $label, $name, $checked, $value) use ($select){
      if(in_array($index, $select)){
         $checked = 'checked';
      }
      return Html::checkbox($name, $checked);
   }
])

But I wouldn't store it as a string. Most likely, I would create a separate linking table where I would store the sizes and id of the product.
ps I did it "on my knee", but if you think about it, you can improve it too.
pss In order to display the label checkbox, the required parameter is passed to the function in the $label variable. Use it and the name of the checkbox will be displayed.
psss In DetailVeiw you can display the desired data in this way
// метод в модели SizeOneHelper
    public function getSizeName()
    {
        return ArrayHelper::filter(self::getSizeList(), explode(',',$this->size));
    }

// в DetailView получаем строку по названиям размеров
echo DetailView::widget([
  'model' => $model,
  'attributes' => [
     [
       'attribute' => 'size',
       'value' => function($model){
          return implode(',',$model->getSizeName());
       }
     ]  
  ]
]);

pssss Create an extra method on the SizeOneHelper model
public  function getSelectSizeList()
    {
        return explode(',',$this->size);
    }

The getSizeName method will change to this
// метод в модели SizeOneHelper
 public function getSizeName()
    {
        return ArrayHelper::filter(self::getSizeList(), $this->getSelectSizeList());
    }

Then the size output might look like this:
// в checkboxList
echo $form->field($model, 'size')->checkboxList(SizeOneHelper::getSizeList(),[
   'item' => function($index, $label, $name, $checked, $value) use ($model){
      if(in_array($index, $model->getSelectSizeList())){
         $checked = 'checked';
      }
      return Html::checkbox($name, $checked, ['label' => $label, 'value' => $value]);
   }
])

R
Ruslan Ruslanov, 2019-10-06
@dasauser

Well, something like this:

//controller
public function actionView() {
    $data = ;
    return $this->render('view', [ 'data' => $data, 'model' => $this->findModel($id), ]);
}

//View
foreach ($data as $key => $value) {
    $checked = '';
    if ($value['checked'] === true) {
        $checked = 'checked';
    }
    echo "<input type=checkbox id=" . $value['id'] . " $checked>";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question