Change a Field’s Value Across Selected Entries Using Craft 3

Problem

You want to change the values to fields in entries, users, etc, using Craft 3 but you are not a MySQL expert.

For example, let’s say you have 1000 entries in a channel and you want to change the value of one field from “Foo” to “Bar”. Manually changing it in the CMS and saving each entry by hand is out of the question. You could run an SQL query in the database itself but you don’t know what you’re doing. This trick will make it easier for you.

Solution

You can use Twig to loop through whichever elements you select, change the values of a designated field, and then save those elements.

First, take a backup of your database. Since you’re going to be making changes to potentially many entries, users, etc, it’s possible you make a mistake and want to revert it back.

Second, you need to choose a template for your code snippet to sit in, whether it’s an existing template or a temporary test template created for the purpose of this task.

Third, select whatever elements you want. In this case it’s entries. Chain all the parameters needed to fine-tune your query.

{% set entries = craft.entries().section('mySectionHandle').all() %}

Then you will loop through that query and use Twig’s {% do %} tag to run an action on each entry without printing anything to a template.

{% for entry in entries %}
    {# 1. Sets the field's new value for this entry #}
    {% do entry.setFieldValue('fieldHandle', 'New Value') %}

    {# 2. Saves the entry with its new value changed #}
    {% do craft.app.getElements().saveElement(entry) %}
{% endfor %}

Next, on the front-end of your site, go to the URL that uses the template this Twig code sits on. By loading the page, the Twig code will run and adjust the value in the database for each entry in the loop.

Finally, if you check your entries in the CMS, you should see the values of those fields changed. If you’re satisfied with the results, remove this code or delete your test template.

Discussion

Note that this example uses .entries(), but it could very well be .users() or any other Craft element.