我使用Yii2多项选择下拉图片,它在创建时工作正常,但没有在更新时显示我选择的值... 表格:
<?php
$allProducts = Product::find()->where('active = 1')->all();
$prArr = array();
if ($allProducts) {
foreach ($allProducts as $allProduct) {
echo '<option value="' . $allProduct->id . '" style="color: #000; height: 50px; padding-left: 70px;padding-top: 15px;background-image: url(\'' . $allProduct->getThumb() . '\');background-repeat: no-repeat;background-size: 65px auto;">' . $allProduct->title . '</option>';
}
}
?>
控制器:
$oldRels = ProductRelated::find()->where('main_product_id = :main_product_id', ['main_product_id' => $model->id])->all();
if ($oldRels) {
foreach ($oldRels as $oldRel) {
$oldRel->delete();
}
}
if (isset($_POST['relProducts']) and ! empty($_POST['relProducts'])) {
foreach ($_POST['relProducts'] as $relProduct_id) {
$relProduct = new ProductRelated;
$relProduct->main_product_id = $model->id;
$relProduct->rel_product_id = $relProduct_id;
$relProduct->save(false);
}
}
当我更新我的recored时,如何在下拉列表中显示带有图像的多个选定值?
答案 0 :(得分:1)
你可以试试这个:
<select id="relProductSelect" name="relProducts[]" multiple>
<?php
$allProducts = Product::find()->where('active = 1')->all();
$arrRelatedProducts = ArrayHelper::map(ProductRelated::find()->where('main_product_id = :main_product_id', ['main_product_id' => $model->id])->all(), 'rel_product_id', 'rel_product_id');
if($allProducts){
foreach($allProducts as $allProduct){
if(in_array($allProduct->id, $arrRelatedProducts)){
echo '<option value="'.$allProduct->id.'" selected style="color: #000; height: 50px; padding-left: 70px;padding-top: 15px;background-image: url(\''.$allProduct->getThumb().'\');background-repeat: no-repeat;background-size: 65px auto;">'.$allProduct->title.'</option>';
}else{
echo '<option value="'.$allProduct->id.'" style="color: #000; height: 50px; padding-left: 70px;padding-top: 15px;background-image: url(\''.$allProduct->getThumb().'\');background-repeat: no-repeat;background-size: 65px auto;">'.$allProduct->title.'</option>';
}
}
}
?>
</select>