Jump to content

Change Field value based on a checkbox


torf
 Share

Recommended Posts

Hi,

I really got Stuck on a quite common Task, but cannot find the problem. The Idea was to have a checkbox in my backend, and set another integer field to 0 upon save if this checkbox is not checked. So I added the following code to my ready.php

$wire->addHookBefore('Pages::saved', function($event){
	$page = $event->arguments(0);
	if($page->hasField("my_checkbox")) {
		if($page->my_checkbox == 0) {
			$page->another_integer_field = 0;
			$this->message("This should have worked"); //for debugging only
		}
	}
});

Everything works great, the debugging message shows up, but the value in "another__integer_field" does not change.

Can anybody tell me where my mistake is?

Link to comment
Share on other sites

Try:
 

$wire->addHookBefore('Pages::saveReady', function($event){
	$page = $event->arguments(0);
	if($page->hasField("my_checkbox")) {
		if($page->my_checkbox == 0) {
			$page->setAndSave('another_integer_field',0);
			$this->message("This should have worked"); //for debugging only
		}
	}
});

 

Link to comment
Share on other sites

The truth lies in the middle of both code snippets ? 

If using Pages::saved you need to use setAndSave because if you only change the page property there will be no later save that actually saves it.

If using Pages::saveReady as 3fingers showed you can use setAndSave but it's actually not necessary. You can simply use $page->yourfield = 'foo'; as the page IS actually saved right afterwards.

Also I prefer to use early exists rather than a lot of if ... if ... if ... but that's a matter of preferance ? 

<?php
$wire->addHookBefore('Pages::saveReady', function($event){
	$page = $event->arguments(0);
	if(!$page->hasField("my_checkbox")) return;
	if($page->my_checkbox) return;
	$page->another_integer_field = 0;
	$this->message("This should have worked"); //for debugging only
});

 

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