Jump to content

Populate fields in save hook


arnoson
 Share

Recommended Posts

Hello,

I'm trying to do the following: When a user saves a page I want to populate some fields on the same page. For example: calculate the ratio of an image and save it in a hidden field.
I've created a Module and populate the field in a beforeSave hook. But my manually populated field doesn't get saved. I guess I have to call $page->save() in order to save the field, but this would lead to an infinite loop. Because I populate the field in a beforeSave hook shouldn't the page save the field right after the execution of my hook?

 

<?php
class ItemHooks extends WireData implements Module {
	public static function getModuleInfo() {
		return array(
			'title' => 'item hooks',
			'version' => 100,
			'summary' => 'add item hooks to process items after beeing saved',
			'href' => '',
			'singular' => true,
			'autoload' => true
		);
	}

	public function init() {
		$this->pages->addHookBefore('save', $this, 'handleSave');
	} 

	public function handleSave($event) {
		$page = $event->arguments('page');
		$fields = $page->fields;
		$field = $fields->get('hidden_field');
		$field->set('value', 'test');
		$fields->save($field);
	}
}
?>

thanks,
Arno

Link to comment
Share on other sites

I think you have to call save on the field object, not the global $fields.

EDIT:

what about:

$page->set("hiden_field", $value);

Because I think you are trying to save the actual field (in the whole PW context), not the field that actually belongs to the page.

This would set the field value so it get's saved after the hook.

  • Like 4
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...