How to add variable to header.php controller and use it in header.tpl - opencart2.3

I am creating a custom theme for OpenCart 2.3 and I need to show some additional information in page header (header.tpl). So I added some variable to catalog/controller/common/header.php:
$data['some_var'] = 'some_value';
And then I am trying to use this data in the header.tpl:
<?php echo $this->data['some_var']; ?>
But I am always getting this error:
Notice: Undefined index: some_var in /var/www/store_com/public_html/catalog/view/theme/mystore/template/common/header.tpl on line 133
If I try to use this code:
<?php echo $some_var; ?>
Then I am getting another error:
Notice: Undefined variable: some_var in /var/www/store_com/public_html/catalog/view/theme/mystore/template/common/header.tpl on line 133
And even when I do echo print_r($this->data) in header.tpl I don't even see this variable in $data array.
What am I doing wrong? Please help.
EDIT
Here is the full code of my header.php controller file. I added my custom variable at the very end of the file.
class ControllerCommonHeader extends Controller {
public function index() {
// Analytics
$this->load->model('extension/extension');
$data['analytics'] = array();
$analytics = $this->model_extension_extension->getExtensions('analytics');
foreach ($analytics as $analytic) {
if ($this->config->get($analytic['code'] . '_status')) {
$data['analytics'][] = $this->load->controller('extension/analytics/' . $analytic['code'], $this->config->get($analytic['code'] . '_status'));
}
}
if ($this->request->server['HTTPS']) {
$server = $this->config->get('config_ssl');
} else {
$server = $this->config->get('config_url');
}
if (is_file(DIR_IMAGE . $this->config->get('config_icon'))) {
$this->document->addLink($server . 'image/' . $this->config->get('config_icon'), 'icon');
}
$data['title'] = $this->document->getTitle();
$data['base'] = $server;
$data['description'] = $this->document->getDescription();
$data['keywords'] = $this->document->getKeywords();
$data['links'] = $this->document->getLinks();
$data['styles'] = $this->document->getStyles();
$data['scripts'] = $this->document->getScripts();
$data['lang'] = $this->language->get('code');
$data['direction'] = $this->language->get('direction');
$data['name'] = $this->config->get('config_name');
if (is_file(DIR_IMAGE . $this->config->get('config_logo'))) {
$data['logo'] = $server . 'image/' . $this->config->get('config_logo');
} else {
$data['logo'] = '';
}
$this->load->language('common/header');
$data['text_home'] = $this->language->get('text_home');
// Wishlist
if ($this->customer->isLogged()) {
$this->load->model('account/wishlist');
$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), $this->model_account_wishlist->getTotalWishlist());
} else {
$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));
}
$data['text_shopping_cart'] = $this->language->get('text_shopping_cart');
$data['text_logged'] = sprintf($this->language->get('text_logged'), $this->url->link('account/account', '', true), $this->customer->getFirstName(), $this->url->link('account/logout', '', true));
$data['text_account'] = $this->language->get('text_account');
$data['text_register'] = $this->language->get('text_register');
$data['text_login'] = $this->language->get('text_login');
$data['text_order'] = $this->language->get('text_order');
$data['text_transaction'] = $this->language->get('text_transaction');
$data['text_download'] = $this->language->get('text_download');
$data['text_logout'] = $this->language->get('text_logout');
$data['text_checkout'] = $this->language->get('text_checkout');
$data['text_category'] = $this->language->get('text_category');
$data['text_all'] = $this->language->get('text_all');
$data['home'] = $this->url->link('common/home');
$data['wishlist'] = $this->url->link('account/wishlist', '', true);
$data['logged'] = $this->customer->isLogged();
$data['account'] = $this->url->link('account/account', '', true);
$data['register'] = $this->url->link('account/register', '', true);
$data['login'] = $this->url->link('account/login', '', true);
$data['order'] = $this->url->link('account/order', '', true);
$data['transaction'] = $this->url->link('account/transaction', '', true);
$data['download'] = $this->url->link('account/download', '', true);
$data['logout'] = $this->url->link('account/logout', '', true);
$data['shopping_cart'] = $this->url->link('checkout/cart');
$data['checkout'] = $this->url->link('checkout/checkout', '', true);
$data['contact'] = $this->url->link('information/contact');
$data['telephone'] = $this->config->get('config_telephone');
// Menu
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$data['categories'] = array();
$categories = $this->model_catalog_category->getCategories(0);
foreach ($categories as $category) {
if ($category['top']) {
// Level 2
$children_data = array();
$children = $this->model_catalog_category->getCategories($category['category_id']);
foreach ($children as $child) {
$filter_data = array(
'filter_category_id' => $child['category_id'],
'filter_sub_category' => true
);
$children_data[] = array(
'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
}
// Level 1
$data['categories'][] = array(
'name' => $category['name'],
'children' => $children_data,
'column' => $category['column'] ? $category['column'] : 1,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
}
$data['language'] = $this->load->controller('common/language');
$data['currency'] = $this->load->controller('common/currency');
$data['search'] = $this->load->controller('common/search');
$data['cart'] = $this->load->controller('common/cart');
// For page specific css
if (isset($this->request->get['route'])) {
if (isset($this->request->get['product_id'])) {
$class = '-' . $this->request->get['product_id'];
} elseif (isset($this->request->get['path'])) {
$class = '-' . $this->request->get['path'];
} elseif (isset($this->request->get['manufacturer_id'])) {
$class = '-' . $this->request->get['manufacturer_id'];
} elseif (isset($this->request->get['information_id'])) {
$class = '-' . $this->request->get['information_id'];
} else {
$class = '';
}
$data['class'] = str_replace('/', '-', $this->request->get['route']) . $class;
} else {
$data['class'] = 'common-home';
}
//CUSTOM THEME VARIABLES BEGIN
$data['some_var'] = 'some_value';
//CUSTOM THEME VARIABLES END
return $this->load->view('common/header', $data);
}
}

I need to see your controller to get the full picture and then i will give you the full answer, but take a look on your controller and make sure that you bind your data like the sample below:
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/header.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/common/header.tpl', $data);
} else {
return $this->load->view('default/template/common/header.tpl', $data);
}
Thanks

I finally found the solution of my problem, but I am not sure if it is the right way to do this. I found that I need to make changes in system/storage/modification/catalog/controller/common/header‌​.php. It seems like after installing some extension via Vqmod the controller file have been copied to this folder. If I add my variables there then I can access them without any issues.

Related

Magento 2 - Update Product stock and Price Programmatically for multiple stores

I'm getting data from the CSV file and according to SKU file load the product.
We are getting 30 products from the CSV file and update those product data in Magento.
We have set up cron every 5 minutes and after 5 minutes it will get the next 30 products and update.
The starting process script is working fine. But after the sometime script is going to be slow and it will take time to update the product.
So, the next cron is running at on the same time there are lots of scripts are running on the server, and the server load will increase.
After taking so much load on the server website going to be slow.
Can you please let me know the way so product updating process will be consistent and time will not so much vary.
public function execute()
{
$data = array of csv file data;
$sql = "Select value FROM " . $tableName . " where path='catalog/product/update_cron' and scope_id=0";
$result = $connection->fetchAll($sql);
$update_cron = $result[0]['value'];
$total_products = count($data);
if ($total_products == $update_cron) {
$this->configWriter->save('catalog/product/update_cron_status', '1', 'default', '0'); // inject Magento\Store\Model\ScopeInterface;
exit;
}
if ($update_cron != '' && $update_cron != 0) {
$data = array_slice($data, (int)$update_cron, 30);
} else {
$update_cron = 0;
$data = array_slice($data, 0, 30);
}
$current_date = date("m/d/Y");
$i = 0;
foreach ($data as $key => $value) {
/*********************************************Update Product Price********************************************************/
if ($value['Artikel'] != '') {
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product_id = $product->getIdBySku($value['Artikel']);
if (!empty($product_id)) {
/************************Update Product Price for all Stores**************************************/
$price_b2b = str_replace(',', '.', (string) $value['Verkoopprijs']);
$price_b2c = str_replace(',', '.', (string) $value['Numeriek1']);
$price_club = str_replace(',', '.', (string) $value['Numeriek2']);
//$special_price_b2b = str_replace(',', '.', (string) $value['Numeriek3']);
$productActionObject = $objectManager->create('Magento\Catalog\Model\Product\Action');
$productActionObject->updateAttributes(array($product_id),
array(
'name' => $value['Artikel'],
'ean_code'=>$value['Barcode'],
'price'=>$price_b2c,
'price_wholesale'=>$price_b2b,
'price_clubs'=>$price_club,
'description'=>$value['Omschrijving Engels'],
),0
);
/* if ($value['Boolean1'] == 'True') {
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => $special_price_b2b, 'special_from_date' => $current_date), 4);
} else { */
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => '', 'special_from_date' => ''), 4);
//}
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_club), 7);
/*********************************************Inventory Update********************************************************/
$stockRegistry = $objectManager->create('Magento\CatalogInventory\Api\StockRegistryInterface');
$sku = $value['Artikel'];
if($sku != '')
{
$qty = round(str_replace(',', '', (string) $value['Stock']));
$stockItem = $stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($value['Stock']);
$stockItem->setIsInStock((int) ($qty > 0)); // this line
$stockRegistry->updateStockItemBySku($sku, $stockItem);
}
/*****************************************************************************************************/
}
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
else {
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
}
die('records completed');
}
}
die('stop');
}
Thanks in advance

Showing course image on custom page in Moodle

I have created a custom page on which all available courses are displayed. I have also uploaded the image for the course and now want to show the name of the course along with the image. I am able to get the names of courses from the database but how to get the image.
Try something like this
// Create a course_in_list object to use the get_course_overviewfiles() method.
require_once($CFG->libdir . '/coursecatlib.php');
$course = new course_in_list($courseid);
$outputimage = '';
foreach ($course->get_course_overviewfiles() as $file) {
if ($file->is_valid_image()) {
$imagepath = '/' . $file->get_contextid() .
'/' . $file->get_component() .
'/' . $file->get_filearea() .
$file->get_filepath() .
$file->get_filename();
$imageurl = file_encode_url($CFG->wwwroot . '/pluginfile.php', $imagepath,
false);
$outputimage = html_writer::tag('div',
html_writer::empty_tag('img', array('src' => $imageurl)),
array('class' => 'courseimage'));
// Use the first image found.
break;
}
}
echo $outputimage;
You may get course image directly from 'overviewfiles' files area.
function get_course_image()
{
global $COURSE;
$url = '';
require_once( $CFG->libdir . '/filelib.php' );
$context = context_course::instance( $COURSE->id );
$fs = get_file_storage();
$files = $fs->get_area_files( $context->id, 'course', 'overviewfiles', 0 );
foreach ( $files as $f )
{
if ( $f->is_valid_image() )
{
$url = moodle_url::make_pluginfile_url( $f->get_contextid(), $f->get_component(), $f->get_filearea(), null, $f->get_filepath(), $f->get_filename(), false );
}
}
return $url;
}

Add several records in moodle

I've been having trouble adding items in my table in moodle, this is what I've trying with no success.
$totalrec = array();
$rec2 = $DB->get_records('table1', null, '', '*', 0, 0);
$rec4 = $DB->get_records('table2', array('x' => 'y') , '', '*', 0, 0);
foreach ($rec2 as $records2) {
$rec3 = $DB->get_records('z', array('m' => 'n') , '', '*', 0, 0);
foreach ($rec3 as $records3) {
if (isset($_REQUEST['a']) && isset($_REQUEST['b'])) {
$ca = $_REQUEST['a'];
$co = $_REQUEST['b'];
$pi = $records2->idp;
$recorsh = new class ();
$recorsh->id = $records2->id;
$recorsh->te = $co;
$recorsh->idt = $ti;
$recorsh->res = $ca;
$recorsh->ida = $idaud;
$totalrec[$n] = array($recorsh);
$n++;
}
}
}
$lastinsertid2 = $DB->insert_records('table4', $totalrec);
and, this one:
$rec2 = $DB->get_records('table1', null, '', '*', 0, 0);
$rec4 = $DB->get_records('table2', array('x' => 'y') , '', '*', 0, 0);
foreach($rec2 as $records2) {
$rec3 = $DB->get_records('z', array('m' => 'n') , '', '*', 0, 0);
foreach($rec3 as $records3) {
if (isset($_REQUEST['a']) && isset($_REQUEST['b'])) {
$ca = $_REQUEST['a'];
$co = $_REQUEST['b'];
$pi = $records2->idp;
$recorsh = new class ();
$recorsh->id = $records2->id;
$recorsh->te = $co;
$recorsh->idt = $ti;
$recorsh->res = $ca;
$recorsh->ida = $idaud;
$lastinsertid = $DB->insert_record('table4', $recorsh, false);
}
}
}
Both of them gives me a "Error writing to database" but doesn't say anything specific, I know that I'm not doing the inserting "in the right way" but I don't know how to do it, what am I doing wrong?
It's probably because the ID is added to each object before inserting.
$recorsh->id = $records2->id;
Like davosmith says, during development always have debugging set to developer level.
In your config.php have this
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 0);
$CFG->debug = E_ALL | E_STRICT; // 32767;
$CFG->debugdisplay = true;
Also never ever use $_REQUEST or $_GET or $_POST directly. This can introduce SQL injection.
Use
$a = optional_param('a', null, PARAM_XXX);
$b = optional_param('b', null, PARAM_XXX);
or
$a = required_param('a', PARAM_XXX);
$b = required_param('b', PARAM_XXX);
Change PARAM_XXX to the type of parameter you are expecting. eg PARAM_INT, PARAM_BOOL etc.

Zend for picture uploads needing to resize images

So, I am using Zend to handle my image uploads. This script works well, but I was wondering if there is a way to resize the image that is being uploaded no matter what the current size is. I've seen 2 similar posts, but their code was entirely different, thus would be difficult to translate into mine from theirs. If possible, I would really like to not have to use extensions, but I will if I have to. Any ideas?
if (isset($_POST['upload'])) {
require_once('scripter/lib.php');
//try {
$destination = 'C:\----';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '10000kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
//$pic = $filename;
if (!$uploader->isValid() || $errors) {
$messages = $uploader->getMessages();
} else {
//$pic = $filename;
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
//$pic = $no_spaces;
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$pic = "imgs/upld/" . $no_spaces;
$uploaded .= " and renamed $no_spaces";
//$pic = $no_spaces;
//$pic = $uploader->getFileName(NULL, FALSE);
} else {$pic = "imgs/upld/" . $filename;;}
$messages[] = "$uploaded";
//$pic = $no_spaces;
}
Zend Framework does not ship with a component for handling images.
Good News! PHP has several components that are really good at dealing with all kinds of image issues.
GD (one of those great PHP extensions) is currently shipped as a core extension for PHP, perhaps you will find it useful.
Maybe this will help: http://phpcodeforbeginner.blogspot.com/2013/04/resize-image-or-crop-image-using-gd.html
(not really trying to be too snarky ;)

tt_news: Modify image src

In order to be able to use lazy loading, I need to modify the src attribute of tt_news' image output like so:
<img src="/foo/bar/baz.png" … /> // <-- before
<img data-original="/foo/bar/baz.png" … /> // <-- after, no src!
I have tried:
plugin.tt_news.displayList.content_stdWrap {
parseFunc < lib.parseFunc_RTE
HTMLparser = 1
HTMLparser.keepNonMatchedTags = 1
HTMLparser.tags.img.fixAttrib.src.unset = 1
}
but to no avail, since
The image in question is not being inserted via RTE, but the "normal" media integration.
That wouldn't copy the src attribute over to data-original before unsetting.
So, what should I do aside from pulling my hair out?
This cannot be solved via typoscript, because the src attribute is hard coded in the cImage function:
$theValue = '<img src="' . htmlspecialchars($GLOBALS['TSFE']->absRefPrefix .
t3lib_div::rawUrlEncodeFP($info[3])) . '" width="' . $info[0] . '" height="' . $info[1] . '"' .
$this->getBorderAttr(' border="' . intval($conf['border']) . '"') .
$params .
($altParam) . ' />';
The only way I see to modify the src attribute is through a user function. tt_news provides a hook for a user function that allows the custom processing of images (see line 2150 of class.tx_ttnews.php).
Example:
Insert the following typoscript:
includeLibs.user_ttnewsImageMarkerFunc = fileadmin/templates/php/user_ttnewsImageMarkerFunc.php
plugin.tt_news.imageMarkerFunc = user_ttnewsImageMarkerFunc->ttnewsImageMarkerFunc
Whereas the file user_ttnewsImageMarkerFunc.php contains:
<?php
class user_ttnewsImageMarkerFunc {
/**
* Fills the image markers with data.
*
* #param array $paramArray: $markerArray and $config of the current news item in an array
* #param [type] $conf: ...
* #return array the processed markerArray
*/
function ttnewsImageMarkerFunc($paramArray, $conf) {
$markerArray = $paramArray[0];
$lConf = $paramArray[1];
$pObj = &$conf['parentObj'];
$row = $pObj->local_cObj->data;
$imageNum = isset($lConf['imageCount']) ? $lConf['imageCount'] : 1;
$imageNum = t3lib_div::intInRange($imageNum, 0, 100);
$theImgCode = '';
$imgs = t3lib_div::trimExplode(',', $row['image'], 1);
$imgsCaptions = explode(chr(10), $row['imagecaption']);
$imgsAltTexts = explode(chr(10), $row['imagealttext']);
$imgsTitleTexts = explode(chr(10), $row['imagetitletext']);
reset($imgs);
if ($pObj->config['code'] == 'SINGLE') {
$markerArray = $this->getSingleViewImages($lConf, $imgs, $imgsCaptions, $imgsAltTexts, $imgsTitleTexts, $imageNum, $markerArray, $pObj);
} else {
$imageMode = (strpos($textRenderObj, 'LATEST') ? $lConf['latestImageMode'] : $lConf['listImageMode']);
$suf = '';
if (is_numeric(substr($lConf['image.']['file.']['maxW'], - 1))) { // 'm' or 'c' not set by TS
if ($imageMode) {
switch ($imageMode) {
case 'resize2max' :
$suf = 'm';
break;
case 'crop' :
$suf = 'c';
break;
case 'resize' :
$suf = '';
break;
}
}
}
// only insert width/height if it is not given by TS and width/height is empty
if ($lConf['image.']['file.']['maxW'] && ! $lConf['image.']['file.']['width']) {
$lConf['image.']['file.']['width'] = $lConf['image.']['file.']['maxW'] . $suf;
unset($lConf['image.']['file.']['maxW']);
}
if ($lConf['image.']['file.']['maxH'] && ! $lConf['image.']['file.']['height']) {
$lConf['image.']['file.']['height'] = $lConf['image.']['file.']['maxH'] . $suf;
unset($lConf['image.']['file.']['maxH']);
}
$cc = 0;
foreach ($imgs as $val) {
if ($cc == $imageNum)
break;
if ($val) {
$lConf['image.']['altText'] = $imgsAltTexts[$cc];
$lConf['image.']['titleText'] = $imgsTitleTexts[$cc];
$lConf['image.']['file'] = 'uploads/pics/' . $val;
$theImgCode .= str_replace('src="', 'class="lazy" data-original="', $pObj->local_cObj->IMAGE($lConf['image.'])) . $pObj->local_cObj->stdWrap($imgsCaptions[$cc], $lConf['caption_stdWrap.']);
}
$cc++;
}
if ($cc) {
$markerArray['###NEWS_IMAGE###'] = $pObj->local_cObj->wrap($theImgCode, $lConf['imageWrapIfAny']);
} else {
$markerArray['###NEWS_IMAGE###'] = $pObj->local_cObj->stdWrap($markerArray['###NEWS_IMAGE###'], $lConf['image.']['noImage_stdWrap.']);
}
}
if ($pObj->debugTimes) {
$pObj->hObj->getParsetime(__METHOD__);
}
// debug($markerArray, '$$markerArray ('.__CLASS__.'::'.__FUNCTION__.')', __LINE__, __FILE__, 2);
return $markerArray;
}
/**
* Fills the image markers for the SINGLE view with data. Supports Optionssplit for some parameters
*
* #param [type] $lConf: ...
* #param [type] $imgs: ...
* #param [type] $imgsCaptions: ...
* #param [type] $imgsAltTexts: ...
* #param [type] $imgsTitleTexts: ...
* #param [type] $imageNum: ...
* #return array $markerArray: filled markerarray
*/
function getSingleViewImages($lConf, $imgs, $imgsCaptions, $imgsAltTexts, $imgsTitleTexts, $imageNum, $markerArray, $pObj) {
$marker = 'NEWS_IMAGE';
$sViewSplitLConf = array();
$tmpMarkers = array();
$iC = count($imgs);
// remove first img from image array in single view if the TSvar firstImageIsPreview is set
if (($iC > 1 && $pObj->config['firstImageIsPreview']) || ($iC >= 1 && $pObj->config['forceFirstImageIsPreview'])) {
array_shift($imgs);
array_shift($imgsCaptions);
array_shift($imgsAltTexts);
array_shift($imgsTitleTexts);
$iC--;
}
if ($iC > $imageNum) {
$iC = $imageNum;
}
// get img array parts for single view pages
if ($pObj->piVars[$pObj->config['singleViewPointerName']]) {
/**
* TODO
* does this work with optionsplit ?
*/
$spage = $pObj->piVars[$pObj->config['singleViewPointerName']];
$astart = $imageNum * $spage;
$imgs = array_slice($imgs, $astart, $imageNum);
$imgsCaptions = array_slice($imgsCaptions, $astart, $imageNum);
$imgsAltTexts = array_slice($imgsAltTexts, $astart, $imageNum);
$imgsTitleTexts = array_slice($imgsTitleTexts, $astart, $imageNum);
}
if ($pObj->conf['enableOptionSplit']) {
if ($lConf['imageMarkerOptionSplit']) {
$ostmp = explode('|*|', $lConf['imageMarkerOptionSplit']);
$osCount = count($ostmp);
}
$sViewSplitLConf = $pObj->processOptionSplit($lConf, $iC);
}
// reset markers for optionSplitted images
for ($m = 1; $m <= $imageNum; $m++) {
$markerArray['###' . $marker . '_' . $m . '###'] = '';
}
$cc = 0;
foreach ($imgs as $val) {
if ($cc == $imageNum)
break;
if ($val) {
if (! empty($sViewSplitLConf[$cc])) {
$lConf = $sViewSplitLConf[$cc];
}
// if (1) {
// $lConf['image.']['imgList.'] = '';
// $lConf['image.']['imgList'] = $val;
// $lConf['image.']['imgPath'] = 'uploads/pics/';
// debug($lConf['image.'], ' ('.__CLASS__.'::'.__FUNCTION__.')', __LINE__, __FILE__, 3);
//
// $imgHtml = $pObj->local_cObj->IMGTEXT($lConf['image.']);
//
// } else {
$lConf['image.']['altText'] = $imgsAltTexts[$cc];
$lConf['image.']['titleText'] = $imgsTitleTexts[$cc];
$lConf['image.']['file'] = 'uploads/pics/' . $val;
$imgHtml = str_replace('src="', 'class="lazy" data-original="', $pObj->local_cObj->IMAGE($lConf['image.'])) . $pObj->local_cObj->stdWrap($imgsCaptions[$cc], $lConf['caption_stdWrap.']);
// }
//debug($imgHtml, '$imgHtml ('.__CLASS__.'::'.__FUNCTION__.')', __LINE__, __FILE__, 3);
if ($osCount) {
if ($iC > 1) {
$mName = '###' . $marker . '_' . $lConf['imageMarkerOptionSplit'] . '###';
} else { // fall back to the first image marker if only one image has been found
$mName = '###' . $marker . '_1###';
}
$tmpMarkers[$mName]['html'] .= $imgHtml;
$tmpMarkers[$mName]['wrap'] = $lConf['imageWrapIfAny'];
} else {
$theImgCode .= $imgHtml;
}
}
$cc++;
}
if ($cc) {
if ($osCount) {
foreach ($tmpMarkers as $mName => $res) {
$markerArray[$mName] = $pObj->local_cObj->wrap($res['html'], $res['wrap']);
}
} else {
$markerArray['###' . $marker . '###'] = $pObj->local_cObj->wrap($theImgCode, $lConf['imageWrapIfAny']);
}
} else {
if ($lConf['imageMarkerOptionSplit']) {
$m = '_1';
}
$markerArray['###' . $marker . $m . '###'] = $pObj->local_cObj->stdWrap($markerArray['###' . $marker . $m . '###'], $lConf['image.']['noImage_stdWrap.']);
}
// debug($sViewSplitLConf, '$sViewSplitLConf ('.__CLASS__.'::'.__FUNCTION__.')', __LINE__, __FILE__, 2);
return $markerArray;
}
}
?>
Most of this code is copied from class.tx_ttnews.php. The important line is the following (in each of the two functions):
str_replace('src="', 'class="lazy" data-original="', $pObj->local_cObj->IMAGE($lConf['image.']))
Then you'll get the following image tags:
<img class="lazy" data-original="uploads/pics/myimage.jpg" width="110" height="70" border="0" alt="" />
In 2019 tt_news is still around. I use it with TYPO3 8 LTS, the version from github as its not anymore in the official extension repository. (For new Projects use "news")
So I think, because tt_news has to be updated in TYPO3 9, its legit to just hack the code directly, by changing tt_news/Classes/Plugin/TtNews.php like this:
--- a/Classes/Plugin/TtNews.php
+++ b/Classes/Plugin/TtNews.php
## -2621,6 +2621,7 ## class TtNews extends AbstractPlugin
$markerArray['###NEWS_IMAGE###'] = $this->local_cObj->stdWrap($markerArray['###NEWS_IMAGE###'],
$lConf['image.']['noImage_stdWrap.']);
}
+ $markerArray['###NEWS_IMAGE###'] = $this->LazyLoading($markerArray['###NEWS_IMAGE###']);
}
}
## -2632,6 +2633,13 ## class TtNews extends AbstractPlugin
}
+ function LazyLoading($html){
+ $html = str_replace('src="', 'class="lazy" data-original="', $html);
+ return $html;
+ }
+
+
/**
* Fills the image markers for the SINGLE view with data. Supports Optionssplit for some parameters
*