5

I've created a lightswitch field that defaults to "On", and it works fine for new entries, but for all existing entries it is set to "Off". I'm keen to avoid having to manually go through all existing entries switching it to "On" - is there a way of making existing entries respect the default value of this new field (rather than treating the absence of a value for it from when they were created as "Off")?

(Or alternatively: is there an easy way to set a field to "On" for all existing entries?)

8

If there was no default set beforehand, then your previous elements will have a value of null for that field. You should be able to include those in your "on" queries by querying for that null value as well as the "on" value in your templates:

{% set onEntries = craft.entries.yourLightswitch([null, '1']).find %}

This won't actually change the value of your previous elements though. One way to do that would be using a SQL query against the craft_content table to update rows (elements) that have null in that column:

UPDATE `craft_content` SET `field_yourLightswitch` = 1 WHERE `field_yourLightswitch` IS NULL;
  • Thanks for this. I really like the first idea, but looking at the content table, it looks like the value has been set to 0 (rather than null) for existing entries, so unfortunately the first approach probably won't work for me... However, that SQL query does the job perfectly! – Nick F Sep 1 '15 at 15:27
  • The SQL as it stands won't affect anything seeing as all the fields have values of 0 to start with. And if you change it to ...WHERE field_yourLightswitch is 0 then you could be setting it to 1 for entries that don't actually have that field in the CMS. I'm a bit wary about running this... – Phil Gyford Oct 21 '15 at 16:09
  • using NULL no rows affected, but when I change to 0 then I get SQL error. Anyone know how to fix this? [SQL]UPDATE craft_content`` SET ``field_enableAdvertisingBlock`` = 1 WHERE ``field_enableAdvertisingBlock`` IS 0; [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0' at line 1 -- ignore the double backticks.. code comments are buggy. – CreateSean Aug 22 '18 at 20:52
  • @CreateSean You'll want to use an = instead of IS for that, but that will update every single "off" switch to "on". It may have been that something has changed with the default column value for lightswitches since this answer, if you're not getting anything returned when using IS NULL – Mike Pepper Aug 24 '18 at 8:30

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.