I have some code that, when a button is clicked, sets a session value to 1. Then (in the same frontend place) checks that value and if present, do something else.
This is my Controller (skimmed to relevant code):
<?php
namespace Vendor\Module\Controller\Index;
class Search extends Action
{
const USERBIKE = 'userbike';
public function execute()
{
# other code
if ($this->getRequest()->getParam(self::USERBIKE)) {
$block = $this->layoutFactory->create()->createBlock('Vendor\Module\Block\Garage');
if ($block->getGarageCollection()->getFirstItem()->getCustomerId()) {
$block->getCoreSession()->setUserBike(1);
}
$writer = new \Zend\Log\Writer\Stream(BP. '/var/log/logfile.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info(print_r($block->getCoreSession()->getUserBike(), true));
}
# other code
}
}
Which takes data from this .phtml form:
<?php
$vendorBlock = $block->getLayout()->createBlock('Vendor\Module\Block\Garage');
$session = $vendorBlock->getCoreSession();
$writer = new \Zend\Log\Writer\Stream(BP. '/var/log/logfile2.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info(print_r($session->getUserBike(), true));
?>
<div class="amfinder-common-wrapper amfinder-<?php echo $block->escapeHtml($block->getFinder()->getTemplate()); ?> <?php echo $block->getHideClassName() ? 'amfinder-hide' : ''; ?>"
id="<?php echo 'amfinder_'. (int) $block->getFinder()->getId(); ?>"
location="<?php echo $block->escapeHtml($block->getLocation()); ?>">
<form method="post" action="/garage/index/search">
<!-- etc. -->
<button class="button action primary"
name="userbike"
value="1"
title="<?php echo $block->escapeHtml(__('Use My Bike Instead')); ?>"
type="submit">
<?php echo $block->escapeHtml(__('Use My Bike Instead')); ?>
</button>
</form>
</div>
Clicking the button creates logfile.log which shows my value to be 1. However, after the page refreshes, logfile2.log is empty. It seems it works but then doesn't?
My session stuff:
<?php
namespace Vendor\Module\Block;
class Garage extends Template
{
protected $_coreSession;
public function __construct(
# etc.
\Magento\Framework\Session\SessionManagerInterface $coreSession
)
{
$this->_coreSession = $coreSession;
# etc.
}
public function getCoreSession()
{
return $this->_coreSession;
}
}
How can I get the session values correctly so that they persist after page refresh? What is wrong with my current code?