Jump to content

Save a value when a page is added using ready.php hook


cb2004
 Share

Recommended Posts

I am having a bit of a brain ache with this one. Can anybody point me in the right direction. At the moment I just want to get the field text_1 populated with the value test and then I should be good to go.

Cheers.

<?php

$pages->addHookAfter("added", function($event) {
	$page = $event->object;
	if($page->template->id == 46) {
		$page->text_1 = "test";
	}
});
Link to comment
Share on other sites

You need to save your change. For PW < 2.7:

$of = $page->of();
$page->of(false);
$page->set('text_1', 'test');
$page->save('text_1');
$page->of($of);

Or for PW >= 2.7:

$page->setAndSave("text_1", "test");
  • Like 1
Link to comment
Share on other sites

$event->object will always give you the object the hook function is on. In this case it's pages.

$pages->addHookAfter("added", function($event) {
	// $pages = $event->object; 
        $page = $event->arguments(0);
	if($page->template->id == 46) {
		$page->setAndSave('text_1', "test");
	}
});
Link to comment
Share on other sites

I have a working solution. I am taking a guess that it cannot update a field directly in the page you are saving without a bit of extra information:

<?php

$pages->addHookBefore('added', function($event) {
	$page = $event->arguments(0);
	if ($page->template->id == 46) {
		$p = wire('pages')->get($page->id);
		$p->setAndSave("text_1", "test");
	}
});

The solution by LostKobrakai works as well.

Edited by cb2004
  • Like 1
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...