1

Within a plugin I have written I would like to route POST requests to the plugin controller and GET requests to a single entity created in craft.

When the user POSTs to http://example.com/start-your-quote it should be handled by the plugin controller. When the user GETs http://example.com/start-your-quote it should load the single entity with the slug 'site-start-your-quote'

I have written the following in the hopes of achieving this:-

 Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
            static function (RegisterUrlRulesEvent $event) {
                $event->rules['POST start-your-quote'] = 'craft-lp-api-helper/lpapi';
                $event->rules['GET start-your-quote'] = 'site-start-your-quote';
            }
        );

The POST is working as expected, however the GET results in the following error:-

Blockquote HTTP 404 – Not Found – yii\web\NotFoundHttpException Page not found. ↵ Caused by: Invalid Route – yii\base\InvalidRouteException Unable to resolve the request "site-start-your-quote".

Hopefully I am missing something simple and someone can point me in the righ direction?

2
  • Mmmm first thought is site-start-your-quote isn't a get request?
    – joomkit
    Commented Feb 5, 2020 at 22:50
  • Thanks @joomkit but going to that slug direct in a browser works fine, it's just from the route rule I'm getting the 404.
    – SloganHD
    Commented Feb 6, 2020 at 7:39

1 Answer 1

1

Well I have managed to achieve what I needed, I'm not sure if this is a very good way to do it though.

I've done it by getting the element of the page I needed and passing that to the route along with the template to use.

It all seems to work though.

Event::on(
        UrlManager::class,
        UrlManager::EVENT_REGISTER_SITE_URL_RULES,
        static function (RegisterUrlRulesEvent $event) {
            $element = Craft::$app->getElements()->getElementByUri(
                'site-start-your-quote',
                Craft::$app->getSites()->getCurrentSite()->id,
                true);
            $event->rules['POST start-your-quote'] = 'craft-lp-api-helper/lpapi';
            $event->rules['GET start-your-quote'] = [
                'template' => '_layouts/forms/start-your-quote.twig',
                'variables' => [
                    'entry' => $element,
                ],
            ];
        }
    );

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.