Hello I have created admin grid for my custom module, I have a form where it is possible to add new product comments. The thing is that I have Product id field, where u can enter id for which product to post comment. So if non-existent id is entered and saved the page breaks.
This is my save controller:
<?php namespace Vendor\Module\Controller\Adminhtml\Comments; use Magento\Backend\App\Action; use Magebit\ProductComments\Model\Comments; use Magento\Catalog\Api\ProductRepositoryInterface; class Save extends Action { private $ productRepository; protected $ _model; /** * @param Action\Context $ context */ public function __construct( Action\Context $ context, Comments $ model, ProductRepositoryInterface $ productRepository ) { parent::__construct($ context); $ this->_model = $ model; $ this->productRepository = $ productRepository; } /** * {@inheritdoc} */ /** * Save action * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { $ data = $ this->getRequest()->getPostValue(); /** @var \Magento\Backend\Model\View\Result\Redirect $ resultRedirect */ $ resultRedirect = $ this->resultRedirectFactory->create(); if ($ data) { /** @var \Vendor\Module\Model\Comments $ model */ $ model = $ this->_model; $ id = $ this->getRequest()->getParam('id'); if ($ id) { $ model->load($ id); } $ model->setData($ data); $ this->_eventManager->dispatch( 'productcomments_comments_prepare_save', ['comments' => $ model, 'request' => $ this->getRequest()] ); try { $ model->save(); $ this->messageManager->addSuccess(__('Comment successfully saved')); $ this->_getSession()->setFormData(false); if ($ this->getRequest()->getParam('back')) { return $ resultRedirect->setPath('*/*/edit', ['id' => $ model->getId(), '_current' => true]); } return $ resultRedirect->setPath('*/*/'); } catch (\Magento\Framework\Exception\LocalizedException $ e) { $ this->messageManager->addError($ e->getMessage()); } catch (\RuntimeException $ e) { $ this->messageManager->addError($ e->getMessage()); } catch (\Exception $ e) { $ this->messageManager->addException($ e, __('Something went wrong while saving the comment')); } $ this->_getSession()->setFormData($ data); return $ resultRedirect->setPath('*/*/edit', ['comment_id' => $ this->getRequest()->getParam('id')]); } return $ resultRedirect->setPath('*/*/'); } }
I was thinking about using productrepository getByID function, but haven’t yet figured it out. Hope someone will have answers for me, thanks!