Search code examples
javascriptyii2bootbox

yii2 customize a bootbox modal instead of alert on data-confirm


For example here I want to change alert for a bootbox.alert(...

'delete' => function ($url, $model, $key) {
                    return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
                        'title' => Yii::t('yii', 'Delete'),
                        'class'=>'btn btn-primary',
                        'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
                        'data-method' => 'post',
                        'data-pjax' => '0',
                    ]);
                },

Solution

  • Just add a HTML class to the element, drop the "data-confirm" param and use a "click" event. That way you can execute whatever you want when the link is clicked.

    'delete' => function ($url, $model, $key) {
                    return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
                        'title' => Yii::t('yii', 'Delete'),
                        'class'=>'btn btn-primary delete-button',
                        'data-id' => $model->id, // For using when the button is clicked
                    ]);
                },
    

    And inside your javascript file:

    $(".delete-button").on("click",function(e){
       e.preventDefault();
       var modelId = $(this).data('id');
       // Run bootbox.alert() here!!
       // Based on the bootbox result, you can decide to fire the initial event again:
       // $(this).unbind('submit').submit()
    });
    

    Hope it helps :)