I've been trying to set the meta title of a product listing page when an action is executed. I found this post on Magento2 StackExchange and tried to replicate in my Controller:
<?php
namespace TreyBake\Garage\Controller\Index;
use Magento\Framework\App\Action\Context;
class Search extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $_pageConfig;
public function __construct(
Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Framework\View\Page\Config $pageConfig
)
{
$this->resultPageFactory = $resultPageFactory;
$this->_pageConfig = $pageConfig;
parent::__construct($context);
}
protected function _prepareLayout()
{
$this->_pageConfig->getTitle()->set('foo');
$pmt = $this->getLayout()->getBlock('page.main.title');
$pmt->setPageTitle('bar');
return parent::_prepareLayout();
}
public function execute()
{
# my controller exec code
$rpf = $this->resultPageFactory->create();
$pmt = $rpf->getLayout()->getBlock('page.main.title');
$pmt->setPageTitle('foobar');
# etc.
}
}
Disabling one at a time makes no change, and both uncommented has no affect. What am I doing wrong and how can I override the meta title (<title>
) for product listing pages using $_GET
params (though, really, if I know how to set the meta title correctly, I can fill in the blanks with $_GET)?
Update:
I think I know why this is so troublesome, the last line in the execute()
method is this:
$this->getResponse()->setRedirect($backUrl);
doing a log of this shows the $backUrl
to equate to:
http://site.development/wheel-tyres/tyres.html?find=aprilia-af-1-futura-1990-4730&sid=cbFktM0OTy
So I don't think I can return $resultPageFactory
as, it's redirected before it's returned.
My Edited Question: How do I set the meta title with redirect?
Another Update
I tried using getResponse()
to set the data, as I did some logging and it doesn't seem I can use it:
$writer = new \Zend\Log\Writer\Stream(BP. '/var/log/dev.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info(
print_r(
get_class_methods($this->getResponse),
true
)
);
This led me to three functions of interest:
getHeaders()
getMetaData()
setMetaData()
I then logged the get* functions and getMetaData()
was empty, getHeaders had data, but I overlooked what it might mean, headers are the HTTP headers (duh).
I then used setMetaData('title', 'foo')
and logged getMetaData
after that and huzzah, my data is there - however, the title for the page remains the same.. again, I'm guessing because of the redirect.