Back to Top

How to insert phtml file with admin form in Adobe Commerce (Magento 2)

Updated 13 August 2024

Here we will learn, How to add phtml file with admin form in Adobe Commerce (Magento 2).

Create the Edit Block File Which will be included by the Edit or Create New Controller According to your need.

Webkul/AddPhtmlDemo/Block/Adminhtml/Demo/Edit.php

<?php
namespace Webkul\AddPhtmlDemo\Block\Adminhtml\Demo;
class Edit extends \Magento\Backend\Block\Widget\Form\Container
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    protected $_optionType;

    /**
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }

    /**
     * Initialize cms page edit block
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_objectId = 'id';
        $this->_blockGroup = 'Webkul_AddPhtmlDemo';
        $this->_controller = 'adminhtml_demo';

        parent::_construct();

        $this->buttonList->update('save', 'label', __('Save Fields'));
        $this->buttonList->add(
            'saveandcontinue',
            [
                'label' => __('Save and Continue Edit'),
                'class' => 'save',
                'data_attribute' => [
                    'mage-init' => [
                        'button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form'],
                    ],
                ]
            ],
            -100
        );
        $this->buttonList->remove('delete');
    }

    /**
     * Retrieve text for header element depending on loaded page
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {
       
    }

    /**
     * Check permission for passed action
     *
     * @param string $resourceId
     * @return bool
     */
    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }

    /**
     * Getter of url for "Save and Continue" button
     * tab_id will be replaced by desired by JS later
     *
     * @return string
     */
    protected function _getSaveAndContinueUrl()
    {
        return $this->getUrl('addphtmldemo/*/save', ['_current' => true, 'back' => 'edit', 'active_tab' => '{{tab_id}}']);
    }


    /**
     * Prepare form Html. call the phtm file with form.
     *
     * @return string
     */
    public function getFormHtml()
    {
       // get the current form as html content.
        $html = parent::getFormHtml();
        //Append the phtml file after the form content.
        $html .= $this->setTemplate('Webkul_AddPhtmlDemo::demo/demo.phtml')->toHtml(); 
        return $html;
    }

    /**
     * Prepare layout
     *
     * @return \Magento\Framework\View\Element\AbstractBlock
     */
    protected function _prepareLayout()
    {

        $this->_formScripts[] = "
            require([
                'jquery',
                'mage/mage',
                'knockout'
            ], function ($){
                
            });
               
        ";
        return parent::_prepareLayout();
    }
}

The getFormHtml method is all that is required in above code. Within this method, we can get the Form (which we have created in below Form.php file) and append our custom phtml file after this Form.

Now lets create the Form.php file.

Searching for an experienced
Magento 2 Company ?
Find out More

Webkul/AddPhtmlDemo/Block/Adminhtml/Demo/Edit/Form.php

<?php

    namespace Webkul\AddPhtmlDemo\Block\Adminhtml\Demo\Edit;

    class Form extends \Magento\Backend\Block\Widget\Form\Generic
    {
        /**
         * @var \Magento\Store\Model\System\Store
         */
        protected $_systemStore;
        
        /**
         * Core registry
         *
         * @var \Magento\Framework\Registry
         */
        protected $_coreRegistry;

        /**
         * @param \Magento\Backend\Block\Template\Context $context
         * @param \Magento\Framework\Registry $registry
         * @param \Magento\Framework\Data\FormFactory $formFactory
         * @param \Magento\Store\Model\System\Store $systemStore
         * @param array $data
         */
        public function __construct(
            \Magento\Backend\Block\Template\Context $context,
            \Magento\Framework\Registry $registry,
            \Magento\Framework\Data\FormFactory $formFactory,
            \Magento\Store\Model\System\Store $systemStore,
            array $data = []
        ) {
            $this->_systemStore = $systemStore;
            $this->_coreRegistry = $registry;
            parent::__construct($context, $registry, $formFactory, $data);
        }

        /**
         * Init form
         *
         * @return void
         */
        protected function _construct()
        {
            parent::_construct();
            $this->setId('demo_form');
            $this->setTitle(__('Demo Information'));
        }

        /**
         * Prepare form
         *
         * @return $this
         */
        protected function _prepareForm()
        {
           //Preparing the form here.
            $form = $this->_formFactory->create(
                ['data' => ['id' => 'edit_form', 'enctype' => 'multipart/form-data', 'action' => $this->getData('action'), 'method' => 'post']]
            );
            $form->setHtmlIdPrefix('demo_');

            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Demo Information'), 'class' => 'fieldset-wide']
            );

            $fieldset->addField(
                'label_name',
                'text',
                ['name' => 'label_name', 'label' => __('Label'), 'title' => __('Demo Field'), 'required' => true]
            );
            
            $form->setUseContainer(true);
            $this->setForm($form);
            return parent::_prepareForm();
        }

    }

Finally let’s create the demo.phtml file.

Webkul/AddPhtmlDemo/view/adminhtml/templates/demo/demo.phtml

<?php echo "Hello i am content of demo.phtm file."; ?>

Now Click on Edit or Add New Field to see the result.

wp-block-image

If you require technical help, please reach out to us at [email protected]. Additionally, discover a range of solutions to upgrade your store’s functionality by visiting the Adobe Commerce plugins section.

For expert advice or to create custom features, hire Adobe Commerce Developers for your project.

. . .

Leave a Comment

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


1 comments

  • Vivek Shingala
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home