K
K
Kevin Mitnick2019-05-11 12:55:55
MODX
Kevin Mitnick, 2019-05-11 12:55:55

Why does assigning a value to TV work every other time?

There is a plugin that fires during the 'OnWebPagePrerender' event, inside the plugin I perform a series of actions and save the resource's TV value like this:

$tvcid = $modx->getObject('modTemplateVar',array('name' => 'views'));
$tvcid->setValue($modx->resource->get("id"), $views);
$tvcid->save();
$modx->cacheManager->clearCache();

Also tried like this:
$modx->resource->setTVValue('views', $views);
$modx->resource->save();

And in the first and other cases, the code does not work correctly, the value changes every other time, or even less often, it is not clear what this is connected with. This part of the code is 100% called, I checked.
Code for calculating views variable:
$views = $modx->resource->getTVValue("views");
$views = empty($views) ? 1 : ((int)$views + 1);

What could be the problem and how to fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kevin Mitnick, 2019-05-14
@volfing

As a result, the problem was in the cache of the resource itself. Despite the fact that the plugin executed correctly every time, regardless of the cache, the resource itself was cacheable and, as a result, gave out-of-date data. In my case, disabling the resource cache is completely inappropriate, I solved the problem by creating a new table in the database.

$views = $modx->query("SELECT * FROM `news_views` WHERE `news_id`='{$modx->resource->get('id')}'");
        
$views = $views->fetch(PDO::FETCH_ASSOC);
        
if(empty($views)){
    $modx->query("INSERT INTO `news_views`(`news_id`, `count`) VALUES({$modx->resource->get('id')}, 1)");
}else{
    $views = $views["count"] + 1;
    $modx->query("UPDATE `news_views` SET count=count+1 WHERE news_id={$modx->resource->get('id')}");
}

A
Alexander, 2019-05-11
@NeiroNx

The problem is that the page is served from the cache most likely, but the code is not executed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question