Skip to content

[5.x]: Querying Entries Based on Lightswitch #17043

@SwiseWeb

Description

@SwiseWeb

What happened?

Description

Currently on a Craft 3 instance, we have an Element API endpoint which which returns results based on a lightswitch field. Currently the criteria is set to this:

[
    'limit' => null,
    'hideOnCalendar' => 'not 1',
    'section' => $sections
]

$sections is a dynamic array and contains various Section handles depending on the Element API request, some of which don't actually have the hideOnCalendar field. That query has worked fine on Craft 3 & 4, but we're in the process of upgrading to 5 and it isn't returning any results when querying for just one Section which doesn't have the hideOnCalendar field.

I traced this issue to here in the Element Query code:

// Make sure the custom field exists in one of the field layouts
if (!isset($fieldsByHandle[$handle])) {
throw new QueryAbortedException("No custom field with the handle \"$handle\" exists in the field layouts involved with this element query.");
}

I imagine that conditional has something to do with the move to JSON for all Craft content, but I'm not sure I follow the requirement. Is there a different way I should be approaching this query?

Steps to reproduce

  1. Create two Sections, Section A and Section B
  2. Create hideOnCalendar Lightswitch field with default value as false
  3. Add hideOnCalendar to Section A, but not Section B
  4. Run the following queries:
    • Query 1: Entry::find()->section(['sectionA', 'sectionB'])->hideOnCalendar(false)->all()
    • Query 2: Entry::find()->section(['sectionA'])->hideOnCalendar(false)->all()
    • Query 3: Entry::find()->section(['sectionB'])->hideOnCalendar(false)->all()

Expected behavior

Given 20 entries in Section A where all have hideOnCalendar set to false and 30 entries in Section B:

  • Query 1 returns 50 results
  • Query 2 returns 20 results
  • Query 3 returns 30 results

Actual behavior

Given 20 entries in Section A and 30 entries in Section B:

  • Query 1 returns 50 results ✅
  • Query 2 returns 20 results ✅
  • Query 3 returns 0 results

Craft CMS version

5.6.13

PHP version

8.2.26

Operating system and version

No response

Database type and version

No response

Image driver and version

No response

Installed plugins and versions

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions