Magento2 – How to Add Delete Button in Custom Form in Backend

adminformmagento2

I am working on the custom extension and I need delete button in the custom form at the backend. When I edit a record, there should be delete button above with other buttons like Back, Reset and Save and continue edit. Please see the screenshot to get more idea. Can someone guide me for it?

enter image description here

Best Answer

Add below code in app\code\Vendor\ModuleName\Block\Adminhtml\Module\Edit.php in _construct()

protected function _construct(){
        $this->addButton(
            'delete',
            [
                'label' => __('Delete'),
                'onclick' => 'deleteConfirm(' . json_encode(__('Are you sure you want to do this?'))
                    . ','
                    . json_encode($this->getDeleteUrl()
                    )
                    . ')',
                'class' => 'scalable delete',
                'level' => -1
            ]
        );
}

Below will be your delete action.

/**
 * @param array $args
 * @return string
 */
public function getDeleteUrl(array $args = [])
{
    $params = array_merge($this->getDefaultUrlParams(), $args);
    return $this->getUrl('module/*/delete', $params);
}