Jump to content
hdesigns

Module For Beginners

Recommended Posts

Today I've created a really simple little module that is configurable and attaches to hooks.

So it has more or less everything of a real world module in it.

I thought processwire beginners would be interested in reading how to create such a module so I added some comments to the source code in a way the module should explain itself...

Here it is:

/**
 * BackgroundChanger module for demonstration purposes
 *
 * Demonstrates the Module interface and how to add hooks in a more real world manner...
 * 
 * ProcessWire 2.x 
 * Copyright (C) 2014 by Domenic Helfenstein
 *
 */

class BackgroundChanger extends WireData implements Module, ConfigurableModule {
    public static function getModuleInfo() {
        return array(
            /*
             * the __("text") methods are used for multilanguage support
             * see: https://processwire.com/api/multi-language-support/code-i18n/
             */
            'title' => __('BackgroundChanger'),
            'summary' => __('This is a simple real world module that can change the background color.'),
            'version' => 105,
            /*
             * autoload must be true if the module depends on hooks
             * see: http://wiki.processwire.com/index.php/Module_Creation#Details_of_what_the_.22autoload.22_property_means
             */
            'autoload' => true,
            /*
             * it is wise to run modules in singular mode when using hooks
             * see: http://wiki.processwire.com/index.php/Module_Creation#Details_of_what_the_.22singular.22_property_means
             */
            'singular' => true,
        );
    }
    
    public function __construct() {
        //set default values
        $this->backgroundColor = 'yellow';
        /*
         * !!! the value in the db will be automatically injected into this var 
         * because it is named equal to the value of $field->name in 
         * getModuleConfigInputfields !!!
         */
    }
    
    public function init() {
        // add a hook after each page is rendered and modify the output
	$this->addHookAfter('Page::render', $this, 'changeBackground');
    }
    
    public function changeBackground($event) {
        $page = $event->object;

        //do only modify non-admin pages
        if($page->template == 'admin') return;
        
        $extension = <<< _OUT
            <style>
                body {background-color:{$this->backgroundColor};}
            </style>
_OUT;
        $event->return = str_replace("</head>", $extension."</head>", $event->return); 
    }
    
    public static function getModuleConfigInputfields(array $data) {
        //create a fieldset
        $inputfields = new InputfieldWrapper(); 
 
        //create field for background color
        $field = wire('modules')->get('InputfieldText');
        $field->name = 'backgroundColor';
        $field->label = __("Enter the hex-code or name of the desired background color. (visit colorpicker.com)");
        
        //if there is already a value stored, set this value to the field
        if(isset($data['backgroundColor'])) $field->value = $data['backgroundColor'];
        
        //add the field to the fieldset
        $inputfields->add($field);
 
        //return the fieldset to display
        return $inputfields; 
    }
}

I hope this helps others creating their own modules!

BackgroundChanger.module

  • Like 18

Share this post


Link to post
Share on other sites

Anything that adds to the learning process is appreciated.  Thanks for the effort.

  • Like 2

Share this post


Link to post
Share on other sites

Thanks for sharing this with added comments to learn from.

It will help me to make my own "count down to event" module.

Share this post


Link to post
Share on other sites

Thanks for this. I've been learning to create a module for the last week and I'm surprised at how well I seem to be doing (touch wood).

The problem I'm facing is that I can't find some of the information I'm looking for, as it seems to be spread all over the place. I have looked through the HelloWorld example, but that didn't help me either. So, I'm hoping someone here can point me to the relevant documentation, or answer the following for me.

How do we remove the fields created in the getModuleConfigInputfields() function? Are they automatically removed when the module is uninstalled, or do we have to manually remove them within the ___uninstall() function?

Also, does anyone have a complete list of the available functions for use within a module, i.e I know about ___uninstall(), ___install(), __construct(), etc, but are there any more built-in ones we can use?

Thanks

Share this post


Link to post
Share on other sites

.............

1. How do we remove the fields created in the getModuleConfigInputfields() function? Are they automatically removed when the module is uninstalled, or do we have to manually remove them within the ___uninstall() function?

2. Also, does anyone have a complete list of the available functions for use within a module, i.e I know about ___uninstall(), ___install(), __construct(), etc, but are there any more built-in ones we can use?

Thanks

1. Those are not actual fields per se. No fields are created in the database. The method just 'creates' inputfields (i.e., HTML input 'areas') that are displayed in a module's configuration screen. The user configurable values in those fields are stored in the database (in that module's row in the 'modules' table in the 'data' column) in JSON-like format. On uninstall, a modules record is deleted from the database (i.e. its row in the table 'modules'), so, everything about the module is deleted:

public function ___uninstall($class) in /wire/core/Modules.php/

$database = $this->wire('database'); 
$query = $database->prepare('DELETE FROM modules WHERE class=:class LIMIT 1'); // QA
$query->bindValue(":class", $class, PDO::PARAM_STR); 
$query->execute();

2. Although there are some methods (functions) specific to modules, you can use any(almost any?) PW and PHP method with modules. It is just PHP :-). If you are really into this, I would suggest to first study the source code of a couple of modules in the modules directory. If you are curious about some stuff have a glance at Modules.php and Module.php although you really don't need to do this. The following threads are also helpful RE configurable modules:

https://processwire.com/talk/topic/5480-configurable-process-module-need-walk-through/

https://processwire.com/talk/topic/3343-how-can-i-setget-module-data-from-db-when-not-implementing-configurablemodule/

https://processwire.com/talk/topic/7581-configurable-module-default-values-on-install/

Other:

https://processwire.com/talk/topic/1313-modules-process-and-the-difference/

...which reminds me,  I really need to get write those modules tutorials as promised... :P

  • Like 1

Share this post


Link to post
Share on other sites

Thanks for the extra info. It becomes much clearer when you find the correct documentation. It now makes sense regarding the configuration fields, and the fact that they are simply HTML input areas, as I was under the impression they were added to the database beforehand.

ProcessWire is a seriously clever and efficient framework.

I look forward to seeing your tutorials.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...