Extending module class

Introduction

Extending module class – in some cases, you need to extend the module class. For example to add new functionality, to change the current one, etc. So this post will focus on how to do that easily.

In previous versions of SugarCRM, you could just name class same as module class and extend it in the custom module folder. /sugar/custom/modules/{MODULE_NAME}/{MODULE_NAME}.php

But in the latest versions, this is not possible. You will get the error: ‘Can not redeclare class’.




How to…

Extending module class is easy by doing non-upgrade safe changes to the module. So, for example, let’s try to extend the Documents module.

First, rename Document class in /sugar/modules/Document/Document.php to SugarDocument.

class SugarDocument extends SugarBean {
...
}

Second, create a new PHP file and Document class in /sugar/custom/modules/Documents/Document.php and make it extend SugarDocument class.

require_once ('modules/Documents/Document.php');
class Document extends SugarDocument {
...
}

The last thing left to do is to tell autoloader to load ‘Document’ class from the custom module. This is done in /sugar/vendor/composer/autoload_classmap.php Just search in autoload_classmap.php file for ‘Document’ and change from default path to custom one. Like in code snippet below.

'Document' => $baseDir . '/custom/modules/Documents/Document.php',




Conclusion

This is the easiest way to extend module class. It will not be “upgrade safe” as we changed directly module class name. But if we create README.md file and properly mark all commits that are not upgrade safe, after the upgrade we can re-apply commit and everything will work fine. Example of proper README.md:

[Commit: 9eee101] (.../commit/9eee101bc96afe02b1223cba5e722d3ce4540b2f)
Documents - changed the class of Documents to SugarDocuments in /modules/Documents/Documents.php and custom file /custom/modules/Documents/Documents.php now have class Documents that extends SugarDocuments.

So developer just needs to use all tools that are available for him and everything will work fine.

If you liked this post, check other our posts too. For instance our post here about using BWC modules after upgrade.

Also check our YouTube channel here.

Marko Vucak Author

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *