Scenario: I want to programatically bulk resave entries in a certain Site in a certain Section of a certain Type.
I have a Craft 3 Module with a Console Controller containing following code:
public function actionResaveEntries()
{
$site = Craft::$app->sites->getSiteById(self::SITE_ID);
$section = Craft::$app->sections->getSectionById(self::SECTION_ID);
$entryType = Craft::$app->sections->getEntryTypeById(self::ENTRY_TYPE_ID);
Craft::$app->getQueue()->push(new ResaveElements([
'description' => Craft::t('app', 'Resaving {section}, {type} entries', [
'section' => $section, 'type' => $entryType->name,
]),
'elementType' => Entry::class,
'criteria' => [
'siteId' => $site->id,
'sectionId' => $section->id,
'typeId' => $entryType->id,
'status' => null,
'enabledForSite' => true
]
]));
$result = 'something';
echo "Resaving entries\n";
return $result;
}
This works as expected when running ./craft resave-entries-module/resave-entries/resave-entries
from the command line & also via a cron job.
However, I now want to modify my code to run Craft::$app->getQueue()->push(new ResaveElements()
only under certain conditions. Specifically, when a deadline (custom date/time field in entry type) has passed.
I tried following, but it doesn't run at all regardless if before or after deadline date. The conditional seems to be ignored.
public function actionResaveEntries()
{
$site = Craft::$app->sites->getSiteById(self::SITE_ID);
$section = Craft::$app->sections->getSectionById(self::SECTION_ID);
$entryType = Craft::$app->sections->getEntryTypeById(self::ENTRY_TYPE_ID);
$entries = Entry::find()
->siteId(self::SITE_ID)
->sectionId(self::SECTION_ID)
->typeId(self::COMP_ENTRY_TYPE_ID)
->all();
foreach ($entries as $entry) {
// Set deadline
$deadline = $entry->competitionJudgingEnd;
// Check if after deadline
$now = new DateTime();
if ($now > $deadline) {
Craft::$app->getQueue()->push(new ResaveElements([
'description' => Craft::t('app', 'Resaving {section}, {type} entries', [
'section' => $section, 'type' => $entryType->name,
]),
'elementType' => Entry::class,
'criteria' => [
'siteId' => $site->id,
'sectionId' => $section->id,
'typeId' => $entryType->id,
'status' => null,
'enabledForSite' => true
]
]));
//$result = 'something';
echo "Resaving entries\n";
//return $result;
} else {
//$result = 'nothing';
echo "Not resaving entries\n";
//return $result;
}
}
In an effort to troubleshoot, I changed the conditional to if ($entry->title == "A known title")
, but it also seems to be ignored. I.e. resave not occurring.
What am I doing wrong, and what can I do to get this working?
UPDATE 01: The conditionals are actually working. There are 3 entries that meet criteria in $entries = Entry::find()
. However, the loop seems to be stop at the first entry. This entry changes if I change the criteria.
UPDATE 02: It looks like the return $result;
was breaking the loop. Updated code above by commenting out return statements.