Jump to content

Need help with module creation


uzlander
 Share

Recommended Posts

Hi there, i've been trying to create a module which works in the admin panel, and does the following:
Auto-fill the "summary" field with some body excerpt in case the user leaves it blank.

Can't  figure what is wrong and it refuses to function as i expect. So, the code:
 

<?php namespace ProcessWire;

class FillSummaryHook extends WireData implements Module { 

    public static function getModuleInfo() {

		return array(
			'title' => 'Fill Summary Field', 	
			'summary' => 'Useful module',
			'version' => 0.4, 
			'autoload' => true, 
		);
	}

  public function ready() { 
    $this->pages->addHookBefore('saved', function($event) {
    	$page = $event->arguments[0];

    	$summaryField = $page->field('summary');
    	$bodyField = $page->field('body');
    
    	// If the summary field is empty, set it to the body excerpt
    	if (empty($summaryField->value)) {
    	    $summaryField->value = strip_tags(substr($bodyField->value, 0, 192));
    	}
    });
  }
}

The file's named: "FillSummaryHook.module" which is inside the same named folder within "modules" directory.
On saving the page it outputs (screenshot) spacer.png

Link to comment
Share on other sites

Hello,

Error message says there's no property "field" on Page class. There are also some more mistakes.

This should be better:

public function ready() {
    $this->pages->addHookBefore('saveReady', function($event) { // Replaced saved with saveReady
        $page = $event->arguments(0); // Replaced [0] with (0)

        $summaryField = $page->summary; // Removed ->field('name')
        $bodyField = $page->body; // Removed ->field('name')
        
        if (empty($summaryField)) { // Removed ->value
            $page->summary = strip_tags(substr($bodyField, 0, 192)); // replaced $summaryField->value with $page->summary, $bodyField->value with $bodyField
        }
    });
}

Note that "save" hook is executed after the page is saved, so it's too late.

Documentation : Page and Pages hooks 

 

EDIT : Note that you can also do that without creating a module, just by adding the hook ($this->pages->addHookBefore...) in site/templates/admin.php

  • Like 3
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...