Friday, 8 July 2016

How to Use Classes in Your Drupal 7 Custom Module

I’ve had a couple of issues with this the last time I’ve set it up from scratch. Normally I’m coming into a project to make changes and not starting from scratch.

The one thing I’d been missing though is that you need to install a ‘Autoload’ into Drupal 7 . This is core in Drupal 8 Install ‘X Autoload’ -
In your module create a new folder . i.e. ‘src’
Create and name a file in that Folder. Use camel case and make it self explanatory

For example MyUsefulHelper.php

 * @file
 * Contains MyUsefulHelper
namespace Drupal\MY_MODULE;
class MyUsefulHelper {
// Methods go here

Note that in the case of 'src' you do not need to name that in the Namespace .
And then in your .module file use code like.

use Drupal\supplier_form\TaxonomyHelpers;

From here on you should be able to call on the methods in the class.

No comments: