I currently have the following <preference/> in one of my di.xml file:

<preference for="Magento\Contact\Controller\Index\Post" type="RadTest\TestModule\Controller\Contact\Post" />

I have an enable/disable configuration option for my module in the admin panel. I only want the <preference> to be enabled when my custom configuration option is set to enabled.

How can I dynamically enable and disable the <preference/> overriding according to the configuration of my module is set?

1 Answer 1


you cannot enable and/or disable preferences based on a config setting.
di.xml is just configuration. you cannot have logic in it, but you can do something else.
You can have in your class a condition that checks your config flag and does some action accordingly.
I assume your class RadTest\TestModule\Controller\Contact\Post extends Magento\Contact\Controller\Index\Post because you have to override at least one method.
let's say you have to override the method execute.
You can make your class do this:

namespace RadTest\TestModule\Controller\Contact;
class Post extends \Magento\Contact\Controller\Index\Post
    public function execute()
        if (your config setting is disabled) {
            return parent::execute();
        //your custom logic here
  • 1
    This is actually what I've been doing and was thinking it will be nice if there is a way to dynamically disable them. Now I know we can't. Thanks a lot! :)
    – xenon
    Dec 7, 2016 at 14:02
  • Can I use this in Vendor/Module/Plugin/Customer/Account/CreatePost.php too?
    – Anto S
    Dec 16, 2020 at 10:50
  • 1
    @Butterfly. Sure. You can use it anywhere you want.
    – Marius
    Dec 16, 2020 at 10:57

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.