Magento2: Translations are not working when executed from Crontab or Commandline

Today I faced an issue with a new project on Magento 2.3.2.

In a Cron class method the system should create a defined order, invoice it and send a special E-Mail with an PDF attached.

The problem was, that the translation were not working – even if the Store was set correctly for the Transactional-Emails.

After some research I finally found a solution that is working.

The secret is, to initiate the Area translation.
You can do this like in the following Code.

/**
 * Execute the cron process
 *
 * @throws \Exception
 */
public function execute()
{
    /**
     * enable translations for emails
     * and also for pdfs creations
     */
    $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND);
    $areaList = $this->getAreaList();
    $areaList->getArea(\Magento\Framework\App\Area::AREA_CRONTAB)
            ->load(\Magento\Framework\App\Area::PART_TRANSLATE);

    /** cron process logic **/
}

The method $this->getAreaList() simply returns an instance of \Magento\Framework\App\AreaList.

After that, the translation is initiated with the load method.

This makes the translation used in between the cron process (or any other command-line execution) work again.

Leave a Reply

Your email address will not be published. Required fields are marked *