Magento 2: Add grid column with a link in each row


I was tasked with adding a column with a link in each row to a custom grid in the Magento 2 admin panel. This grid does not use Ui Components. It took quite a while to find the solution, so I’m posting here to save for later and also for your viewing. This file is \Block\Adminhtml\$area\Grid.php and adds a “Delete” link to each row. The below sample uses a value for “id” for each data item in the collection (“index”), and adds an “id” URL variable with the id value to the hyperlink.

protected function _prepareColumns()
{
	//.... other columns here
 
	$this->addColumn('action', array(
		'header' => __('Action'),
		'width' => '100',
		'type' => 'action',
		'getter' => 'getId',
		'actions' => array(
			array(
				'caption' => __('Delete'),
				'url' => array('base' => '*/config_cms_page_field/delete'),
				'field' => 'id'
			)
		),
		'filter' => false,
		'sortable' => false,
		'index' => 'id',
		'is_system' => true,
	));
	return parent::_prepareColumns();
}

Further enhancements might include adding a confirmation popup once the delete link is clicked. For that we’d use this instead of the “url” array key. The trouble I had is what variable is used for the “id” of each row. If you can figure it out please let me know. A view renderer may be needed for this.

'onclick' => 'deleteConfirm("'.__('Are you sure you want to delete this?').'", \'' . $this->getUrl('*/config_cms_page_field/delete', ['id' => 111]) . '\')',

Leave a comment

Your email address will not be published. Required fields are marked *