Retrieving pages by using filterBy on a structure field

Hello,

I’ve got “Proposals” pages with this structure field containing a multiselect field.
The multiselect field has its “max” option set to 1 so I’ve always only one value in this field.

proposalParticipantsUsers:
    label: Participants
    type: structure
    fields:
        participantUser:
        label: Add a participant for this project
        max: 1     
        type: multiselect
        options: query
        query: 
            fetch: kirby.collection('candidats')
            text: "{{ user.name }} - {{ user.email }}"
            value: "{{ user.id }}"

I would like to filter all the proposals pages which have a specific user id stored in the “participantUser” field.

Can I use filterBy directly on the pages like this :

$proposalsSelected = $allProposals->filterBy( ... ? ) // if yes how?

or am I obliged to loop on proposals pages first and then check if the structure field contain the specific user id ?

foreach ( $proposals as $proposal ) :
if ( $proposal->proposalParticipantsUsers()->toStructure()->filterBy( 'participantUser', '==', $user_id ) ) :
// do something ...
endif;
endforeach;

No. You have to use the filter method with a callback:

$userId = 'xxx';
$proposalsSelected = $allProposals->filter(function($proposal) use($userid) {
  $users = $proposal->proposalParticipantsUsers()->toStructure();
  return $users->filterBy('participantUser', $userId)->isNotEmpty();
}

Does a filter like this can be called in a hook ?

Yes, sure, it doesn’t matter where you call it (provided your userid is known in the hook.

Ok cool I will try, thx Sonja :slight_smile: