how to filter in the dynamic zone in strapi using graphql?

jacksonkasi

Apr 2nd, 2023 11:11 PM

hello, dev's. i need help in strapi. if any one know please help me! thanks 🙂

query GetPosts($datelte: Date!, $dategte: Date!, $searchkey: String) {
  posts(filters: { effectiveDate: { lte: $datelte, gte: $dategte } }) {
    data {
      attributes {
        effectiveDate
        contentSections {
        ... on ComponentElementsEvents {
          title
            }
        }
      }
    }
  }
}

here how can I add a search filter by searchkey for the title?

title it's inside a dynamic zone.

dynamic zone image
filed inside dynamic zone filter

bobbyiliev

Apr 3rd, 2023 01:34 AM

Hi there,

The code snippet that you've shared does not seem to be correct, it includes a bunch of span tags. Can you re-share the code snippet that only contains your JS code?

Report
1
jacksonkasi

Apr 3rd, 2023 10:03 AM

@bobbyiliev Can you help me if you read the article again?

bobbyiliev

Apr 4th, 2023 01:21 AM

Hey!

Not 100% sure, but based on the information that you've provided, In Strapi, you'll need to use a nested filter with the elemMatch operator:

The elemMatch operator

You should be able to modify the GraphQL query like this:

query GetPosts($datelte: Date!, $dategte: Date!, $searchkey: String) {
  posts(filters: { effectiveDate: { lte: $datelte, gte: $dategte }, contentSections: { elemMatch: { __component: "elements.events", title_contains: $searchkey } } }) {
    data {
      attributes {
        effectiveDate
        contentSections {
          ... on ComponentElementsEvents {
            title
          }
        }
      }
    }
  }
}

Here's what has been added to the query:

  • A new filter for the contentSections field: contentSections: { elemMatch: { __component: "elements.events", title_contains: $searchkey } }.
  • The elemMatch operator is used to match components within the dynamic zone. We're specifying the component we want to filter by using the __component field with the value elements.events.
  • The title_contains operator is used to filter the title field based on the $searchkey variable.

An alternative option would be to use the approach described here:

Adding Search on your Strapi website

Let me know how it goes!

jacksonkasi

Apr 4th, 2023 02:37 AM

Thank you for sharing your thoughts with me. I have also attempted to follow that approach, but unfortunately, it did not work as expected.Screenshot 2023-04-04 150602.png

bobbyiliev

Apr 4th, 2023 06:56 AM

Indeed that seems to be a bit more complex than I initially thought. It might be best to start a discussion on the official Strapi forum instead where there will be more Strapi experts:

https://forum.strapi.io/

Report
1