Jump to content

Assigning a value by page name (I didn't know you can do this)


Jonathan Lahijani
 Share

Recommended Posts

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.

  • Like 3
Link to comment
Share on other sites

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 🙂 

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