Skip to content

Il router personalizzato non funziona in Router.php Magento 2 [SOLVED]

Dopo esserci consultati con specialisti in materia, programmatori di vari rami e docenti, abbiamo trovato la soluzione al dilemma e la presentiamo in questo post.

Soluzione:

Infine, ho RISOLTO il problema.

Nessuna modifica in di.xml.

Di seguito sono riportate le modifiche che ho apportato:

appcodeCustomModuleControllerRouter.php rimosso la condizione di controllo.

namespace CustomModuleController;

use MagentoFrameworkAppActionFactory;
use MagentoFrameworkAppActionForward;
use MagentoFrameworkAppActionRedirect;
use MagentoFrameworkAppConfigScopeConfigInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoFrameworkAppResponseInterface;
use MagentoFrameworkAppRouterInterface;
use MagentoFrameworkAppState;
use MagentoFrameworkDataObject;
use MagentoFrameworkEventManagerInterface;
use MagentoFrameworkUrl;
use MagentoFrameworkUrlInterface;
use MagentoStoreModelScopeInterface;
use MagentoStoreModelStoreManagerInterface;
use CustomModuleModelRoutingEntity;
use MagentoFrameworkControllerResultFactory;

class Router implements RouterInterface {

    /**
     * @var MagentoFrameworkAppActionFactory
     */
    protected $actionFactory;

    /**
     * Event manager
     * @var MagentoFrameworkEventManagerInterface
     */
    protected $eventManager;

    /**
     * Store manager
     * @var MagentoStoreModelStoreManagerInterface
     */
    protected $storeManager;

    /**
     * Posts factory
     * @var CustomModuleModelPostsFactory
     */
    protected $postsFactory;

    /**
     * Config primary
     * @var MagentoFrameworkAppState
     */
    protected $appState;

    /**
     * Url
     * @var MagentoFrameworkUrlInterface
     */
    protected $url;

    /**
     * Response
     * @var MagentoFrameworkAppResponseInterface|MagentoFrameworkAppResponseHttp
     */
    protected $response;

    /**
     * @var MagentoFrameworkAppConfigScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var bool
     */
    protected $dispatched;

    /**
     * @var CustomModuleModelRoutingEntity[]
     */
    protected $routingEntities;

    /**
     * @param ActionFactory $actionFactory
     * @param ManagerInterface $eventManager
     * @param UrlInterface $url
     * @param State $appState
     * @param StoreManagerInterface $storeManager
     * @param ResponseInterface $response
     * @param ScopeConfigInterface $scopeConfig
     * @param array $routingEntities
     */
    public function __construct(
    ActionFactory $actionFactory, ManagerInterface $eventManager, UrlInterface $url, State $appState, StoreManagerInterface $storeManager, ResponseInterface $response, ScopeConfigInterface $scopeConfig, ResultFactory $resultFactory, array $routingEntities
    ) {
        $this->actionFactory = $actionFactory;
        $this->eventManager = $eventManager;
        $this->url = $url;
        $this->appState = $appState;
        $this->storeManager = $storeManager;
        $this->response = $response;
        $this->scopeConfig = $scopeConfig;
        $this->routingEntities = $routingEntities;
        $this->resultFactory = $resultFactory;
    }

    /**
     * Validate and Match
     *
     * @param MagentoFrameworkAppRequestInterface $request
     * @return bool
     */
    public function match(MagentoFrameworkAppRequestInterface $request) {

        if (!$this->dispatched) {
            $urlKey = trim($request->getPathInfo(), '/');
            $origUrlKey = $urlKey;

            // START CHECK FOR URL KEY EXIST THEN ONLY PROCEED OTHERWIES NOT
            $postsURLPrefix = $this->scopeConfig->getValue('Module/posts/url_prefix', ScopeInterface::SCOPE_STORE);
            $postsURLSuffix = $this->scopeConfig->getValue('Module/posts/url_suffix', ScopeInterface::SCOPE_STORE);
            $parts = explode('/', $urlKey);

            if ($postsURLSuffix) {
                $suffix = substr($urlKey, -strlen($postsURLSuffix) - 1);
                if ($suffix != '.' . $postsURLSuffix) {
                    return false;
                }
                $urlKey = substr($urlKey, 0, -strlen($postsURLSuffix) - 1);
            }

            if (isset($parts[1])) {
                $postsIdentifier = str_replace($suffix, "", $parts[1]); // Posts URL Key
                // START CHECK FOR PREFIX & SUFFIX
                if ($parts[0] == $postsURLPrefix && $postsURLSuffix == $postsURLSuffix) {

                    // START CHECK FOR URL KEY EXIST THEN ONLY PROCEED OTHERWIES NOT
                    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                    $instance = $objectManager->get('CustomModuleModelResourceModelPosts');
                    $id = $instance->checkUrlKey($postsIdentifier, $this->storeManager->getStore()->getId());

                    if (!$id) {
                        return null;
                    }
                    // STOP CHECK FOR URL KEY EXIST THEN ONLY PROCEED OTHERWIES NOT

                    $condition = new DataObject(['url_key' => $origUrlKey, 'continue' => true]);
                    $this->eventManager->dispatch(
                            'Custom_Module_controller_router_match_before', ['router' => $this, 'condition' => $condition]
                    );

                    $origUrlKey = $condition->getUrlKey();

                    if ($condition->getRedirectUrl()) {

                        $this->response->setRedirect($condition->getRedirectUrl());
                        $request->setDispatched(true);
                        return $this->actionFactory->create(Redirect::class);
                    }

                    if (!$condition->getContinue()) {
                        return null;
                    }

                    foreach ($this->routingEntities as $entityKey => $entity) {
                        $match = $this->matchRoute($request, $entity, $origUrlKey, $origUrlKey);
                        if ($match === false) {
                            continue;
                        }
                        return $match;
                    }
                }
            }
            // END CHECK FOR PREFIX & SUFFIX
        }

        return null;
    }

    /**
     * @param RequestInterface|MagentoFrameworkHTTPPhpEnvironmentRequest $request
     * @param Entity $entity
     * @param $urlKey
     * @param $origUrlKey
     * @return bool|MagentoFrameworkAppActionInterface|null
     */
    protected function matchRoute(RequestInterface $request, Entity $entity, $urlKey, $origUrlKey) {

        $prefix = $this->scopeConfig->getValue($entity->getPrefixConfigPath(), ScopeInterface::SCOPE_STORE);

        if ($prefix) {
            $parts = explode('/', $urlKey);
            if ($parts[0] != $prefix || count($parts) != 2) {
                return false;
            }
            $urlKey = $parts[1];
        }

        $configSuffix = $this->scopeConfig->getValue($entity->getSuffixConfigPath(), ScopeInterface::SCOPE_STORE);

        if ($configSuffix) {
            $suffix = substr($urlKey, -strlen($configSuffix) - 1);
            if ($suffix != '.' . $configSuffix) {
                return false;
            }
            $urlKey = substr($urlKey, 0, -strlen($configSuffix) - 1);
        }

        $instance = $entity->getFactory()->create();
        $id = $instance->checkUrlKey($urlKey, $this->storeManager->getStore()->getId());

        if (!$id) {
            return null;
        }

        $request->setModuleName('Module');
        $request->setControllerName($entity->getController());
        $request->setActionName($entity->getViewAction());
        $request->setParam($entity->getParam(), $id);
        $request->setAlias(Url::REWRITE_REQUEST_PATH_ALIAS, $origUrlKey);
        $request->setDispatched(true);
        $this->dispatched = true;

        return $this->actionFactory->create(Forward::class);
    }
}

appcodeCustomModuleControllerReplyIndex.php

namespace CustomModuleControllerReply;

class Index extends MagentoFrameworkAppActionAction {

    /** @var  MagentoFrameworkViewResultPage */
    protected $resultPageFactory;

    /**     * @param MagentoFrameworkAppActionContext $context      */
    public function __construct(MagentoFrameworkAppActionContext $context, MagentoFrameworkViewResultPageFactory $resultPageFactory) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Blog Index, shows a list of recent blog posts.
     *
     * @return MagentoFrameworkViewResultPageFactory
     */
    public function execute() {
        $resultPage = $this->resultPageFactory->create();

        $post = $this->getRequest()->getPostValue();

        echo "
";
        print_r($post);
        exit;

        return $resultPage;
    }
}

Se pensi che il nostro post ti sia stato utile, sarebbe molto utile se lo condividessi con più appassionati di programmazione in questo modo contribuisci a diffondere questo contenuto.



Utilizzate il nostro motore di ricerca

Ricerca
Generic filters

Lascia un commento

Il tuo indirizzo email non sarà pubblicato.