I want to insert data in custom table "outofstockproductnotification". But before insert data, I want to check if some data like email id and product id is already exist or not in my custom table. I saved it by using this code.
filepath : app/code/Chirag/Stockproduct/view/frontend/templates/form.phtml
/**
* Product view template
*
* @var $block \Magento\Catalog\Block\Product\View
*/
?>
<?php $_helper = $this->helper('Magento\Catalog\Helper\Output'); ?>
<?php $_product = $block->getProduct(); ?>
<?php if (!$_product->isAvailable()): ?>
<div id="emailnotificationstock" class="">
<label for="notification-container-1183">
Subscribe to back in stock notification </label>
<div class="notification-container" id="notification-container-1183">
<form method="post" name="emailnotification" id="emailnotification" action="<?php echo $this->getUrl('stockproduct/index/save'); ?>" >
<div class="input-fields fieldset">
<input name="guest_email" class="input-text amxnotif-guest-email" id="amxnotif-guest-email-1183" size="50" type="email" data-validate="{required:true, 'validate-email':true}" placeholder="Insert your email">
<input type="hidden" name="product_id" value="<?php echo $_product->getId(); ?>">
<input type="hidden" name="createddate" value="<?php echo $date = date('Y-m-d H:i:s'); ?>">
<button type="submit" class="action submit primary">
<span>Submit</span>
</button>
</div>
</form>
</div>
</div>
<?php endif; ?>
file path : app/code/Chirag/Stockproduct/Controller/Index/save.php
namespace Chirag\Stockproduct\Controller\Index;
use Magento\Framework\App\Action\Context;
use Chirag\Stockproduct\Model\TestFactory;
class Save extends \Magento\Framework\App\Action\Action
{
/**
* @var Stockproduct
*/
protected $_test;
public function __construct(
Context $context,
TestFactory $test
) {
$this->_test = $test;
parent::__construct($context);
}
public function execute()
{
$email = $this->getRequest()->getParam('guest_email');
$product = $this->getRequest()->getParam('product_id');
$createddate = $this->getRequest()->getParam('createddate');
//check weather user already register for same product.
//if not exist data than submit data
$test = $this->_test->create();
$test->setEmailid($email);
$test->setProductid($product);
$test->setCreatedAt($createddate);
if($test->save()){
$this->messageManager->addSuccessMessage(__('We will notify you when product is in stock!'));
}else{
$this->messageManager->addErrorMessage(__('Error!! Data was not saved.'));
}
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($_SERVER['HTTP_REFERER']);
return $resultRedirect;
//if data exist than display approprate message
//$this->messageManager->addErrorMessage(__('You already registerd for this product.'));
}
}
In save.php, I want to check if there is emailid and productid is already exist or not in custom table "outofstockproductnotification". Here i put code of two files only. I think you can understand from these. Any help will be appreciate. Thanks.