0

How to delete the record from my custom table. without using object manager?

Example : delete from customer_comments where comments_id=124

2 Answers 2

7

I think the best way just follow Magento standard. For example just check Cms magento module.

So you have a new module app/code/MyCompany/MyModule

Model/Comment.php

namespace MyCompany\MyModule\Model;

class Comment extends \Magento\Framework\Model\AbstractModel {

    /**
     * @var string
     */
    protected $_cacheTag = 'customer_comment';

    /**
     * @var string
     */
    protected $_eventPrefix = 'customer_comment';

    /**
     * @return void
     */
    protected function _construct()
    {
        $this->_init(\MyCompany\MyModule\Model\ResourceModel\Comment::class);
    }

}

Model/ResourceModel/Comment.php

namespace MyCompany\MyModule\Model\ResourceModel;

class Comment extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb {

    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('you_custom_table_name', 'comment_id');
    }

}

Controller/Comment/Delete.php

namespace MyCompany\MyModule\Controller\Comment;

use MyCompany\MyModule\Model\CommentFactory;

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

    /**
     * @var CommentFactory
     */
    protected $_commentFactory;
    protected $messageManager;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param CommentFactory $commentFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Message\ManagerInterface $messageManager,   
        CommentFactory $commentFactory
    ) {
        $this->_commentFactory = $commentFactory;
        $this->messageManager = $messageManager;
        parent::__construct($context);
    }

    public function execute() 
    {
        $id = $this->getRequest()->getParam('comment_id');
        try {
            $model = $this->_commentFactory->create();
            $model->load($id);
            $model->delete();
        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
        }
    }

}
1
  • 1
    $model->load($id); is not good way. load() is @deprecated because entities must not be responsible for their own loading. Service contracts should persist entities. Use resource model "load" or collections to implement service contract model loading operations. see \Magento\Framework\Model\AbstractModel::load() Jun 18, 2019 at 11:17
0

enter image description herehow to pass argument on button click to delete this id like

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.