0
<?php $_product = $block->getProduct(); 
$exPrice=$_product->getData('ex_price');
?>
<?php if ($exPrice == true): ?>
<div class="note_1">
  <p><b style="color: red;">Note:</b> <span style="color: darkblue;">We don't have prices, because the prices depends on the sizes and the quantities</span></p>  
</div>

<div class="product-quote">
    <form class="product-qoute-form" action="quote/crud/save" id="my-form" data-mage-init='{"validation": {}}' method="post">
        <div style="margin-bottom:10px;" class="row"> 
          <div class="col-lg-12 col-md-12">
            <div class="field name required">
                <div class="control">
                  <label for="" class="elementor-field-label">Company Name</label>
                  <input name="company" id="Company Name" title=" Company Name" placeholder="Company Name" value="" type="text" data-validate="{required:true}" aria-required="true" required>
                </div>
              </div>
          </div>
          <div class="col-lg-12 col-md-12">
            <div class="field email required">
              <div class="control">
                <label for="" class="elementor-field-label">Email</label>
                <input name="email" id="email" title="Email" placeholder="Email" value="" type="email" data-validate="{required:true, 'validate-email':true}" aria-required="true" required>
              </div>
            </div>
          </div>
          
        </div>
        <div style="margin-bottom:10px;" class="row"> 
         
          <!-- <div class="col-lg-6 col-md-6">
            <div class="field name required">
                <div class="control">
                  <label for="" class="elementor-field-label">Company Name</label>
                  <input name="company" id="Company Name" title=" Company Name" placeholder="Company Name" value="" type="text" data-validate="{required:true}" aria-required="true">
                </div>
              </div>
          </div> -->
          <div class="col-lg-12 col-md-12">
            <div class="field telephone">
              <div class="control">
                <label for="" class="elementor-field-label">Phone</label>
                <input name="telephone" id="telephone" placeholder="Telephone" title="Phone Number" type="text" required>
              </div>
            </div>
          </div>
           <div class="col-lg-12 col-md-12">
             <div class="field name required">
              <div class="control">
                <label for="" class="elementor-field-label">Shipping Country</label>
                <input name="country" id="country" title=" country" placeholder="Country" type="text" data-validate="{required:true}" aria-required="true" required> 
              </div>
            </div>
          </div>
        </div>
      <!--   <div style="margin-bottom:10px;" class="row"> 
          
          <div class="col-lg-12 col-md-12">
            <div class="field name required">
                <div class="control">
                  <label for="" class="elementor-field-label">Width</label>
                  <input name="width" id="width" title=" width" placeholder="Width" value="" type="text" data-validate="{required:true}" aria-required="true" required>
                </div>
              </div>
          </div>
          <div class="col-lg-12 col-md-12">
            <div class="field email required">
              <div class="control">
                <label for="" class="elementor-field-label">Height</label>
                <input name="height" id="height" title=" height" placeholder="Height" value="" type="text" data-validate="{required:true}" aria-required="true" required>
              </div>
            </div>
          </div>
        </div> -->
        <div style="margin-bottom:10px;" class="row"> 
          
          <div class="col-lg-12 col-md-12">
            <div class="field email required">
              <div class="control">
                <label for="" class="elementor-field-label">Quantity</label>
                <input name="quantity" id="Quantity" title=" quantity" placeholder="Quantity" type="text" data-validate="{required:true}" aria-required="true" required>
              </div>
            </div>
          </div>
          <!-- <div class="col-lg-6 col-md-6">
            <div class="field name required">
                <div class="control">
                  <label for="" class="elementor-field-label">Depth</label>
                  <input name="depth" id="Depth" title=" depth" placeholder="Depth" value="" type="text" data-validate="{required:true}" aria-required="true">
                </div>
              </div>
          </div> -->
        </div>
        <div style="margin-bottom:10px;" class="row"> 
          <div class="col-lg-12 col-md-12">
            <div class="field email required">
              <div class="control">
                <label for="" class="elementor-field-label">Your message</label>
                <textarea name="comment" id="comment" placeholder="Your message" title="Your message" cols="5" rows="3" data-validate="{required:true}" aria-required="true" required></textarea>
              </div>
            </div>
          </div>
        </div>
        <div class="action-toolbar">
            <input type="hidden" name="sku" id="sku" value="<?php echo $_product->getSku(); ?>">
            <button id="btnSaveIt" type="submit" title="Submit" class="action primary tocart orange_1">
                <span>Request for Quote</span>
            </button>
        </div>
    </form>
</div>
<!-- <script type="text/x-magento-init">
    {
        "#my-form": {
            "validation": {}
        }
    }
</script> -->
<script type="text/javascript" async defer>
    require(["jquery","mage/mage","Magento_Ui/js/model/messageList"],function($) {
        
        var dataForm = $('#my-form');
        dataForm.mage('validation', {});
        
        $(document).ready(function() {
          
          $("#my-form").on("submit",function(){
             var status = dataForm.validation('isValid'); //validates form and returns boolean
             var get_data=dataForm.serialize();
             // alert($.type(get_data));
              if(status){
                console.log('form is validated'); //form is valid
                
                var comp_name=jQuery("input[name='company']").val();
                var email=jQuery("input[name='email']").val();
                var telephone=jQuery("input[name='telephone']").val();
                var country=jQuery("input[name='country']").val();
                var quantity=jQuery("input[name='quantity']").val();
                var msg=jQuery("#comment").val();
                // console.log(msg);            
                var sku=jQuery("input[name='sku']").val();
                var url = "<?php echo $this->getUrl().'quote/crud/save'?>";            
                jQuery.ajax({
                   url: url,
                   type: "post",
                   // dataType: "text",
                   // data:{quote:get_data},
                   data: {company:comp_name,email:email,telephone:telephone,country:country,quantity:quantity,comment:msg,sku:sku},
                   showLoader: true,
                   cache: false,
                   success: function(data){
                      if(data.response == 'added'){ // if true (1)
                          // setTimeout(function(){// wait for 5 secs(2)
                          //      window.location.reload(); // then reload the page.(3)
                          // }, 1000);
                          $("#my-form")[0].reset();
                          console.log('success');
                            // messageList.addSuccessMessage({
                            //   message: 'Quote Email Confirmation is successully sent'
                            // });
                          // alert('success'); 
                       }else{
                          alert('success is wrong'); 
                       }
          
                    },
                     error: function (error) {
                        console.log(error, "fail");
                     }
                });
                return false;
              }else{
              console.log('form is not validated');
              }
          });
        });
    });
</script>
<style type="text/css" media="screen">
.product-add-form{
  display: none;
}
.price-box{
  display: none;
}
.availability.only{
  display: none;
}
.product-info-main .product-info-stock-sku .attribute.sku {
     float: none !important; 
}
.action-toolbar{
  text-align: center;
}
.note_1{
  margin-top: 20px;
}
.note_1 p{
  font-size: 1.5rem;
}
</style>
<?php endif; ?>

2 Answers 2

0

Please check below code i have make custom form and saved in custom table.Below code is as per my requirement. So Please controller and model code and parameter name change as per your.

.phtml file custom form code

<div class="col-sm-8">
        <form method="POST" action="<?= $this->getUrl('mcf/index/save'); ?>" id="mcf" role="form" name="RegForm" enctype="multipart/form-data" data-mage-init='{"validation":{"rules": {"field-2": {"required":true}}}}'>
            <div class="form-group">
                <h2>Form</h2>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your Name') ?></span></label>
                <input id="name" name="name" type="text" class="form-control" data-validate='{"required":true}'>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your FirstName') ?></span></label>
                <input id="firstname" name="firstname" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your LastName') ?></span></label>
                <input id="lastname" name="lastname" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your  Address') ?></span></label>
                <input id="address" name="address" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label" for="field-2"><span><?= $block->escapeHtml('Your Mobile Number') ?></span></label>
                <input id="mo_number" name="mo_number" type="text" class="form-control" data-validate='{"required":true, "validate-number": true}'>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Gender') ?></span></label><br>
                <input type="radio" name="gender" value="male" checked>Male<br>
                <input type="radio" name="gender" value="female">FeMale<br>
                <input type="radio" name="gender" value="other">Other<br>
            </div>
            <div class="actions-toolbar">
                <div class="primary">
                    <button type="submit" title="Submit" id="mcf-btn" class="action submit primary" data-mage-init='{"mcf_js":{}}'>
                        <span>Submit</span>
                    </button>
                </div>
            </div>
        </form>
    </div>

Mag\MCF\view\frontend\requirejs-config.js

var config = {
    map: {
        '*':{
                mcf_js:'Mag_MCF/js/mcf_js',
            }
        },
    shim:{
            'mcf_js':{
                                 deps: ['jquery']
                             }
        }
};

Mag\MCF\view\frontend\web\js\mcf_js.js

define(["jquery", "domReady!","mcf_js"], function($,dom,mcf_js){

    $(document).on('click', '#mcf-btn', function(e){
        var ajxurl = $('#mcf').attr('action');
        var formdata = new FormData(jQuery('#mcf')[0]);
        $.ajax({
            url: ajxurl,
            type: "POST",
            cache: false,
            contentType: false,
            processData: false,
            data: formdata,
            showLoader: true,
            success: function(data){
                location.reload();
                alert("Save");
            }
        });
        e.preventDefault();
    });

})

To handle the POST method in your controller class, you have to implement the Magento\Framework\App\Action\HttpPostActionInterface

Your Controller file

<?php

namespace Mag\MCF\Controller\Index;

use Mag\MCF\Model\McfFactory;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;

class Save extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface
{
    protected $_mcfFactory;
    private $logger;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        McfFactory $mcfFactory
    ) {
        $this->_mcfFactory = $mcfFactory;
        parent::__construct($context);
    }
    public function execute()
    {
        $post_data = $this->getRequest()->getPostValue();
        try {
            $Mcfdata = $this->_mcfFactory->create();
            $Mcfdata->setData($post_data);
            $Mcfdata->save();
            $this->messageManager->addSuccess(__("Save Data"));
        } catch (\Exception $e) {
            $this->messageManager->addError(__('please try again. Form Not Submit'));
        }
    }
}

UPDATE

Mag\MCF\Model\DataExample.php

<?php 
namespace Mag\MCF\Model;
class DataExample extends \Magento\Framework\Model\AbstractModel{
    public function _construct(){
        $this->_init("Mag\MCF\Model\ResourceModel\DataExample");
    }
}
 ?>

Mag\MCF\Model\ResourceModel\DataExample.php

<?php 
namespace Mag\MCF\Model\ResourceModel;
class DataExample extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb{
 public function _construct(){
 $this->_init("data_example","id");
 }
}
 ?>

Mag\MCF\Model\ResourceModel\Collection.php

<?php 
namespace Mag\MCF\Model\ResourceModel\DataExample;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection{
    public function _construct(){
        $this->_init("Mag\MCF\Model\DataExample","Mag\MCF\Model\ResourceModel\DataExample");
    }
}
 ?>

THANKS.

6
  • Thanks Mohit for helpul comment can you share the model code
    – Mage2
    Jan 1 at 19:49
  • @MoazzamS i have updated my answer please check and let me know if any query. Jan 2 at 5:24
  • Thanks Mohit if i have any problem then i will share you
    – Mage2
    Jan 2 at 13:49
  • Yes sure you will share. Jan 2 at 14:01
  • Hi mohit i want to add admin grid in admin panel have you admin grid code for this form
    – Mage2
    Jan 3 at 12:55
0

Here is my code for save the form data in db

<?php
    namespace Form\Quote\Controller\Crud;
    
    use Magento\Framework\Controller\ResultFactory;
    use Form\Quote\Model\QuoteFormFactory;
    class Save extends \Magento\Framework\App\Action\Action
    {
        /**
         * @var contact
         */
        protected $context;
        protected $resultFactory;
        protected $messageManager;
        protected $_quoteFactory;
        public function __construct(
            \Magento\Framework\App\Action\Context $context,
            \Magento\Framework\Message\ManagerInterface $messageManager,
            QuoteFormFactory $quoteFactory,
            \Form\Quote\Helper\Data $helper
        ) {
            parent::__construct($context);
            $this->_helper = $helper;
            $this->messageManager = $messageManager;
            $this->_quoteFactory = $quoteFactory;
            // $this->_resultFactory = $resultFactory;
        }
    
        public function execute()
        {
            $Data=array();
    
            // 1. POST request : 
            $post = (array) $this->getRequest()->getPost();
            // var_dump($post);
            // die();
            if (!empty($post)) {
                // Retrieve your form data
                // Doing-something with...
    
                // Display the succes form validation message
                $Data['sku']=$post['sku'];
                // $Data['name']=$post['name'];
                $Data['email']=$post['email'];
                $Data['telephone']=$post['telephone'];
                $Data['company']=$post['company'];
                $Data['country']=$post['country'];
                $Data['quantity']=$post['quantity'];
                $Data['comment']=$post['comment'];
                $quoteData = $this->_quoteFactory->create();
                $quoteData->setData($Data);
                $quoteData->save();
                $this->_helper->sendEmail($Data);            
                $this->messageManager->addSuccessMessage('Quote Email Confirmation is successully sent');
                // we are using ajax in phtml for checking the response of form 
                if (!empty($Data)) {
                    $response="added";
                }else{
                    $response="not added";
                }
                $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_JSON);
                $resultRedirect->setData([
                    "response" => $response
                    // 'success' => true,
                    // 'message' => $this->messageManager->addSuccess("Quote Email Confirmation is successully sent")
                ]);
                return $resultRedirect;
                
                // die();
    
                //  // Redirect to your form page (or anywhere you want...)
                $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
                // $resultRedirect->setUrl('/crud/save/');
                // reload the cotroller on same page means preveius page
                $resultRedirect->setUrl($this->_redirect->getRefererUrl());
                return $resultRedirect;
                }
            // 2. GET request : Render the booking page 
                $this->_view->loadLayout();
                $this->_view->renderLayout();
        }
    }

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.