0

I using admin form from this example

But i want change modelFactory from model to repository

But i don`t know how do it.

I need to change this files from model to repository

    <?php

namespace Jeff\Contacts\Controller\Adminhtml\Index;

use Exception;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Jeff\Contacts\Model\ContactFactory;

class Delete extends Action
{

    const ADMIN_RESOURCE = 'Index';

    protected $resultPageFactory;
    protected $contactFactory;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        ContactFactory $contactFactory
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->contactFactory = $contactFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $id = $this->getRequest()->getParam('id');

        $contact = $this->contactFactory->create()->load($id);

        if(!$contact)
        {
            $this->messageManager->addError(__('Unable to process. please, try again.'));
            $resultRedirect = $this->resultRedirectFactory->create();
            return $resultRedirect->setPath('*/*/', array('_current' => true));
        }

        try{
            $contact->delete();
            $this->messageManager->addSuccess(__('Your contact has been deleted !'));
        }
        catch(\Exception $e)
        {
            $this->messageManager->addError(__('Error while trying to delete contact'));
            $resultRedirect = $this->resultRedirectFactory->create();
            return $resultRedirect->setPath('*/*/index', array('_current' => true));
        }

        $resultRedirect = $this->resultRedirectFactory->create();
        return $resultRedirect->setPath('*/*/index', array('_current' => true));
    }
}

And this file:


    <?php
namespace Jeff\Contacts\Controller\Adminhtml\Index;
use Exception;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Jeff\Contacts\Model\ContactFactory;

class Save extends Action
{

    const ADMIN_RESOURCE = 'Index';

    protected $resultPageFactory;
    protected $contactFactory;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        ContactFactory $contactFactory
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->contactFactory = $contactFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();

        if($data)
        {
            try{
                $id = $data['jeff_contacts_contact_id'];

                $contact = $this->contactFactory->create()->load($id);

                $data = array_filter($data, function($value) {return $value !== ''; });

                $contact->setData($data);
                $contact->save();
                $this->messageManager->addSuccess(__('Successfully saved the item.'));
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
                return $resultRedirect->setPath('*/*/');
            }
            catch(Exception $e)
            {
                $this->messageManager->addError($e->getMessage());
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData($data);
                return $resultRedirect->setPath('*/*/edit', ['id' => $contact->getId()]);
            }
        }

        return $resultRedirect->setPath('*/*/');
    }
}
4
  • did you make repository class? Commented Nov 18, 2020 at 4:16
  • yes i have repository class Commented Nov 18, 2020 at 10:17
  • Does your repository class has required methods i-e delete, save...? Commented Nov 18, 2020 at 10:20
  • i have method delete,save,getbyid,deletebyid Commented Nov 18, 2020 at 11:04

1 Answer 1

0

This is Save controller using Repository:

<?php

namespace Vendor\Module\Controller\Adminhtml\Article;

use Magento\Backend\App\Action;
use \Magento\Backend\Helper\Js;
use Vendor\Module\Model\Article;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Exception\LocalizedException;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var DataPersistorInterface
     */
    protected $dataPersistor;
    protected $_backendJsHelper;

   
    private $articleFactory;
    private $articleRepository;

    /**
     * @param Action\Context $context
     * @param DataPersistorInterface $dataPersistor
     * @param \Vendor\Module\Model\ArticleFactory $articleFactory
     * @param \Vendor\Module\Api\ArticleRepositoryInterface $articleRepository
     */
    public function __construct(
        Action\Context $context,
        DataPersistorInterface $dataPersistor,
        Js $backendJsHelper,
        \Vendor\Module\Model\ArticleFactory $articleFactory = null,
        \Vendor\Module\Api\ArticleRepositoryInterface $articleRepository = null
    ) {
           $this->dataPersistor = $dataPersistor;
           $this->_backendJsHelper = $backendJsHelper;
           $this->articleFactory = $articleFactory
            ?: \Magento\Framework\App\ObjectManager::getInstance()->get(\Vendor\Module\Model\ArticleFactory::class);
           $this->articleRepository = $articleRepository
            ?: \Magento\Framework\App\ObjectManager::getInstance()->get(\Vendor\Module\Api\ArticleRepositoryInterface::class);
            parent::__construct($context);
    }
    
    /**
     * Authorization level
     *
     * @see _isAllowed()
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Vendor_Module::save');
    }

    /**
     * Save action
     *
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @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) {
            if (isset($data['status']) && $data['status'] === 'true') {
                $data['status'] = Article::STATUS_ENABLED;
            }
            if (empty($data['article_id'])) {
                $data['article_id'] = null;
            }

            /** @var \Vendor\Module\Model\Article $model */
            $model = $this->articleFactory->create();

            $id = $this->getRequest()->getParam('article_id');
            if ($id) {
                try {
                    $model = $this->articleRepository->getById($id);
                } catch (LocalizedException $e) {
                    $this->messageManager->addErrorMessage(__('This article no longer exists.'));
                    return $resultRedirect->setPath('*/*/');
                }
            }

            $model->setData($data);

            $this->_eventManager->dispatch(
                'article_article_prepare_save',
                ['article' => $model, 'request' => $this->getRequest()]
            );

            try {
                $this->articleRepository->save($model);
                $this->messageManager->addSuccessMessage(__('You saved the article.'));
                $this->dataPersistor->clear('article_article');
                
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['article_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addExceptionMessage($e->getPrevious() ?:$e);
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the article.'));
            }

            

            $this->dataPersistor->set('article_article', $data);
            return $resultRedirect->setPath('*/*/edit', ['article_id' => $this->getRequest()->getParam('article_id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }
}

Note : My module is related to articles, hope you can change where it's used according to your requirements.

4
  • I don`t can get id from request $data = $this->getRequest()->getPostValue(); if($data) { try{ // $id = $this->getRequest()->getParam ( 'id' ); return "" Commented Nov 18, 2020 at 12:46
  • How about getting this way? $id = $data['jeff_contacts_contact_id'];. I think your param name is different than id. Commented Nov 18, 2020 at 12:52
  • when i create new contact i can get id, I try $id = $data['jeff_contacts_contact_id']; and $ id = $ this-> getRequest () -> getParam ('jeff_contacts_contact_id'); in this cases i get $id = "" Commented Nov 18, 2020 at 13:06
  • That's something to do with the name of param passed ingetParam method. I answered what you asked, using repository instead of modelFactory. Hope that's working fine. Commented Nov 19, 2020 at 4:26

Your Answer

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

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