1

I'm getting mixed results when using a lightswitch field together with order('RAND()') and I wonder if I'm doing something wrong.

For example, this code gives me the correct results:

craft.entries.section('section').lightSwitchField('1').first()

... but this selects entries from all entries in my channel instead of just the ones with the lightswitch field switched on.

craft.entries.section('section').lightSwitchField('1').order('RAND()').first()
1

Instead of using .first() try using .limit():

craft.entries.section('section').lightSwitchField('1').order('RAND()').limit(1)

I have just ran a test and this is working fine for me.

EDIT

I am using this code without any errors:

{% set entry = craft.entries.section('lorem').lightSwitchField('1').order('RAND()').first %}

{% if entry|length %}
    {{ entry.title }}
{% endif %}
  • I'm now getting "Object of class Craft\ElementCriteriaModel could not be converted to string". I'm assuming since craft.entries doesn't return the first model/entry found. Any idea around this without having to run a for loop on the reponse or variable[0]? set entry = craft.entries.section('section').lightSwitchField('1').order('RAND()').limit(1).first() – naboovalley Jan 19 '15 at 14:51
  • @naboovalley I have edited my answer with the working test code I am using. So this searches the section for all entries that have the lightswitch ticked, outputs them randomly but shows the first one, and without using a for-loop. Is this what you are after? – Jamie Wade Jan 19 '15 at 15:02
  • Your code is now exactly like my code from my question which isn't working for me. If I use the ".limit(1)" option instead I'm getting the correct result and then I can use entry[0].title instead of entry.title but it feels like a workaround. – naboovalley Jan 19 '15 at 15:47
  • Actually this isn't working either for me. Maybe I need to take this to Craft support.. – naboovalley Jan 19 '15 at 15:51
  • @naboovalley Very strange, I literally took it back to basics when testing that code. Added the lightswitch field, ticked a few random entries and it was all working absolutely fine. If that code definitely isn't working for you then there must be something else going on here, I'll wait and see what other answers people come back with! – Jamie Wade Jan 19 '15 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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