3

I have created a custom button in UI component magento2 I want to have post data ( id ) on button click in controller

Button in UI Component

<item name="combinations" xsi:type="string">Vendor\Module\Block\Adminhtml\Form\Buttons\CombinationButton</item>

Block

class CombinationButton extends GenericButton implements ButtonProviderInterface
{
 
    /**
     * @return array
     */
    public function getButtonData()
    {
        return [
            'label' => __('Generate Combinations'),
            'on_click' => sprintf("location.href = '%s';", $this->getUrl()),
            'class' => 'action-secondary',
            'data_attribute' => [
                'mage-init' => [
                    'buttonAdapter' => [
                        'actions' => [
                            [
                                'targetName' => 'hairforadmin_formula_form.hairforadmin_formula_form',
                                'actionName' => 'generatecombinations',
                                'params' => [
                                    false
                                ]
                            ]
                        ]
                    ]
                ]
            ],
            'sort_order' => 100
        ];
    }
 
    /**
     * Get URL for back (reset) button
     *
     * @return string
     */
    public function getUrl()
    {
        return $this->getUrl('*/*/generatecombinations');
    }
}

Controller

class GenerateCombinations extends Action

{

private $modelFactory;

public function __construct(Context $context, FormulaFactory $modelFactory)
{
    $this->modelFactory = $modelFactory;
    parent::__construct($context);
}

public function execute()
{
    $id = $this->getRequest()->getParam('formula_id');

    echo "<pre>";
    print_r($id);
    exit;
}
}
1
  • any update on this? Commented Dec 13, 2023 at 6:55

1 Answer 1

0

I did it using my custom form

Layout File adminFrontname_controller_action

<?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="styles"/>
    <update handle="editor"/>
    <head>
        <css src="Vendor_Module::css/style.css"/>
    </head>
    <body>
        <referenceContainer name="content">
        <block class="Vendor\Module\Block\Adminhtml\Block\Edit\Form" name="edit_contact2" template="Vendor_Module::block.phtml"/> 
        </referenceContainer>
    </body>
</page>

Controller

<?php
namespace Vendor\Module\Controller\Adminhtml\Block;
use Magento\Framework\Controller\ResultFactory;

class NewAction extends \Magento\Backend\App\Action {

    protected $resultPageFactory ;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        parent::__construct( $context );
        $this->resultPageFactory = $resultPageFactory;
    }

    public function execute() {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend( ( __( 'Manage CustomBlock' ) ) );
        return $resultPage;
    }
}

Block

<?php

namespace Vendor\Module\Block\Adminhtml\Block\Edit;
use Vendor\Module\Model\CustomBlockFactory;
use Vendor\Module\Model\ResourceModel\Field;
use Magento\Store\Model\System\Store;

class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
    protected $_coreRegistry;
    protected $_gridFactory;
    protected $_systemStore;
    protected $_required_options;
    protected $_optionsFactory;
    protected $modelFactory;
    protected $_scopeConfig;
    private $_bannerRm;
    protected $_storeManager;


    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        CustomBlockFactory $modelFactory,
        Field $bannerRm,
        Store $systemStore,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Data\FormFactory $formFactory,
        array $data = []
    ) {
        parent::__construct($context, $registry, $formFactory, $data);
        $this->_coreRegistry = $registry;
        $this->_systemStore = $systemStore;
        $this->modelFactory = $modelFactory;
        $this->_bannerRm = $bannerRm;
        $this->_storeManager = $storeManager;
        $this->_scopeConfig = $context->getScopeConfig();
    }

    public function getBlock($blockId) {
        $model = $this->modelFactory->create()->load($blockId);
        if($model->getData()) {
            return $model->getData();
        }
        return [];
    }

    public function getFieldsByBlockId($blockId) {
        $fields = $this->_bannerRm->getFieldsByBlockId($blockId);
        return $fields;
    }
    public function getCardFields($blockId,$cardId) {
        $fields = $this->_bannerRm->getCardFields($blockId,$cardId);
        return $fields;
    }   

    public function getBaseImageUrl()
    {
        $mediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        $imageUrl = $mediaUrl.'fme/customblock';
        return $imageUrl;
    }

    public function getStoreOptions()
    {
        $stores = $this->_storeManager->getStores();
        $storeOptions = ['0' => 'All Store Views']; // Add the default option
        foreach ($stores as $store) {
            $storeOptions[$store->getId()] = $store->getName();
        }
        return $storeOptions;
    }

}

My Template File

<?php
$params  = $this->getRequest()->getParams();
$blockId = isset($params['block_id']) ? $params['block_id'] : '';
$baseMediaurl = $this->getBaseImageUrl();
$count = 0;
?>

<div class="page-main-actions">
   <div class="page-actions-placeholder"></div>
   <div class="page-actions" data-ui-id="page-actions-toolbar-content-header">
      <div class="page-actions-inner" data-title="New Customer">
         <div class="page-actions-buttons">
            <button id="back" title="Back" type="button" class="action- scalable back" ui-button-widget-hook-id="buttonIdiHMgFHjdv6">
            <span>Back</span>
            </button>
            <button id="save" title="Save Block" type="button" class="action- scalable save primary ui-button ui-corner-all ui-widget" data-form-role="save" ui-button-widget-hook-id="buttonIdt6bFjhJr3W" data-ui-id="save-button" onClick="submitForm()">
            <span>Save Block</span>
            </button>
         </div>
      </div>
   </div>
</div>
<form  method="post" action="<?php echo $this->getUrl('blocksadmin/block/save', ['_secure' => true]);?>" enctype="multipart/form-data" class="custom_form" id="custom_form">
   //form fields
</form>
<script>
function submitForm() {
    var form = document.getElementById('custom_form');
    var messagesContainer = document.getElementById('messages');

    if (form.checkValidity()) {
        form.submit();
    } else {
        var errorMessage = 'Please fill in all required fields.';
        messagesContainer.innerHTML = '<div class="messages"><div class="message message-error error"><div data-ui-id="messages-message-error">' + errorMessage + '</div></div></div>';
        window.scrollTo(0, 0);
        setTimeout(function() {
            messagesContainer.innerHTML = ''; 
        }, 4000);
    }
}
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.