ProcessWire 3.0.126 core updates

This week we take a look at what’s in ProcessWire 3.0.126 which focuses largely on resolving issue reports, but also includes a handy new $page->if() method.

I mentioned in the last blog post that I’ve got to focus on client projects in the month of February and that’s what I’ve been doing. However, I’ve found that it works well to work through GitHub issue reports in the processwire-issues repo at the same time, going back and forth. So I’ve been doing both, focusing on issue reports that I can resolve fairly easily, while giving much needed attention to my client work. That’s likely what the next couple of weeks will look like here too.

This strategy is working well, both for the client work and the core. We’re making a lot of progress on resolving older issue reports. This has been made possible by the work of @netcarver who has been managing the issue reports and identifying those that can be closed as well as those that need more work or additional info. Big thanks to him for doing all this and maintaining the great momentum.

We have a new version of the core ready this week. While there are a lot of minor fixes and optimizations (per various resolved issue reports) there isn’t anything major relative to the previous dev branch version, so this post will be short. However, there is one new API method I wanted to take a closer look at this week, so I’ll use this post to cover it in more detail.

New $page->if() method

This new method enables you to conditionally render a string or execute an inline function according to whether the expression in the first argument matches. It came about because I was looking for a way to save time and space when outputting various $page fields, and often found it necessary to have more conditional logic or ternary operator statements than I wanted. This has always been the case, though I never gave much thought to it before, it's just the nature of it. But now I'm needing to develop a lot of template files, outputting a lot of fields, without a lot of time to do it, and don't want to riddle my code with ternary operater expressions. I'm always looking for ways to do things better, faster and simpler, and with less code, while improving rather than reducing readability. The $page->if() method enabled me to reduce the amount of time and code necessary to accomplish the output I was looking for, while making it more readable in my template files. This method is easier to show than it is to describe, so I’ll start with some examples. Note however that the purpose of these examples isn't to demonstrate the best or code-saving use cases, but rather to introduce the method with simple examples while demonstrating different usages of the arguments:

// if summary is populated, output it in an paragraph
echo $page->if("summary", "<p class='summary'>{summary}</p>");

// if price is populated, format for output, otherwise ask them to call for price
echo $page->if("price", function($n) { return '$' . number_format($n); }, "Please call");

// you can also use selector strings
echo $page->if("inventory>10", "In stock", "Limited availability");

// output an <img> tag for the first image on the page, or blank if none
echo $page->if("images", function($val) { return "<img src='{$val->first->url}'>"; });

How it works

This $page->if() method merges the capabilities of $page->if(), $page->get() and $page->getMarkup() methods in one, plus it provides some useful PW type-specific logic, providing a useful output shortcut. This can be quite handy in some output situations. In many cases it enables you to accomplish on one-line of code what might have otherwise taken multiple lines of code. Use this when looking for a useful shortcut and this one fits your need better than a regular if() statement or PHP ternary operator (which may still be preferable in many cases).

The logic in this method is smarter for PW than a regular PHP if() statement or ternary in a couple of ways. If the value resolves to any kind of empty WireArray (like a PageArray or files/images) the NO condition is used. If the WireArray is populated with at least one item then the YES condition is used. So this if() method (unlike PHP if) requires that not only is the value present, but it is also populated in order to match the $yes condition. Likewise, If value resolves to a NullPage the NO condition is used.

Arguments

This method is primarily intended for conditionally outputting some formatted string value or markup, however its use is not limited to that, as you can specify whatever you’d like for the $yes and $no arguments. Here are the arguments that it accepts:

echo $page->if($key, $yes, $no);
echo $page->if($key, $yes); // $no argument is optional

$key argument

The $key argument may be any of the following:

  • A field name, in which case we will use the value of that field on this page. If the value is empty the NO condition will be used, otherwise the YES condition will be used. You can use any format for the field name that the Page::get() method accepts, so subfields and OR field statements are also okay, i.e. categories.count, field1|field2|field3, etc.

  • A selector string that must match this page in order to return the YES condition. If it does not match then the NO condition will be used.

  • A boolean, integer, digit string or PHP array. If considered empty by PHP it will return the NO condition, otherwise it will return the YES condition.

$yes and $no arguments

The $yes and $no arguments (the conditional actions) may be any of the following:

  • Any string value that you’d like (HTML markup is likely a common use case).

  • A field name that is present on this page, or optionally the word “value” to refer to the field specified in the $key argument. Either way, makes this method return the actual field value as it exists on the page, rather than a string/markup version of it.

  • Any callable inline function that returns the value you want this function to return.

  • A string containing one or more {field} placeholders, where you replace “field” with a field name. These are in turn populated by the Page::getMarkup() method. You can also use {field.subfield} and {field1|field2|field3} OR-type placeholder strings.

  • A string containing {value} somewhere, where it will be replaced with the markup value of the field name given in the $key argument.

  • If you omit the $no argument an empty string is assumed.

  • If you omit both the $yes and $no arguments, then boolean is assumed (true for yes, false for no), which makes this method likewise return a boolean. The only real reason to do this would be to take advantage of the method’s slightly different behavior than regular PHP if() statements (i.e. treating empty WireArray or NullPage objects as false conditions).

Return value

The return value can actually be anything since your arguments specify it, or your inline function returns it. However in most cases I think you'll likely be dealing with strings as the return value since this function is largely intended as a front-end conditional output helper. As mentioned earlier, this method will return a boolean only you omit the $yes and $no arguments.

Conclusion

This method is an optional helper that’s an alternative to a regular PHP if() statement, kind of like how the PageArray::each() method is an optional alternative to a foreach(). But both have PW intelligence behind them that often (though not always) enables them to do the job with less code, work and space. I built this method a couple of weeks ago, but waited to add it to the core because I wanted to see how effective it would prove to be in the real world with my client projects. After a couple weeks of using it, I know I'll be using it a lot going forward, so wanted to go and and tell you about it this week. Try it out sometime and see if you find it helpful in your own projects as an alternative conditional output strategy.

Thanks for reading and have a great weekend. Visit the ProcessWire Weekly this weekend for the latest ProcessWire news, updates and site of the week.

Comments

  • HMCB

    HMCB

    Will use this a lot! Thank you.

  • MrSnoozles

    MrSnoozles

    • 6 years ago
    • 51

    this is super cool, well done.

  • Niko

    Niko

    • 6 years ago
    • 42

    Great thing! Will it output a field rendering if I pass a fieldname as $yes or $no or just the value?

  • Mark

    Mark

    • 6 years ago
    • 41

    Awesome! I can see this really help simplify the various conditional checks we sometimes need in our template files!

  • Manlio

    Manlio

    • 6 years ago
    • 30

    Great as usual. I think this is very useful. Thank you Ryan

 

PrevA closer look at ProcessWire ProMailer

11

This week we take a closer look at the upcoming ProMailer module with a lot more details and screenshots. Plus an update on next steps with the new website and development schedule in the weeks ahead.  More 

NextProcessWire 3.0.127 core updates

3

This week we look at the latest version of ProcessWire, 3.0.127. This version contains nearly 30 new commits resolving dozens of older issue reports and adds two new useful status settings for pages. More 

Latest news

  • ProcessWire Weekly #552
    In the 552nd issue of ProcessWire Weekly we'll check out the latest weekly update from Ryan, take a quick look at a new e-commerce solution for ProcessWire, and more. Read on!
    Weekly.pw / 7 December 2024
  • Custom Fields Module
    This week we look at a new ProFields module named Custom Fields. This module provides a way to rapidly build out ProcessWire fields that contain any number of subfields/properties within them.
    Blog / 30 August 2024
  • Subscribe to weekly ProcessWire news

“…building with ProcessWire was a breeze, I really love all the flexibility the system provides. I can’t imagine using any other CMS in the future.” —Thomas Aull