Sortby on filterby with structurefiled

Hi,
I built me a searchfunction with filter:

    $result = $page->children()->filter(function($child) {
        return str::contains($child->propertytyp(), $_SESSION['propertyquery']) && str::contains($child->propertyzip(), $_SESSION['zipquery']);
    });

Now Im try to sortBy these filter with a button.
This works fine if I have a normal field but on a structure I don’t get it to work.
I tried it with ->toStructure() or ->yaml()but I dont get the structurefield.

if(r::is('post') && get('sortprice')) {
    if(!isset($_SESSION['sortprice']) OR $_SESSION['sortprice'] == 'desc'){
        $_SESSION['sortprice'] = 'asc';
        $result = $result->sortBy('propertyzip', 'asc');
        dump('Wird nach Preis (ASC) sortiert');
    }
    elseif($_SESSION['sortprice'] == 'asc') {
        $_SESSION['sortprice'] = 'desc';
        $result = $result->sortBy('propertyzip', 'desc');
        dump('Wird nach Preis (DESC) sortiert');
    }
}

at the field propertyzipI need the structurefield pricewith subfield price.
I hope sometimes the time is coming when I have no problems with the structure field :slight_smile:

Could you please provide more information, for example the blueprint with the structure field. And what exactly do you want to sort when there is a structure field? Can you provide an example for the expected result?

Hello Sonja,
this is the structurefield:

prices:
      type: structure
      entry: >
        {{text}} {{price}}
      fields:
        text:
          label: Text
          type: text
          width: 1/2
        price:
          label: Preis/Kosten
          type: text
          width: 1/2

My expected result is that the result is sort in asc or descorder based on the structurefield price.
I tested my code with a normal field and there it works.

In the template I have on the head a searchform which is producing the $result.
And under the form I have another form where I have buttons for the resultsorting.

Well, but by definition, a structure field usually contains more than one entry… so which price is the one you want to sort by? Or the lowest when sorting asc und the highest when sorting desc?

Hi,
sorry I forgot to write it.
I want to sort for the first price in the structure field.

Cheers and good night!

Your best option is probably the map() method to fetch the first structure field and create a new “virtual field” that contains the price, then sort by this virtual field. Something like:

$results = $results->map(function($item) {
  $prices = $item->prices()->structure();
  if($prices->count()) {
    $item->price = $prices->first()->price();
  } else {
    $item->price = '';
  }
  return $item;
})->sortBy('price');

(not tested)

1 Like