Magento2 : Grid Button

Custom Button On Grid:
If grid is created using ui_componets then button can be add with folowing way.
class BackButton extends GenericButton implements ButtonProviderInterface
{
    
    protected $_request;
    protected $urlBuilder;

/**
 * @param \Magento\Framework\App\RequestInterface $request
 */
    
    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
             \Magento\Backend\Block\Context $context,
        array $data = []
    ) {
        $this->_request = $request;
        $this->urlBuilder = $context->getUrlBuilder();
    }

    /**
     * @return array
     */
    public function getButtonData()
    {
        return [
            'label' => __('Back'),
            'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
            'class' => 'back',
            'sort_order' => 10
        ];
    }

    public function getBackUrl()
    { 
        $reqeustParams = $this->_request->getParams();
        $parmvalue = $reqeustParams['parmname'];
        return $this->urlBuilder->getUrl(
            'namespace/moduluename_controller',
            [
                'parmname' => $parmvalue

            ]
        );
    } 
    
     
}
If grid is created using layout xml  then button can be add with folowing way
In Block => edit.php or view.php file
protected function _construct() {
        $this->addButton(
                'BackButton', [
            'label' => __('Back'),
            'onclick' => 'setLocation(\'' . $this->getBackUrl() . '\')',
            'class' => 'action-default scalable back'
                ], -1
        );
                                  
    }
public function getBackUrl()
    { 
      $parmname = $this->getRequest()->getParam('parmname'); 
      return $this->getUrl('*/*/*',['parmname'=>$parmname]);  
    }

Comments