Magento 2 Training : Unit 5 – Lesson B

Admin layout creation

We have to create a layout before create the form :
app/code/Maxime/Jobs/view/adminhtml/layout/jobs_department_edit.xml

Put this little content :

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="editor"/>
    <body>
        <referenceContainer name="content">
            <block class="Maxime\Jobs\Block\Adminhtml\Department\Edit" name="jobs_department_edit"/>
        </referenceContainer>
    </body>
</page>

We define a block inside, so we will create it.

Edit block creation

Add the file :
app/code/Maxime/Jobs/Block/Adminhtml/Department/Edit.php

With this code inside :

<?php
namespace Maxime\Jobs\Block\Adminhtml\Department;

use Magento\Backend\Block\Widget\Form\Container;

class Edit extends 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);
    }

    /**
     * Department edit block
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_objectId = 'entity_id';
        $this->_blockGroup = 'Maxime_Jobs';
        $this->_controller = 'adminhtml_department';

        parent::_construct();

        if ($this->_isAllowedAction('Maxime_Jobs::department_save')) {
            $this->buttonList->update('save', 'label', __('Save Department'));
            $this->buttonList->add(
                'saveandcontinue',
                [
                    'label' => __('Save and Continue Edit'),
                    'class' => 'save',
                    'data_attribute' => [
                        'mage-init' => [
                            'button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form'],
                        ],
                    ]
                ],
                -100
            );
        } else {
            $this->buttonList->remove('save');
        }

    }

    /**
     * Get header with Department name
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {
        if ($this->_coreRegistry->registry('jobs_department')->getId()) {
            return __("Edit Department '%1'", $this->escapeHtml($this->_coreRegistry->registry('jobs_department')->getName()));
        } else {
            return __('New Department');
        }
    }

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

The first construct is usual and you know it.
The second is different and have only one underscore. It is called after the first (wich have 2 underscores)
Inside we display or not the save button accorting to the ACL.
We add another button “Save & Continue edit”.

The “getHeaderText” method is called by the parent class method “getHeaderHtml”.
On the page display, it is not used, but we set it.
To finish, the “_getSaveAndContinueUrl” return the edition URL to redirect the user.

Last, but not least, the form creation !

Admin form creation

Create the file :
app/code/Maxime/Jobs/Block/Adminhtml/Department/Edit/Form.php

With the following content :

<?php
namespace Maxime\Jobs\Block\Adminhtml\Department\Edit;

use \Magento\Backend\Block\Widget\Form\Generic;

class Form extends Generic
{

    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $_systemStore;

    /**
     * @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;
        parent::__construct($context, $registry, $formFactory, $data);
    }

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

    /**
     * Prepare form
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        /** @var \Maxime\Jobs\Model\Department $model */
        $model = $this->_coreRegistry->registry('jobs_department');

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

        $form->setHtmlIdPrefix('department_');

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

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

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

        $fieldset->addField(
            'description',
            'textarea',
            ['name' => 'description', 'label' => __('Department Description'), 'title' => __('Department Description'), 'required' => true]
        );

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

        return parent::_prepareForm();
    }
}

To sum up, we create the form and two fields :
– “Name”, text input
– “Description”, textarea

If we are on edition mode, we add an hidden field with the ID of the element.

Now you can add a lot of departments !!

formedition

We will delete it on the next part 😉

Continue training
Return to previous lesson
Layouts and forms on Magento 2 admin
Tagged on:         

3 thoughts on “Layouts and forms on Magento 2 admin

  • 09/21/2016 at 04:58
    Permalink

    When i click ‘Add New’ button or ‘Edit’, it redirect to blank page. How to solve this problem?

    Reply
  • 08/19/2020 at 09:08
    Permalink

    Hi, i fallowed your module save and continue not working

    Reply

Leave a Reply to Riki Delfian Cancel reply

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

We use cookies to ensure that we give you the best experience on our website.
Ok