Customize delete confirmation in GridView
As nearly everything in Yii 2, you are starting from scratch with out-of-the-box solution for displaying models in grids (using yii\grid\GridView). Usually last among columns ($columns) of such grid there is an button column (yii\grid\ActionColumn) that serves basic operations for corresponding row or item. One of such column’s buttons there’s a delete button.
Everything is ready for you, to be used without much effort, but only as long as you are building an English-only application, as translating or customizing delete confirmation in such scenario isn’t a super-easy task. One of a great approaches is given in here: How to create a custom delete button?.
But, it works just great, if you want to customize just a single delete button of a one or maybe two grid view. What about, if you have a grid view for each and every of your data model?
Then the idea of using custom class comes in help.
You can define a really simple class that extends yii\grid\ActionColumn:
class CustomActionColumn extends ActionColumn
{
/**
* @var string message displayed as a confirmation of clicking "Delete" button
*/
public string $deleteConfirmationText = 'Are you sure?';
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
$this->initDefaultButtons();
}
/**
* Overrides the default button rendering callbacks.
*/
protected function initDefaultButtons()
{
$this->initDefaultButton('view', 'eye-open');
$this->initDefaultButton('update', 'pencil');
$this->initDefaultButton('delete', 'trash', [
'data-confirm' => $this->deleteConfirmationText,
'data-method' => 'post',
]);
}
}
And then just declare it as a one of columns in your grid view:
'class' => CustomActionColumn::class, 'deleteConfirmationText' => 'Seriously!',
You can use translations naturally:
'class' => CustomActionColumn::class,
'deleteConfirmationText' => Yii::t('app', 'Are you sure?'),
And this is just the beginning. Because using the very similar way you can customize nearly every aspect of your action column.