1

How do you override the beforeAction method of Craft's base controller? I'm disabling CSRF for a specific route.

public function beforeAction($action): bool
{
    $requestOrigin = \Craft::$app->getRequest()->headers->get('Origin');
    $origin = getenv('ENVIRONMENT') === 'dev' ? getenv('ORIGIN_DEV') :getenv('ORIGIN_PRODUCTION');

    / Disable CSRF validation for valid origins
    if ($requestOrigin === $origin) {
      $this->enableCsrfValidation = false;
    }

    if (!parent::beforeAction($action)) {
      return false;
    }

    return true;
}

I know that there have been similar questions asked before on overriding plugin methods and there's also the blueprint inside the controller itself. Just struggling to understand how to override the craft\web\Controller's method for this

1

Solution is to create a custom controller in a module that extends the cart controller. This gives the functionality to overwrite the beforeAction method, while keeping all other functionality.

As an example:

<?php

namespace modules\controllers;

use craft\commerce\controllers\CartController;

class FooController extends CartController
{
    public function beforeAction($action)
    {
        // Your overwritten logic here
        $something = 'test';

        return $something;
    }
}

Instead of posting to commerce/cart/update-cart you would then (in the example above) post to my-module/foo/update-cart. There is some useful documentation in the Craft docs on building a custom module and how to create customer controllers and actions.

[Answered by Nathaniel Hammond Pixel & Tonic]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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