Jonathan Lahijani Posted December 21, 2023 Share Posted December 21, 2023 After over 10 years, I didn't know you can simply give a page's name when assigning a value to a page field. I discovered this by accident. I used to do this: $page->setAndSave('order_status', $pages->get('/path/to/order-statuses/pending/')); But I realized you can simply do this in ProcessWire making it much easier on the eyes, with the added benefit of not having to update the code if the path to the page changes: $page->setAndSave('order_status', 'pending'); My mind is blown. It makes me wonder what other little things I haven't realized yet. 3 Link to comment Share on other sites More sharing options...
nbcommunication Posted December 21, 2023 Share Posted December 21, 2023 "I didn't know you can do this" is definitely a good theme for a blog post @ryan! 3 Link to comment Share on other sites More sharing options...
bernhard Posted December 21, 2023 Share Posted December 21, 2023 Thx for sharing, didn't know that as well! Not sure if your example is real or not, but I'd recommend something like this: $order->setOrderStatus('pending'); So your $page should better be an OrderPage (custom page class) and that pageclass should have this method: <?php ... public function setOrderStatus($status) { $this->setAndSave( 'order_status', $this->wire->pages->get("/path/to/order-statuses/$status") ); } I know the benefit looks little, but the code does not only get cleaner to read: <?php $page->setAndSave('order_status', $pages->get('/path/to/order-statuses/pending/')); // vs $order->setOrderStatus('pending'); It gets also more error-proof (what if someone/something created another page with name "pending" somewhere else in the tree? And not to forget your system will be better and easier to maintain. Imagine for example you change the path of your statuses one day. You only change the path in setOrderStatus() and you are done, rather than finding all instances of ->setAndSave(...). Also maybe one day the client want's E-Mail notifications on changed statuses... Simply go to setOrderStatus() method and add the mail code there. If you have several ->setAndSave('order_status', 'something') sprinkled around you might be tempted to add the mail sending on several locations or you might forget it somewhere and you'll have introduced an unnecessary bug ? PS: I'd even more prefer setStatus() but that's already taken by the Page baseclass. updateStatus() would also be an option. But setOrderStatus() might be the clearest anyhow ? 4 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