processwire / processwire-requests

ProcessWire feature requests.
39 stars 0 forks source link

please add methods to force return type of file/image fields #453

Closed BernhardBaumrock closed 2 years ago

BernhardBaumrock commented 2 years ago

Short description of the enhancement

Please add the following two methods to the Page class:

$page->getImage('myimagesfield'); // return PageImage (or null)
$page->getImages('myimagesfield'); // return PageImages (array)

Edit: Obviously we'd also need the same for PageFiles and PageFile - or maybe a method that has a proper wording for both scenarios?

$page->getSingular('myimagesorfilesfield');
$page->getMulti('myimagesorfilesfield');

getArray() is already taken...

Current vs. suggested behavior

Currently it is really not easy to make sure that the returned value in your code is either a single PageImage or a PageArray. This has always caused confusion with newcomers, but even some advanced members like Horst and Me where using a solution that to our surprise was not as bullet-proof as we thought!! See here: https://processwire.com/talk/topic/26952-get-image-in-the-context-of-a-hook/?do=findComment&comment=222917

Why would the enhancement be useful to users?

When working with image fields in code it is sometimes important to make sure that you are either working with a singular or a multi field. Some possible solutions would be:

$images = $page->getUnformatted('myimagesfield')->find('created!=10');
if($images->count()) echo $images->first()->url;

// or
$image = $page->getFormatted('myimagesfield');
if($image instanceof PageImages AND $image->count()) echo $image->first()->url;
elseif($image) echo $image->url; // singular pageimage

Are these two really the best options we have? Am I missing something?

Please also see my explanation why that can really be a problem in the forum: https://processwire.com/talk/topic/27494-images-first-api/?do=findComment&comment=226185

@ryancramerdesign

BernhardBaumrock commented 2 years ago

Added in the latest DEV :) https://processwire.com/talk/topic/27528-weekly-update-%E2%80%93%C2%A02-september-2022/#comment-226391 Thx @ryancramerdesign !