1

When a user clicks the open modal button the popup modal opened correctly.

enter image description here

I want a form in a modal and save the data into the database. please, anyone gives the solution.

0

Form in form.phtml

    <div id="myModel">
        <form action="<?php  echo $block->getBaseUrl().'your path to controller';?>" method="post" id="form_validate contact-form" data-mage-init='{"validation": {}}'>
            <label>Name</label>                
            <input type="text" name="name" id="name" data-validate="{required:true}">
            <label>Quantity </label>
            <input type="number" name="quote_qty" id="quote_qty" data-validate='{"required":true}'>    
            <label>price</label>
            <input type="text" name="quote_price" id="quote_price"  data-validate="{required:true}">
            <label>description</label>
            <input type="text" name="quote_desc" id="quote_desc" data-validate='{"required":true}'>
            <input type="hiddden" name="product_price" id="product_price" hidden>                 
            <button type="submit" id="submit" name="submit">submit</button>
            <button type="reset" name="reset">Reset</button>
        </form>
    </div>   
    <script type="text/x-magento-init">
        {
            "#custom-form": {
                "validation": {}
            }
        }
    </script>

Call this form.phtml into model.phtml

<button  class="open-contact-form">Quote This Product</button>
<div id="popup-modal">
    <div class="contact-form-popup" style="display: none;">
        <?php           
            echo $this->getLayout()
            ->createBlock("Infy\Quotesystem\Block\Quote\Quote" )
            ->setTemplate("Infy_Quotesystem::form.phtml")
            ->toHtml();             
        ?>
    </div>
    <div class="static-block-message" style="display: none;">
    <?php echo 'display error'; ?>
    </div>
</div>
<script>
    require(
    [
    'jquery',
    'Magento_Ui/js/modal/modal'
    ],
        function($, modal) {
            jQuery(document).ready(function(){
                var options = {
                    type: 'popup',
                    responsive: true,
                    innerScroll: true,
                    title: 'Contact Form',
                    buttons: [{
                    text: $.mage.__('Close'),
                    class: '',
                    click: function () {
                    this.closeModal();
                    }
                     }]
                };
                var openModal = modal(options, $('#popup-modal'));

                jQuery('body').on('click', '.open-contact-form', function(){
                    jQuery('.contact-form-popup').show();
                    jQuery('.static-block-message').hide();
                    jQuery('#popup-modal').modal('openModal');
                });

                jQuery('body').on('click', '#contact-form .action.submit', function(e){
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    jQuery.ajax({
                    type: 'post',
                    url: '<?php  echo $block->getBaseUrl().'Your path to controller';?>',
                    data: jQuery('#contact-form').serialize(),
                    cache: false,
                    showLoader: 'true',
                    success: function(data, status, xhr) {
                            // data contains your controller response
                        },
                    error: function (xhr, status, errorThrown) {
                        console.log('Error happens. Try again.');
                        console.log(errorThrown);
                    }
                    });
                    return false;
                });
            });
        }
);
</script>

Create your controller

namespace Vender\Modulename\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory; 

class Controllername extends \Magento\Framework\App\Action\Action
{


    protected $_pageFactory;

    public function __construct(        
        \Magento\Framework\App\Action\Context $context, 
         \Magento\Framework\Controller\ResultFactory $resultFactory,
        \Magento\Framework\View\Result\PageFactory $pageFactory,
         \Infy\Quotesystem\Helper\Data $helperData,
         \Infy\Quotesystem\Model\PostFactory $postFactory
    )
    {
        parent::__construct($context);
        $this->_pageFactory = $pageFactory;
        $this->resultFactory = $resultFactory;
        $this->_postFactory = $postFactory;
        $this->helperData = $helperData;

    }

    public function execute()
    {
        $resultPage = $this->_pageFactory->create();
        $post = $this->getRequest()->getPostValue();    
        $qty = $this->getRequest()->getParam('quote_qty');        
        $price = $this->getRequest()->getParam('quote_price'); 
        $desc = $this->getRequest()->getParam('quote_desc');
        $p_name = $this->getRequest()->getParam('name');
        $p_price = $this->getRequest()->getParam('p_price');

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->create('Magento\Customer\Model\Session');
        if ($customerSession->isLoggedIn()) {            
            $emailcust = $customerSession->getCustomer()->getEmail();            

            $std = $this->_postFactory->create();
            $std->setProduct_quantity($qty);
            $std->setQuotePrice($price);
            $std->setQuoteDescription($desc);
            $std->setProductName($p_name);
            $std->setProduct_price($p_price);
            $std->setCustom_email($emailcust);

            $adminuserId = 1;
            $user1 = \Magento\Framework\App\ObjectManager::getInstance()->create(
            'Magento\User\Model\User');
            $user1->load($adminuserId); 
            $name = $user1->getUsername();
            $email = $user1->getEmail();
            $msg = 'User Add Quote in '.$p_name.' Quote Price is: '.$price;
            $user = $emailcust;
            if ($std->save())
            {
                $sendmail = $this->helperData->sendMail($msg, $user, $p_name, $name, $email);
            }
            else{$this->messageManager->addError(__($e->getMessage()));}


            // $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $resultRedirect = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);
             $resultRedirect->setPath('*/index/*');
            return $resultRedirect;


        }
        else{
          $response = $this->resultFactory
            ->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
            ->setData([
                'status'  => "Incomplete",
                'message' => "Please Login/Register!!"
            ]);

        return $response;

        }   
    }
}
| improve this answer | |
  • Created a Modal Via UI_components Modal Component. where I can put these files and how can connect with the phtml files. – Nishan than Oct 23 '19 at 11:24

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.