TransWikia.com

Magento 2 : How to Change Form encoding?

Magento Asked on November 10, 2021

I would like add multipart-form/data to Magento2’s Admin Form.

Vendor/Module/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

 <preference for="MagentoCustomerBlockAdminhtmlGroupEditForm"
 type="VednorModuleBlockAdminhtmlGroupEditForm" />

 </config>

I’ve override below file

magento-customer/Block/Adminhtml/Group/Edit/Form.php

TO

Vendor/Module/Block/Adminhtml/Group/Edit/Form.php

 <?php
 namespace VivekShopAsGroupBlockAdminhtmlGroupEdit;

 use MagentoCustomerControllerRegistryConstants;
 use MagentoBackendBlockWidgetFormGeneric;
 use MagentoFrameworkDataForm as DataForm;


 class Form extends MagentoCustomerBlockAdminhtmlGroupEditForm
 {
protected $formFactory;


public function __construct(

    MagentoFrameworkAppResponseFactory $responseFactory,
    MagentoFrameworkUrlInterface $url,
    MagentoBackendBlockTemplateContext $context,
    MagentoFrameworkRegistry $registry,
    MagentoFrameworkDataFormFactory $formFactory,
    MagentoTaxModelTaxClassSourceCustomer $taxCustomer,
    MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
    MagentoTaxHelperData $taxHelper,
    MagentoStoreModelStoreManagerInterface $storeManager,
    MagentoFrameworkUrlInterface $urlInterface, 
    MagentoFrameworkViewResultLayoutFactory $resultLayoutFactory,
    MagentoCustomerApiDataGroupInterfaceFactory $groupDataFactory,

    array $data = []
) {
    $this->_responseFactory = $responseFactory;
    $this->_url = $url;
    $this->_taxCustomer = $taxCustomer;
    $this->_taxHelper = $taxHelper;
    $this->_storeManager = $storeManager;
    $this->uploaderFactory = $uploaderFactory;
    $this->_urlInterface = $urlInterface;
    $this->formFactory = $formFactory;
    $this->groupDataFactory = $groupDataFactory;
    $this->_resultLayoutFactory = $resultLayoutFactory;
    parent::__construct($context, $registry, $formFactory, $data);
}

protected function _prepareForm()
{
   parent::_prepareForm(); //add this
    /** @var MagentoFrameworkDataForm $form */
   $form = $this->_formFactory->create(
    [
    'data' => [
           'id' => 'edit_form',
           'action' => $this->getData('action'),
           'method' => 'post',
           'enctype' => 'multipart/form-data'
          ]
    ]
);
    $form->setUseContainer(true);
    $this->setForm($form);
    return $this; //chnage this
   }
   }

I did upgrade and Deploy but it not seems to be working for me.

Took reference from Magento StackExchange

What i am missing ? Any Guide..

Thanks in Advance.

4 Answers

  1. Add / Edit custom module's di.xml like below.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="MagentoUserBlockUserEditForm" type="CustomOverrideBlockUserEditForm" />
</config>

  1. Create Preference File at path CustomOverrideBlockUserEditForm.php. Add below code.
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace CustomOverrideBlockUserEdit;

/**
 * Adminhtml permissions user edit form
 *
 * @SuppressWarnings(PHPMD.DepthOfInheritance)
 */
class Form extends MagentoUserBlockUserEditForm
{
    /**
     * @return $this
     */
    protected function _prepareForm()
    {
        parent::_prepareForm();
        /** @var MagentoFrameworkDataForm $form */
        $form = $this->_formFactory->create([
            'data' => 
                [
                    'id' => 'edit_form',
                    'action' => $this->getData('action'),
                    'method' => 'post',
                    'enctype' => 'multipart/form-data' //Updated this
                ]
            ]
        );
        $form->setUseContainer(true);
        $this->setForm($form);
        return $this;
    }
}

Answered by Kazim Noorani on November 10, 2021

Follow below steps

Step:1 Create file di.xml at location xxx/app/code/Vendor/ModuleName/etc/adminhtml/di.xml & add below code.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="MagentoCustomerBlockAdminhtmlGroupEditForm" type="VendorModuleNameBlockAdminhtmlGroupEditForm"/>
</config>

Step:2 Create Form.php file at location xxx/app/code/Vendor/ModuleName/Block/Adminhtml/Group/Edit and add below code in this file.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace VendorModuleNameBlockAdminhtmlGroupEdit;

use MagentoCustomerControllerRegistryConstants;

/**
 * Adminhtml customer groups edit form
 */
class Form extends MagentoCustomerBlockAdminhtmlGroupEditForm
{
    /**
     * @var MagentoTaxModelTaxClassSourceCustomer
     */
    protected $_taxCustomer;

    /**
     * @var MagentoTaxHelperData
     */
    protected $_taxHelper;

    /**
     * @var MagentoCustomerApiGroupRepositoryInterface
     */
    protected $_groupRepository;

    /**
     * @var MagentoCustomerApiDataGroupInterfaceFactory
     */
    protected $groupDataFactory;

    /**
     * @param MagentoBackendBlockTemplateContext $context
     * @param MagentoFrameworkRegistry $registry
     * @param MagentoFrameworkDataFormFactory $formFactory
     * @param MagentoTaxModelTaxClassSourceCustomer $taxCustomer
     * @param MagentoTaxHelperData $taxHelper
     * @param MagentoCustomerApiGroupRepositoryInterface $groupRepository
     * @param MagentoCustomerApiDataGroupInterfaceFactory $groupDataFactory
     * @param array $data
     */
    public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoFrameworkRegistry $registry,
        MagentoFrameworkDataFormFactory $formFactory,
        MagentoTaxModelTaxClassSourceCustomer $taxCustomer,
        MagentoTaxHelperData $taxHelper,
        MagentoCustomerApiGroupRepositoryInterface $groupRepository,
        MagentoCustomerApiDataGroupInterfaceFactory $groupDataFactory,
        array $data = []
    ) {
        parent::__construct(
            $context,
            $registry,
            $formFactory,
            $taxCustomer,
            $taxHelper,
            $groupRepository,
            $groupDataFactory,
            $data
        );
    }

    /**
     * Prepare form for render
     *
     * @return void
     */
    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        /** @var MagentoFrameworkDataForm $form */
        $form = $this->_formFactory->create();

        $groupId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_GROUP_ID);
        /** @var MagentoCustomerApiDataGroupInterface $customerGroup */
        if ($groupId === null) {
            $customerGroup = $this->groupDataFactory->create();
            $defaultCustomerTaxClass = $this->_taxHelper->getDefaultCustomerTaxClass();
        } else {
            $customerGroup = $this->_groupRepository->getById($groupId);
            $defaultCustomerTaxClass = $customerGroup->getTaxClassId();
        }

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

        $validateClass = sprintf(
            'required-entry validate-length maximum-length-%d',
            MagentoCustomerModelGroupManagement::GROUP_CODE_MAX_LENGTH
        );
        $name = $fieldset->addField(
            'customer_group_code',
            'text',
            [
                'name' => 'code',
                'label' => __('Group Name'),
                'title' => __('Group Name'),
                'note' => __(
                    'Maximum length must be less then %1 characters.',
                    MagentoCustomerModelGroupManagement::GROUP_CODE_MAX_LENGTH
                ),
                'class' => $validateClass,
                'required' => true
            ]
        );

        if ($customerGroup->getId() == 0 && $customerGroup->getCode()) {
            $name->setDisabled(true);
        }

        $fieldset->addField(
            'tax_class_id',
            'select',
            [
                'name' => 'tax_class',
                'label' => __('Tax Class'),
                'title' => __('Tax Class'),
                'class' => 'required-entry',
                'required' => true,
                'values' => $this->_taxCustomer->toOptionArray(),
            ]
        );

        if ($customerGroup->getId() !== null) {
            // If edit add id
            $form->addField('id', 'hidden', ['name' => 'id', 'value' => $customerGroup->getId()]);
        }

        if ($this->_backendSession->getCustomerGroupData()) {
            $form->addValues($this->_backendSession->getCustomerGroupData());
            $this->_backendSession->setCustomerGroupData(null);
        } else {
            // TODO: need to figure out how the DATA can work with forms
            $form->addValues(
                [
                    'id' => $customerGroup->getId(),
                    'customer_group_code' => $customerGroup->getCode(),
                    'tax_class_id' => $defaultCustomerTaxClass,
                ]
            );
        }

        $form->setUseContainer(true);
        $form->setId('edit_form');
        $form->setAction($this->getUrl('customer/group/save'));
        $form->setMethod('post');
        $form->setEnctype('multipart/form-data');
        $this->setForm($form);
        return $this;
    }
}

Step:3 After run below commands

php bin/magento setup:di:compile
php bin/magento cache:clean
php bin/magento cache:flush

Note: I have added above code vendor name is Vendor & module name is ModuleName. Please change per your requirement.

Answered by Abdul on November 10, 2021

Try to use this code inside your class:

<?php

namespace VendorModuleBlockAdminhtmlGroupEdit;

class Form extends MagentoCustomerBlockAdminhtmlGroupEditForm
{

    protected function _prepareForm()
    {
       parent::_prepareForm();

       $form = $this->getForm();
       $form->setData('enctype', 'multipart/form-data');
    }
}

Answered by George M on November 10, 2021

IN your Vendor/Module/Block/Adminhtml/Group/Edit/Form.php file change as per below. And add right class for extending

    namespace VendorModuleBlockAdminhtmlGroupEdit;

use MagentoCustomerControllerRegistryConstants;


class Form extends MagentoCustomerBlockAdminhtmlGroupEditForm
{

    protected function _prepareForm()
    {
       parent::_prepareForm(); //add this
        /** @var MagentoFrameworkDataForm $form */
       $form = $this->_formFactory->create(
        [
        'data' => [
               'id' => 'edit_form',
               'action' => $this->getData('action'),
               'method' => 'post',
               'enctype' => 'multipart/form-data'
              ]
        ]
    );
        $form->setUseContainer(true);
        $this->setForm($form);
        return $this; //chnage this
    }
}

Answered by Murtuza Zabuawala on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP