torf Posted March 23, 2022 Share Posted March 23, 2022 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 More sharing options...
3fingers Posted March 23, 2022 Share Posted March 23, 2022 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 More sharing options...
bernhard Posted March 23, 2022 Share Posted March 23, 2022 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 }); 1 Link to comment Share on other sites More sharing options...
torf Posted March 23, 2022 Author Share Posted March 23, 2022 Thanks a lot - both of you. It works, and again I am a bit nearer to understanding how processwire works. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now