1

I am attempting to query entries via that have a field (ex numberField) with field type Number. Some of the entries don't have a value for this field, so in the response it has null. I am wanting to order the entries by this Number field, but I am wanting the ones with a valid number to be ordered first, and then the ones with values of null to come after. Examples below:

Rough query

query getElements {
  entries(
    section: ["anEntryType"]
    orderBy: "numberField ASC"
  ) {
    id
    ... on anEntryType_default_Entry {
      numberField
    }
  }
}

Response

{
  "data": {
    "entries": [
      {
        "id": "1",
        "numberField": null
      },
      {
        "id": "2",
        "numberField": null
      },
      {
        "id": "3",
        "numberField": 100
      },
      {
        "id": "4",
        "numberField": 200
      },
    ]
  }
}

Desired Response

{
  "data": {
    "entries": [
      {
        "id": "3",
        "numberField": 100
      },
      {
        "id": "4",
        "numberField": 200
      },
      {
        "id": "1",
        "numberField": null
      },
      {
        "id": "2",
        "numberField": null
      },
    ]
  }
}

Is this possible? Thanks!

1 Answer 1

1

You can try this.

query getElements {
  entries(
    section: ["anEntryType"]
    orderBy: [
      {
        field: "numberField"
        direction: "ASC"
      },
      {
        field: "numberField"
        direction: "ASC"
        value: null
      }
    ]
  ) {
    id
    ... on anEntryType_default_Entry {
      numberField
    }
  }
}

or

To sort the entries with a valid numberField value first, followed by the entries with a null value for numberField, you can use the following orderBy parameter in your query:

orderBy: [{
  field: "numberField",
  direction: "ASC",
  custom: "IS NOT NULL"
}, {
  field: "numberField",
  direction: "ASC"
}]

The custom parameter allows you to specify a custom sorting function that is applied after the initial sorting based on the field and direction parameters. The value "IS NOT NULL" tells Craft CMS to sort the entries with a non-null value for numberField before the entries with a null value for numberField.

Here is an example of how your GraphQL query would look with this sorting function included:

query getElements {
  entries(
    section: ["anEntryType"],
    orderBy: [{
      field: "numberField",
      direction: "ASC",
      custom: "IS NOT NULL"
    }, {
      field: "numberField",
      direction: "ASC"
    }]
  ) {
    id
    ... on anEntryType_default_Entry {
      numberField
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.