Skip to content

How I can add a `Create New Button` to my Grid in magento2 where redirects to another page?

I am learning magento extention creation, and I try to add a “Create New” record in my admin grid. So far I made this grid:

namespace MageGuideFirstModuleBlockAdminhtml;

use MageGuideFirstModuleModelFactoriesBlogPostCollectionFactory as BlogPostCollectionFactory;
use MagentoBackendBlockTemplateContext;
use MagentoBackendHelperData;
use MagentoFrameworkObjectManagerInterface;
use MagentoBackendBlockWidgetGridExtended;
use MagentoFrameworkRegistry;


class Grid extends Extended
{
// also you can use Magento Default CollectionFactory

    protected $registry;
    protected $_objectManager = null;
    protected BlogPostCollectionFactory $demoFactory;

    public function __construct(
        Context $context,
        Data $backendHelper,
        Registry $registry,
        ObjectManagerInterface $objectManager,
        BlogPostCollectionFactory $demoFactory,
        array $data = []
    ) {
        $this->_objectManager = $objectManager;
        $this->registry = $registry;
        $this -> demoFactory = $demoFactory;
        parent::__construct($context, $backendHelper, $data);
    }
    protected function _construct()
    {
        parent::_construct();
        $this->setId('blog_post_id');
        $this->setDefaultSort('created_at');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
    }
    protected function _prepareCollection()
    {
        $demo = $this->demoFactory->create()
            ->addFieldToSelect('*');

        $demo->addFieldToFilter('blog_post_id', array('neq' => ''));

        $this->setCollection($demo);

        return parent::_prepareCollection();
    }
    protected function _prepareColumns()
    {

        $this->addColumn(
            'id',
            [
                'header' => __('ID'),
                'type' => 'number',
                'index' => 'blog_post_id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id',
            ]
        );
        $this->addColumn(
            'title',
            [
                'header' => __('Blog Post Title'),
                'type' => 'text',
                'index' => 'title',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id',
            ]
        );

        $this->addColumn(
            'skus',
            [
                'header' => __('Product Skus'),
                'type' => 'text',
                'index' => 'skus',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id',
            ]
        );

        $this->addColumn(
            'created_at',
            [
                'header' => __('Created At'),
                'index' => 'creation_dt',
                'type' => 'datetime',
            ]
        );

        $this->addColumn(
            'updated_at',
            [
                'header' => __('Last Update Datetime'),
                'index' => 'update_dt',
                'type' => 'datetime',
            ]
        );

        return parent::_prepareColumns();
    }

    public function getGridUrl()
    {
        return $this->getUrl('*/*/actionName', ['_current' => true]);
    }
}

And I load it via this contoller:


namespace MageGuideFirstModuleControllerAdminhtmlIndex;

use MageGuideFirstModuleBlockAdminhtmlGrid as AdminGrid;

use MagentoBackendAppAction;
use MagentoBackendAppActionContext;
use MagentoFrameworkViewResultPageFactory;

class Index extends Action
{
    protected $resultPageFactory;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }
    public function execute()
    {
        $this->_view->loadLayout();
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('BlogPosts'));
        $resultPage->setActiveMenu('MageGuide_FirstModule::home');
        $resultPage->addBreadcrumb(__('BlogPosts'), __('BlogPosts'));
        $this->_addContent($this->_view->getLayout()->createBlock(AdminGrid::class));
        $this->_view->renderLayout();
    }
    protected function _isAllowed()
    {
        return true;
    }
}

Also I made a plain Page where later I will add a form that creates a new BlogPost:

namespace MageGuideFirstModuleControllerAdminhtmlBlogpostForm;

use MagentoBackendAppAction;

class Index extends Action
{
    /** @var MagentoFrameworkViewResultPageFactory  */
    protected $resultPageFactory;
    public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoFrameworkViewResultPageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    /**
     *
     * @return MagentoFrameworkViewResultPage
     */
    public function execute()
    {
        return $this->resultPageFactory->create();
    }

    protected function _isAllowed()
    {
        return true;
    }
}

That using the following template `./app/code/MageGuide/FirstModule/view/adminhtml/layout/adminblogposts_blogpostform_index.xml:

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left"  xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <title>
            Add BLogpost
        </title>
    </head>
    <body>
        <referenceContainer name="content">
            Hello
        </referenceContainer>
    </body>
</page>

What I want is upon showing the Grid to add a button-hyperlink Create New where a new page will open for showing the form page. Do you know how I can do that?