Skip to content

Kirby 4.4.1

$pages->when()

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.

$pages->when(mixed $condition, Closure $callback, ?Closure $fallback = null): mixed

Parameters

Name Type Default
$condition * mixed
$callback * Closure
$fallback Closure|null null

Return type

mixed

Parent class

Kirby\Cms\Pages inherited from Kirby\Toolkit\Collection

Examples

Apply the filter method only if the first parameter evaluates to true:

$size  = get('size');
$color = get('color');
$fit   = get('fit');

$products = $page->children()
    ->when($size, fn ($size) => $this->filterBy('size', $size))
    ->when($color, fn ($color) => $this->filterBy('color', $color))
    ->when($price, fn ($fit) => $this->filterBy('style', $fit));

With a fallback if the first parameter does not evaluate to true:

$sortBy = false;
$articles = $page->children()
    ->when(
            $sortBy,
            fn ($sortBy) => $this->sortBy($sortBy),
            fn () => $this->sortBy('title')
        );