0

I am trying to display a grid for my module on an extra tab added on the customer_index_edit. I managed to add custom tab, and i am trying to add layout, like in Magento_Wishlist, but it`s unsuccessfully. When i click the tab, nothing changed. Can someone help me?

UPDATE:

I created layout {Vendor}/{Extension}/view/adminhtml/layout/customer_index_edit.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="customer_form">
            <block class="Webinse\Crm\Block\Adminhtml\CustomerReminderTab" name="crm_reminders">
            </block>
        </referenceBlock>
    </body>
</page>

Next, i created Block {Vendor}/{Extension}/Block/Adminhtml/CustomerReminderTab.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Webinse\Crm\Block\Adminhtml;

use Magento\Framework\Registry;
use Magento\Backend\Block\Template\Context;
use Magento\Ui\Component\Layout\Tabs\TabWrapper;
use Magento\Ui\Component\Layout\Tabs\TabInterface;
use Magento\Customer\Controller\RegistryConstants;

class CustomerReminderTab extends TabWrapper implements TabInterface
{
    /**
     * Core registry
     *
     * @var Registry
     */
    protected $coreRegistry = null;

    /**
     * @var bool
     */
    protected $isAjaxLoaded = true;

    /**
     * Constructor
     *
     * @param Context $context
     * @param Registry $registry
     * @param array $data
     */
    public function __construct(Context $context, Registry $registry, array $data = [])
    {
        $this->coreRegistry = $registry;
        parent::__construct($context, $data);
    }

    /**
     * @inheritdoc
     */
    public function canShowTab()
    {
        return $this->coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
    }

    /**
     * Return Tab label
     *
     * @return \Magento\Framework\Phrase
     */
    public function getTabLabel()
    {
        return __('CRM');
    }

    /**
     * Return URL link to Tab content
     *
     * @return string
     */
    public function getTabUrl()
    {
        return $this->getUrl('customer/*/reminder', ['_current' => true]);
    }
}

Next {Vendor}/{Extension}/view/adminhtml/layout/customer_index_reminder.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/layout_generic.xsd">

    <container name="root">
        <block class="Magento\Framework\View\Element\Template" as="grid">
            <arguments>
                <argument name="template" xsi:type="string">Webinse_Crm::customer/edit/tab/reminder.phtml</argument>
            </arguments>
        </block>
    </container>
</layout>

And template {Vendor}/{Extension}/view/adminhtml/templates/customer/edit/tab/reminder.phtml

<?php echo 'hello world'; ?>

But it`s not working. When i click on the tab, i have nothing. Can someone explain how to do this in the right way?

  • What have you tried so far? Please post any code etc you have added to get this to work – Sander Mangel Sep 7 '15 at 9:35
  • @sander-mangel Please, check my code. I hope you can help me. – ZebraBeard Sep 9 '15 at 9:59
  • @ZebraBeard, hi have you done this? – Bojjaiah Oct 21 '15 at 9:24
  • @magento-two no – ZebraBeard Oct 21 '15 at 9:45
2

Please follow below steps

admin layout xml app\code\Sugarcode\Test\view\adminhtml\layout\test_lists_edit.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>
        <css src="jquery/fileUploader/css/jquery.fileupload-ui.css"/>
    </head>
    <update handle="editor"/>
    <body>
        <referenceContainer name="content">
            <block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit" name="list_post_edit"/>
        </referenceContainer>
        <referenceContainer name="left">
            <block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tabs" name="list_post_edit_tabs">
                <block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Main" name="list_post_edit_tab_main"/>
                <action method="addTab">
                    <argument name="name" xsi:type="string">main_section</argument>
                    <argument name="block" xsi:type="string">list_post_edit_tab_main</argument>
                </action>
            </block>
        </referenceContainer>
    </body>
</page>

controller where you need to check id is there or not to fill form and save the data in register

app\code\Sugarcode\Test\Controller\Adminhtml\Lists\Edit.php

<?php

namespace Sugarcode\Test\Controller\Adminhtml\Lists;

use Magento\Backend\App\Action;

class Edit extends \Magento\Backend\App\Action
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Magento\Framework\Registry $registry
     */
    public function __construct(
        Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\Registry $registry
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->_coreRegistry = $registry;
        parent::__construct($context);
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return true;
    }

    /**
     * Init actions
     *
     * @return \Magento\Backend\Model\View\Result\Page
     */
    protected function _initAction()
    {
        // load layout, set active menu and breadcrumbs
        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        $resultPage->setActiveMenu('Sugarcode_Test::test')
            ->addBreadcrumb(__('Lists'), __('Lists'))
            ->addBreadcrumb(__('Manage Info'), __('Manage Info'));
        return $resultPage;
    }

    /**
     * Edit Blog Post
     *
     * @return \Magento\Backend\Model\View\Result\Page|\Magento\Backend\Model\View\Result\Redirect
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        // 1. Get ID and create model
        $id = $this->getRequest()->getParam('id');
        $model = $this->_objectManager->create('Sugarcode\Test\Model\Test');

        // 2. Initial checking
        if ($id) {
            $model->load($id);
            if (!$model->getId()) {
                $this->messageManager->addError(__('This info no longer exists.'));
                /** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                $resultRedirect = $this->resultRedirectFactory->create();

                return $resultRedirect->setPath('*/*/');
            }
        }

        // 3. Set entered data if was error when we do save
        $data = $this->_objectManager->get('Magento\Backend\Model\Session')->getFormData(true);
        if (!empty($data)) {
            $model->setData($data);
        }

        // 4. Register model to use later in blocks
        $this->_coreRegistry->register('lists', $model);

        // 5. Build edit form
        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        $resultPage = $this->_initAction();
        $resultPage->addBreadcrumb(
            $id ? __('Edit Info') : __('New Info'),
            $id ? __('Edit info') : __('New Info')
        );
        $resultPage->getConfig()->getTitle()->prepend(__('Info'));
        $resultPage->getConfig()->getTitle()
            ->prepend($model->getId() ? $model->getTitle() : __('New Info'));

        return $resultPage;
    }
}

lets move on to block app\code\Sugarcode\Test\Block\Adminhtml\Lists\Edit.php

<?php

namespace Sugarcode\Test\Block\Adminhtml\Lists;

class Edit extends \Magento\Backend\Block\Widget\Form\Container
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @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 blog post edit block
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_objectId = 'id';
        $this->_blockGroup = 'Sugarcode_Test';
        $this->_controller = 'adminhtml_lists';

        parent::_construct();

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

        $this->buttonList->update('delete', 'label', __('Delete List'));
    }

    /**
     * Retrieve text for header element depending on loaded post
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {
        if ($this->_coreRegistry->registry('lists')->getId()) {
            return __("Edit List '%1'", $this->escapeHtml($this->_coreRegistry->registry('lists')->getTitle()));
        } else {
            return __('New Info');
        }
    }

    /**
     * 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('test/*/save', ['_current' => true, 'back' => 'edit', 'active_tab' => '{{tab_id}}']);
    }

    /**
     * Prepare layout
     *
     * @return \Magento\Framework\View\Element\AbstractBlock
     */
    protected function _prepareLayout()
    {
        $this->_formScripts[] = "
            function toggleEditor() {
                if (tinyMCE.getInstanceById('page_content') == null) {
                    tinyMCE.execCommand('mceAddControl', false, 'content');
                } else {
                    tinyMCE.execCommand('mceRemoveControl', false, 'content');
                }
            };
        ";
        return parent::_prepareLayout();
    }

}

as like in magneto1.x here alo we have mode which default folder name is edit so create folder called edit then create below files

app\code\Sugarcode\Test\Block\Adminhtml\Lists\Edit\Form.php

<?php

namespace Sugarcode\Test\Block\Adminhtml\Lists\Edit;

/**
 * Adminhtml blog post edit form block
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
    /**
     * Prepare form
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create(
            ['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']]
        );
        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }
}

app\code\Sugarcode\Test\Block\Adminhtml\Lists\Edit\tabs.php

<?php
namespace Sugarcode\Test\Block\Adminhtml\Lists\Edit;

/**
 * Admin page left menu
 */
class Tabs extends \Magento\Backend\Block\Widget\Tabs
{
    /**
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('post_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle(__('Information'));
    }
}

now create folder called form and file main.php as per layout xml this will load in form container if you need tabs then you need to use interface

class Main extends \Magento\Backend\Block\Widget\Form\Generic implements \Magento\Backend\Block\Widget\Tab\TabInterface

then interface function needs to be implemented here in below code below Prepare label for tab are for tabs app\code\Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Main.php

<?php

namespace Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab;

/**
 * Blog post edit form main tab
 */
class Main extends \Magento\Backend\Block\Widget\Form\Generic implements \Magento\Backend\Block\Widget\Tab\TabInterface
{
    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $_systemStore;

    /**
     * @var \Magento\Cms\Model\Wysiwyg\Config
     */
    protected $_wysiwygConfig;

    /**
     * @var \Sugarcode\Test\Model\Status
     */
    protected $_status;

    /**
     * @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,
        \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
        \Sugarcode\Test\Model\Status $status,
        array $data = []
    ) {
        $this->_systemStore = $systemStore;
        $this->_wysiwygConfig = $wysiwygConfig;
        $this->_status = $status;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * Prepare form
     *
     * @return $this
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function _prepareForm()
    {
        /* @var $model \SR\Weblog\Model\BlogPosts */

        $model = $this->_coreRegistry->registry('lists');

        $isElementDisabled = false;

        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create();

        $form->setHtmlIdPrefix('page_');

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

        if ($model->getId()) {
            $fieldset->addField('id', 'hidden', ['name' => 'id']);
        }


        $fieldset->addField(
            'title',
            'text',
            [
                'name' => 'title',
                'label' => __('Title'),
                'title' => __('Title'),
                'required' => true,
                'disabled' => $isElementDisabled,
                'value' =>'abc'
            ]
        );




        if (!$model->getId()) {
            $model->setData('status', $isElementDisabled ? '0' : '1');
        }

        $fieldset->addField(
            'status',
            'select',
            [
                'label' => __('Status'),
                'title' => __('Status'),
                'name' => 'status',
                'required' => true,
                'options' => $this->_status->getOptionArray(),
                'disabled' => $isElementDisabled
            ]
        );
        $fieldset->addField(
            'short_summary',
            'editor',
            [
                'name' => 'short_summary',
                'label' => __('Summary'),
                'title' => __('Summary'),
                'style' => 'height:36em',
                'required' => true,
                'config' => $this->_wysiwygConfig->getConfig()
            ]
        );




        $dateFormat = $this->_localeDate->getDateFormat(
            \IntlDateFormatter::SHORT
        );

        /* $fieldset->addField(
            'created_at',
            'date',
            [
                'name' => 'created_at',
                'label' => __('Created Date'),
                'date_format' => $dateFormat,
                'disabled' => $isElementDisabled,
                'class' => 'validate-date validate-date-range date-range-custom_theme-from'
            ]
        ); */

        $form->setValues($model->getData());
        $this->setForm($form);

        return parent::_prepareForm();
    }

    /**
     * Prepare label for tab
     *
     * @return \Magento\Framework\Phrase
     */
    public function getTabLabel()
    {
        return __('Information');
    }

    /**
     * Prepare title for tab
     *
     * @return \Magento\Framework\Phrase
     */
    public function getTabTitle()
    {
        return __('Information');
    }

    /**
     * {@inheritdoc}
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isHidden()
    {
        return false;
    }

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

if you dont wants tabs then follow below code

app\code\Sugarcode\Test\view\adminhtml\layout\test_lists_details.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="jquery/fileUploader/css/jquery.fileupload-ui.css"/>
    </head>
    <update handle="editor"/>
    <body>
        <referenceContainer name="content">
            <block class="Sugarcode\Test\Block\Adminhtml\Lists\Details" name="details_block_edit"/>
        </referenceContainer>
    </body>
</page>

app\code\Sugarcode\Test\Controller\Adminhtml\Lists\Details.php

<?php

namespace Sugarcode\Test\Controller\Adminhtml\Lists;

use Magento\Backend\App\Action;

class Details extends \Magento\Backend\App\Action
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Magento\Framework\Registry $registry
     */
    public function __construct(
        Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\Registry $registry
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->_coreRegistry = $registry;
        parent::__construct($context);
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return true;
    }

    /**
     * Init actions
     *
     * @return \Magento\Backend\Model\View\Result\Page
     */
    protected function _initAction()
    {
        // load layout, set active menu and breadcrumbs
        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        $resultPage->setActiveMenu('Sugarcode_Test::test')
            ->addBreadcrumb(__('Lists'), __('Lists'))
            ->addBreadcrumb(__('Manage Info'), __('Manage Info'));
        return $resultPage;
    }

    /**
     * Edit Blog Post
     *
     * @return \Magento\Backend\Model\View\Result\Page|\Magento\Backend\Model\View\Result\Redirect
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        // 1. Get ID and create model
        $id = $this->getRequest()->getParam('id');
        $model = $this->_objectManager->create('Sugarcode\Test\Model\Test');

        // 2. Initial checking
        if ($id) {
            $model->load($id);
            if (!$model->getId()) {
                $this->messageManager->addError(__('This info no longer exists.'));
                /** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                $resultRedirect = $this->resultRedirectFactory->create();

                return $resultRedirect->setPath('*/*/');
            }
        }

        // 3. Set entered data if was error when we do save
        $data = $this->_objectManager->get('Magento\Backend\Model\Session')->getFormData(true);
        if (!empty($data)) {
            $model->setData($data);
        }

        // 4. Register model to use later in blocks
        $this->_coreRegistry->register('lists', $model);

        // 5. Build edit form
        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        $resultPage = $this->_initAction();
        $resultPage->addBreadcrumb(
            $id ? __('Edit Info') : __('New Info'),
            $id ? __('Edit info') : __('New Info')
        );
        $resultPage->getConfig()->getTitle()->prepend(__('Info'));
        $resultPage->getConfig()->getTitle()
            ->prepend($model->getId() ? $model->getTitle() : __('New Info'));

        return $resultPage;
    }
}

now in blocks app\code\Sugarcode\Test\Block\Adminhtml\Lists\Details.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sugarcode\Test\Block\Adminhtml\Lists;

/**
 * CMS block edit form container
 */
class Details extends \Magento\Backend\Block\Widget\Form\Container
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @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);
    }

    /**
     * @return void
     */
    protected function _construct()
    {
          $this->_objectId = 'id';
        $this->_blockGroup = 'Sugarcode_Test';
        $this->_controller = 'adminhtml_lists';
        $this->_mode = 'details';

        parent::_construct();

        $this->buttonList->update('save', 'label', __('Save Details'));
        $this->buttonList->update('delete', 'label', __('Delete Details'));

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

        $this->_formScripts[] = "
            function toggleEditor() {
                if (tinyMCE.getInstanceById('block_content') == null) {
                    tinyMCE.execCommand('mceAddControl', false, 'block_content');
                } else {
                    tinyMCE.execCommand('mceRemoveControl', false, 'block_content');
                }
            }
        ";
    }

    /**
     * Get edit form container header text
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {
        if ($this->_coreRegistry->registry('lists')->getId()) {
            return __("Edit Details '%1'", $this->escapeHtml($this->_coreRegistry->registry('lists')->getTitle()));
        } else {
            return __('New Details');
        }
    }
}

in above file imp code is

$this->_mode = 'details';

and finally app\code\Sugarcode\Test\Block\Adminhtml\Lists\Details\Form.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sugarcode\Test\Block\Adminhtml\Lists\Details;

/**
 * Adminhtml cms block edit form
 */
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
    /**
     * @var \Magento\Cms\Model\Wysiwyg\Config
     */
    protected $_wysiwygConfig;


    /**
     * @var \Sugarcode\Test\Model\Status
     */
    protected $_status;


    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Data\FormFactory $formFactory
     * @param \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig
     * @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\Cms\Model\Wysiwyg\Config $wysiwygConfig,
        \Sugarcode\Test\Model\Status $status,
        array $data = []
    ) {
        $this->_wysiwygConfig = $wysiwygConfig;
        $this->_status = $status;
        parent::__construct($context, $registry, $formFactory, $data);
    }

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

    /**
     * Prepare form
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        $model = $this->_coreRegistry->registry('lists');

        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create(
            ['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']]
        );

        $form->setHtmlIdPrefix('block_');

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

        if ($model->getId()) {
            $fieldset->addField('id', 'hidden', ['name' => 'id']);
        }

        $fieldset->addField(
            'title',
            'text',
            ['name' => 'title', 'label' => __('Block Title'), 'title' => __('Block Title'), 'required' => true]
        );



        $fieldset->addField(
            'status',
            'select',
            [
                'label' => __('Status'),
                'title' => __('Status'),
                'name' => 'status',
                'required' => true,
                'options' => $this->_status->getOptionArray(),
            ]
        );
        if (!$model->getId()) {
            $model->setData('status', '1');
        }

       $fieldset->addField(
            'short_summary',
            'editor',
            [
                'name' => 'short_summary',
                'label' => __('Summary'),
                'title' => __('Summary'),
                'style' => 'height:36em',
                'required' => true,
                'config' => $this->_wysiwygConfig->getConfig()
            ]
        );


        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}

above are the two ways of edit for ,
edit is for edit a content with tab and
details is for edit a content without tabs

| improve this answer | |
  • you solution for custom module not for customer tab grid – Nikhil Vaghela Nov 17 '16 at 9:23
1

last Answer show how to add edit form and in this i am showing how to add new tab with grid selections you need to follow last answer after that you need to edit below file for adding grid to new tab in this i just added same grid and gave option to slect it so i created one field called in_lists_grid of text filed

then i edited app\code\Sugarcode\Test\view\adminhtml\layout\test_lists_edit.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>
        <css src="jquery/fileUploader/css/jquery.fileupload-ui.css"/>
    </head>
    <update handle="editor"/>
    <body>
        <referenceContainer name="left">
            <block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tabs" name="list_post_edit_tabs">
                <block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Main" name="list_post_edit_tab_main"/>
                <action method="addTab">
                    <argument name="name" xsi:type="string">main_section</argument>
                    <argument name="block" xsi:type="string">list_post_edit_tab_main</argument>
                </action>
            </block>
        </referenceContainer>
        <referenceContainer name="content">
            <block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Gridlists" name="adminhtml.tests.lists.tabs.grid.js" template="Sugarcode_Test::lists/tabs_grid_js.phtml"/>
            <block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit" name="list_post_edit"/>
        </referenceContainer>
    </body>
</page>

just i added one more block in content xml that is

<block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Gridlists" name="adminhtml.tests.lists.tabs.grid.js" template="Sugarcode_Test::lists/tabs_grid_js.phtml"/>

then i added Gridlists.php block \app\code\Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Gridlists.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab;

/**
 *
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class Gridlists extends \Magento\Backend\Block\Widget\Tabs
{
    /**
     * User model factory
     *
     * @var \Magento\User\Model\Resource\User\CollectionFactory
     */


    protected $_testFactory; 

    protected $_objectManager;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder
     * @param \Magento\Backend\Model\Auth\Session $authSession
     * @param \Magento\User\Model\Resource\User\CollectionFactory $userCollectionFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Json\EncoderInterface $jsonEncoder,
        \Sugarcode\Test\Model\TestFactory $testFactory,
        \Magento\Backend\Model\Auth\Session $authSession,
        \Sugarcode\Test\Model\Resource\Test\CollectionFactory $userCollectionFactory,
        array $data = []
    ) {
        // _userCollectionFactory is used in parent::__construct
        $this->_testFactory = $testFactory;
        $this->_objectManager = $objectManager;
        $this->_jsonEncoder = $jsonEncoder;
        parent::__construct($context, $jsonEncoder, $authSession, $data);
    }

    /**
     * Class constructor
     *
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $id = $this->getRequest()->getParam('id', false);
       // $this->setTemplate('lists/lists.phtml')->assign('alists', [1]);
      //$this->assign('alists', $this->getAlists())->assign('id', $id);

    }

    /**
     * @return $this
     */
    protected function _prepareLayout()
    {
        $this->setChild(
            'listsGrid',
            $this->getLayout()->createBlock('Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Gridtabs', 'listsTabsGrid')
        );
        return parent::_prepareLayout();
    }

    /**
     * @return string
     */
    public function getGridHtml()
    {
        return $this->getChildHtml('listsGrid');
    }

}

same way i created a grid for this app\code\Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Gridtabs.php

<?php

namespace Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab;


use Magento\Backend\Block\Widget\Grid\Column;


class Gridtabs  extends \Magento\Backend\Block\Widget\Grid\Extended
{/**
     * @var \Magento\Framework\Module\Manager
     */
    protected $moduleManager;

    protected $_testFactory; 

    protected $_objectManager;

    protected $_status;

    /**
     * @var \Magento\Framework\Json\EncoderInterface
     */
    protected $_jsonEncoder;

    //protected $_template = 'lists/tabs_grid_js.phtml';

    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Sugarcode\Test\Model\TestFactory $testFactory,
        \Sugarcode\Test\Model\Status $status,
        \Magento\Framework\Json\EncoderInterface $jsonEncoder,
        \Magento\Framework\Module\Manager $moduleManager,
        array $data = []
    ) {
        $this->_testFactory = $testFactory;
        $this->_status = $status;
        $this->moduleManager = $moduleManager;
        $this->_objectManager = $objectManager;
        $this->_jsonEncoder = $jsonEncoder;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('listsGrid');
        $this->setDefaultSort('id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        $this->setVarNameFilter('lists_filter');
    }

    /**
     * @return $this
     */
    protected function _prepareCollection()
    {
        $collection = $this->_testFactory->create()->getCollection();
        $this->setCollection($collection);

        parent::_prepareCollection();
        return $this;
    }

    protected function _addColumnFilterToCollection($column)
    {

    if ($column->getId() == 'in_lists_gridtabs') {
            $inlistsIds = $this->getAlists();

            if (empty($inlistsIds)) {
                $inlistsIds = 0;
            }
            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('id', ['in' => $inlistsIds]);
            } else {
                if ($inlistsIds) {
                    $this->getCollection()->addFieldToFilter('id', ['nin' => $inlistsIds]);
                }
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }
        return $this;
    }
    public function getAlists($json = false)
    {

         //       return [1];
        $id=$this->getRequest()->getParam('id');
        $collection = $this->_testFactory->create()->setId($id);
        $listso = $this->_objectManager->create('Sugarcode\Test\Model\Test')->load($id);
        $collection=unserialize($listso->getInListsGrid());

        if (sizeof($collection) > 0) {
            if ($json) {
                $jsonLists = [];
                foreach ($collection as $usrid) {
                    $jsonLists[$usrid] = 0;
                }
                return $this->_jsonEncoder->encode((object)$jsonLists);
            } else {
                return array_values($collection);
            }
        } else {
            if ($json) {
                return '{}';
            } else {
                return [];
            }
        }

    }  


    public function isReadonly()
    {
        return false;
    }

    /**
     * @return $this
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function _prepareColumns()
    {
         $this->addColumn(
            'in_lists_gridtabs',
            [
                'header_css_class' => 'a-center',
                'type' => 'checkbox',
                'name' => 'in_lists_gridtabs',
                'values' => $this->getAlists(),
                'align' => 'center',
                'index' => 'id'
            ]
        );
         $this->addColumn(
            'lists_id',
            [
                'header' => __('ID'),
                'type' => 'number',
                'index' => 'id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id',
                'name'=>'lists_id'
            ]
        );  
        $this->addColumn(
            'lists_title',
            [
                'header' => __('Title'),
                'index' => 'title',
                'class' => 'xxx',
                'name'=>'lists_title'
            ]
        );

        $this->addColumn(
            'lists_created_at',
            [
                'header' => __('Created Date'),
                'index' => 'created_at',
                'name'=>'lists_created_at'
            ]
        );


        $this->addColumn(
            'lists_status',
            [
                'header' => __('Status'),
                'index' => 'status',
                'type' => 'options',
                'name'=>'lists_status',
                'options' => $this->_status->getOptionArray()
            ]
        );


        return parent::_prepareColumns();
    }


    /**
     * @return string
     */
    public function getGridUrl()
    {
        $id = $this->getRequest()->getParam('id');
        return $this->getUrl('*/*/gridtabs', ['id' => $id]);
    }


    /**
     * Prepare label for tab
     *
     * @return \Magento\Framework\Phrase
     */
    public function getTabLabel()
    {
        return __('Test Grid');
    }

    /**
     * Prepare title for tab
     *
     * @return \Magento\Framework\Phrase
     */
    public function getTabTitle()
    {
        return __('Test Grid');
    }

    /**
     * {@inheritdoc}
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isHidden()
    {
        return false;
    }

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

you need to add two hidden filed in form for that you need to add in form so edit Main.php

app\code\Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Main.php :-

protected function _prepareForm(){ .
.
.
.
.
old code where you add fileds in last add below code

$fieldset->addField('in_lists_grid', 'hidden', ['name' => 'in_lists_grid', 'id' => 'in_lists_gridz']);

$fieldset->addField('in_lists_grid_old', 'hidden', ['name' => 'in_lists_grid_old']);

for check box action you need to create js so i created app\code\Sugarcode\Test\view\adminhtml\templates\lists\tabs_grid_js.phtml

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<script>
require([
    'jquery',
    'mage/adminhtml/grid',
    'prototype'
], function(jQuery){

<!--
<?php $myBlock = $block->getLayout()->getBlock('listsTabsGrid'); ?>
<?php if (is_object($myBlock) && $myBlock->getJsObjectName()): ?>
    var checkBoxes = $H(<?php echo $myBlock->getAlists(true) ?>);
    var warning = false;
    if (checkBoxes.size() > 0) {
        warning = true;
    }
    jQuery('#in_lists_grid').val(checkBoxes.toQueryString());

    function registerlistsTabs(grid, element, checked)
    {
        if (checked) {
            checkBoxes.set(element.value, 0);
        } else {
            checkBoxes.unset(element.value);
        }
        $('in_lists_grid').value = checkBoxes.toQueryString();
        grid.reloadParams = {'in_lists_grid[]':checkBoxes.keys()};
    }

    function listsTabsRowClick(grid, event)
    {
        var trElement = Event.findElement(event, 'tr');
        var isInput   = Event.element(event).tagName == 'INPUT';
        if (trElement) {
            var checkbox = Element.getElementsBySelector(trElement, 'input');
            if(checkbox[0]){
                var checked = isInput ? !checkbox[0].checked : checkbox[0].checked;
                if (checked) {
                    if ( confirm("<?php echo __('Warning!\r\nThis action will remove those lists from already assigned list\r\nAre you sure?') ?>") ) {
                        checkbox[0].checked = false;
                        checkBoxes.unset(checkbox[0].value);
                        varienElementMethods.setHasChanges(checkbox[0]);
                    } else {
                        checkbox[0].checked = true;
                    }
                } else {
                    checkbox[0].checked = true;
                    checkBoxes.set(checkbox[0].value, true);
                }

                $('in_lists_grid').value = checkBoxes.toQueryString();
                grid.reloadParams = {'in_lists_grid[]':checkBoxes.keys()};
            }
        }
    }

    function listsTabsRowInit(grid, row)
    {
        var checkbox = $(row).getElementsByClassName('checkbox')[0];
        if (checkbox) {
            if (checkbox.checked) {
                checkBoxes.set(checkbox.value, checkbox.checked);
            } else {
                checkBoxes.unset(checkbox.value);
            }

            $('in_lists_grid').value = checkBoxes.toQueryString();
            grid.reloadParams = {'in_lists_grid[]':checkBoxes.keys()};
        }
    }

    function massSelectUsers(allCheckbox)
    {
        if (!allCheckbox.checked && checkBoxes.size() > 0) {
            if (!confirm("<?php echo __('Warning!\r\nThis action will remove those lists from already assigned list\r\nAre you sure?') ?>") ) {
                allCheckbox.checked = false;
                return false;
            }
        }
        <?php echo $myBlock->getJsObjectName() ?>.rows.each(function(row)
        {
            $(row).getElementsByClassName('checkbox')[0].checked = allCheckbox.checked;
            listsTabsRowInit(<?php echo $myBlock->getJsObjectName() ?>, row);
        });
    }
    Event.observe(window, "load", function(){
        <?php echo $myBlock->getJsObjectName() ?>.rowClickCallback = listsTabsRowClick;
        <?php echo $myBlock->getJsObjectName() ?>.initRowCallback = listsTabsRowInit;
        <?php echo $myBlock->getJsObjectName() ?>.checkboxCheckCallback = registerlistsTabs;
        <?php echo $myBlock->getJsObjectName() ?>.checkCheckboxes = massSelectUsers;
        <?php echo $myBlock->getJsObjectName() ?>.rows.each(function(row){listsTabsRowInit(<?php echo $myBlock->getJsObjectName() ?>, row)});
        $('in_lists_grid_old').value = $('in_lists_grid').value;
    });
<?php endif; ?>
//-->

});
</script>

now grid is ready in side edit tab if you need to serach for that then u need to add two new files that is

app\code\Sugarcode\Test\view\adminhtml\layout\test_lists_gridtabs.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/layout_generic.xsd">
    <update handle="formkey"/>
    <container name="root" label="Root">
        <block class="Sugarcode\Test\Block\Adminhtml\Lists\Edit\Tab\Gridtabs" name="post_tabs_test_grid_content"/>
    </container>
</layout>

and controller app\code\Sugarcode\Test\Controller\Adminhtml\Lists\Gridtabs.php

class Gridtabs extends  \Magento\Backend\App\Action
{
    /**
     * Queue list Ajax action
     *
     * @return void
     */
    public function execute()
    {
       $this->_view->loadLayout(false);
        $this->_view->getLayout()->getMessagesBlock()->setMessages($this->messageManager->getMessages(true));
        $this->_view->renderLayout();
    }
}

:-)

| improve this answer | |
  • Hello can you provide Sugarcode/Test module zip so we will get proepr idea – MagikVishal Dec 8 '15 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.