Kartik yii2 select2 add data-attribute in <option>

Hello everyone :smiley:

I have a little question, i’m using kartik/select2 widget to select product. i push the data from an arrayhelper -> map (id,product name).

My question is: how i could add in the a data-attribute like this : data-price=“12.0”
this my code for now : (i’m using dynamicform too, because i can add multiple products - just the code of the field)

$products = ArrayHelper::map(Product::find()->where(['maker_id'=>$model->maker_id])->all(), 'id', 'product_name',);

 <?= $form->field($modelProduct, "[{$i}]product_id")
                     ->widget(Select2::classname(), [
                     'name'=>'product_id',
                      'hideSearch' => false,
                      'data' => $products,
                      'options' => ['placeholder' => 'Sélectionner'],
                      'pluginOptions' => [
                           'allowClear' => true
                      ],
               ]);
     ?>
     just add a data-attributes in the options like this
         'options' => ['placeholder' => 'Sélectionner','data-price'=>'12.0'],

Just don’t use ArrayHelper::map
Prepare you data like an array of objects
[ {'id'=>$model->id, 'text'=>$model->product_name, 'data-price'=>$model->price}, { ... } ]

Thank you, but this doesn’t work. First it doesn’t add the data-attribute, but even if it did, i can’t add the $product->price that way.

Thank you for your answer. Finally i did it in an other way,
i added a javascript function on the select change, to ask the controller for the product price.
That way i can get the product price, multiply it by the quantity selected and save directly the total.

Thank you all for your help

I know you already solved your problem, but here is another way to solve it:

You can pass these “extra” data inside the “options” “options” parameter. It will look something like this:

// Get products
$products = Product::find()->where(['maker_id'=>$model->maker_id])->all();
// Prepare the array, which you already do
$productsData = ArrayHelper::map($products, 'id', 'product_name',);
// Prepare the extras array, where all extra data will be
$productsExtraData = [];
foreach ( $products as $product ) {
    $productsExtraData[$product->id] = ['data-price' => $product->price];
}
?>

<?= $form->field( $modelProduct, "[{$i}]product_id")
    ->widget(Select2::classname(), [
        'name'=>'product_id',
        'hideSearch' => false,
        'data' => $productsData,
        'options' => [
            'placeholder' => 'Sélectionner',
            'options' => $productsExtraData
        ],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
?>
1 Like