I'm building a component in which the value of a number should be increased every 2 hours by 0.1.

What would be the best solution for that? I have a field type number with the value 1200 by default.

Is there a way I can change in the dashboard this value every 2 hours? Or Should I do it in Twig and push it somehow to the Database? Is there a way to update the field from twig to DB?

1 Answer 1


You can create a controller command that does that and call it in set intervals from a cronjob. The controller command will find the element that's storing your number, increment the number by the set interval and then save it. Something like this:

$entryWithNumberField = \craft\elements\Entry::find()
$currentNumber = $entryWithNumberField->getFieldValue('my_number_field');
$entryWithNumberField->setFieldValue('my_number_field', $currentNumber + 0.2);

However, this isn't a great solution as its very error prone. If the cron job fails for any reason (the server rebooting as part of a planned maintenance, for instance), the number will no longer be accurate.

Instead of saving the number every two hours, simply calculate the current number wherever you need to use it based on the defined starting point and the current time. This way, it will always be accurate, won't have the possibility for race conditions or be dependent on the previous state.

For example:

$entry = Entry::find()->my_number_field(':notempty:')->one();

$offset = $entry->my_number_field;

$now = time();
$start = $entry->dateCreated->getTimestamp();
$twoHourIntervalsPassed = floor($now - $start / 3600 / 2);
$incrementBy = $twoHourIntervalsPassed * 0.2;
$final = $offset + $incrementBy;
  • Thank you, it seems correct, I'll give it a shot on Monday :)
    – loliki
    May 20 at 20:17

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.