Magento 2 with Full Page Cache: How to get product ID from a product page? - magento2

I am trying to find a solution to what seems to be a FPC-linked issue.
In my code I am using the following method in order to get the current product ID from a Product page.
$this->catalogSession->getData('last_viewed_product_id')
This worked just fine until I tried it on a website with Full Page Cache: in this case, it returns an empty value (maybe because the session data cannot be accessed from cache).
Does anyone know an alternative method to get the product ID from the current context?
I have tried this alternative synthax:
$_SESSION['catalog']['last_viewed_product_id'];

While not the best solution and definitely not best practice, you can use objectmanager:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$id = $product->getId();
This will get you the id but, as stated above, it's not suggested and you should create a block and inject the registry there and call it in your code.
You can see this post https://meetanshi.com/blog/get-current-product-id-in-magento-2/

Related

Retrieving the BackendUser from BackendUserAuthentication

I'm trying to develop an extension that adds a Button to the ClearCache menu in the TYPO3 Backend. In a large installation with multiple domains, non-admin users need a button to clear the page cache for their domain, but only of those pages that they have access to. The default options.clearCache.pages = 1 instead flushes the whole Frontend Cache of the installation.
I've gotten so far as to calling a method in a custom class ClearCacheHook, that implements \TYPO3\CMS\Backend\Toolbar\ClearCacheActionsHookInterface.
I next need to get a list of all page uids the BackendUser has access to, which is done with $backendUser->getDbMountPoints(). All the docs speak of a global variable $BE_USER, but this isn't set for me. I have a $GLOBALS['BE_USER'], but that is of the class BackendUserAuthentication.
I can't figure out how to resolve the BackendUser from the BackendUserAuthentication. Theres the BackendUser uid in the object so I tried initializing a TYPO3\\CMS\\Beuser\\Domain\\Repository\\BackendUserRepository via the ObjectManager, but that fails.
I'll focus on the more specific tasks: Create an instance of BackendUserRepository and create an instance of BackendUser from uid.
You might have a look at the UsernameViewHelper.php class of be_log in the TYPO3 core.
specifically this:
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Domain\Repository\BackendUserRepository;
use TYPO3\CMS\Extbase\Object\ObjectManager;
...
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$backendUserRepository = $objectManager->get(BackendUserRepository::class);
/** #var \TYPO3\CMS\Extbase\Domain\Model\BackendUser $user */
$user = $backendUserRepository->findByUid($uid);
If there is something, I don't find in the documentation, I sometimes look at existing extensions. A good candidate is the news extensions. Other good candidates are, of course, the TYPO3 source code.

Create a link in backend to a frontend page

I would link to create a link to a frontend page inside a backend module.
Using:
<f:link.page pageUid="40" >Link</f:link.page>
Doesn't work. It generates a link to the current backend module.
Any solution ?
Since TYPO3 v9 you can use the following lines of code:
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Routing\PageRouter;
$siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
$site = $siteFinder->getSiteByPageId($pageId);
$router = $site->getRouter();
$frontendUrl = (string) $router->generateUri($pageId);
Thanks to Benni Mack # TYPO3Camp Mitteldeutschland
This is a very long story but the gist is: it is not possible to create FE links in BE/CLI context without a lot of workarounds and dummy objects/values.
If possible you should use solutions like pagepath which generate URLs for an eID script which performs the actual URL generation on demand.

how to get static block content custom attributes by block id in magento

I am creating this below block content in admin HTML. I cant able to get the slidertype attributes in 3columns.phtml but in template page i can get
$this->getData('slidertype').
So kindly give the solution that how to get the following attributes.
{{block type="catalog/product_bestseller" name="bestseller" slidercount="20" slidertype="1" template="catalog/product/bestseller_right.phtml"}}
I am using the below code to get static block attribute value. Its working fine for us.
$bestSellerBlock = Mage::getModel('cms/block')
->setStoreId(Mage::app()->getStore()->getId())
->load("best_seller");
$bestSellerContentText = strip_tags($bestSellerBlock->getContent());
preg_match('/slidertype="(.*?)"/u',$bestSellerContentText,$sliderTypeArray);
$sliderType = trim($sliderTypeArray[1]);
Thanks,
Arularasan D.

How to add some extra parameter in the airbrake parameters for JS errors

When we are sending the airbrake error to the airbrake server, by default it includes the controller name and action name.
But the question is that I want to add some extra parameters like username, email of the current user. If anyone has any idea please suggest how to do that?
In my layout application.html:
- if ['development'].include?(Rails.env)
= airbrake_javascript_notifier
= render :partial => 'layouts/airbrake_notifier'
and in the partial I have written:
Airbrake.errorDefaults['name'] = "#{current_user.name}";<br/>
Airbrake.errorDefaults['email'] = "#{current_user.email}";<br/>
Airbrake.errorDefaults['phone'] = "#{current_user.phone}";<br/>
Airbrake.errorDefaults['title'] = "#{current_user.title;<br/>
Not a great solution, but the Airbrake Knowledge Base recommends essentially patching the airbrake gem source of the lib/airbrake/notice.rb file.
def initialize(args)
...
self.parameters = args[:parameters] ||
action_dispatch_params ||
rack_env(:params) ||
{'username' => current_user.name}
It would certainly be better to have this be configurable without patching source.
What I've done instead is simply add a few pieces of data to the session (current_user.name mainly), since session data is sent with the request. I wouldn't do this for more than a few little pieces of data.
We've just added getting current users into the Airbrake Gem.
https://github.com/airbrake/airbrake/wiki/Sending-current-user-information
You'll soon be able to sort by current user in an upcoming redesign of the UI.

Typo3 eID, how to access config

I've just created an eID in Typo3. I can't figure out how to access the config data for my plugin from the Typo3 instance.
I've tried the code from the link but it doesn't want to work. I keep getting an exception "No TypoScript template found! " on the call " $TSFE->getConfigArray(); "
http://lists.typo3.org/pipermail/typo3-dev/2006-December/021392.html
Any ideas?
Thanks.
In eID mode, only a small part of the regular TYPO3 frontend is loaded. Unfortunately TypoScript is not loaded. To still access the TypoScript configuration you need manually load the components it needs to do so. Unfortunately this can be a bit of a pain in the butt. So in some cases it might be easier to just load a page containing a single plugin that doesn't contain anything else (without headers etc.).
If you do want to load the TypoScript templates yourself, you can try something like the following:
require_once(PATH_tslib.'class.tslib_fe.php');
require_once(PATH_t3lib.'class.t3lib_userauth.php' );
require_once(PATH_tslib.'class.tslib_feuserauth.php');
require_once(PATH_t3lib.'class.t3lib_cs.php');
require_once(PATH_tslib.'class.tslib_content.php') ;
require_once(PATH_t3lib.'class.t3lib_tstemplate.php');
require_once(PATH_t3lib.'class.t3lib_page.php');
$TSFEclassName = t3lib_div::makeInstanceClassName('tslib_fe');
$id = isset($HTTP_GET_VARS['id'])?$HTTP_GET_VARS['id']:0;
$GLOBALS['TSFE'] = new $TSFEclassName($TYPO3_CONF_VARS, $id, '0', 1, '','','','');
$GLOBALS['TSFE']->connectToMySQL();
$GLOBALS['TSFE']->initFEuser();
$GLOBALS['TSFE']->fetch_the_id();
$GLOBALS['TSFE']->getPageAndRootline();
$GLOBALS['TSFE']->initTemplate();
$GLOBALS['TSFE']->tmpl->getFileName_backPath = PATH_site;
$GLOBALS['TSFE']->forceTemplateParsing = 1;
$GLOBALS['TSFE']->getConfigArray();
$cObj = t3lib_div::makeInstance('tslib_cObj');
This initializes the TSFE and cObj but is also used to load and parse the TypoScript templates. You might need to make some modifications to (probably kick some things out)
The code came from one of the comments on the following blog post: http://sebastiaandejonge.com/blog/articles/2010/september/21/bringing-ajax-to-your-frontend-plugins/
Good luck!