XF 2.0 How to pass a variable to PAGE_CONTAINER template

AndyB

Well-known member
In my Banner add-on, I would like to pass a variable from PHP code to the PAGE_CONTAINER template.

The goal is to display a random image in the header with a different image being display upon each page load.

For example I pass from PHP a variable to the forum_list template using this code:

PHP:
<?php

namespace Andy\Banner\XF\Pub\Controller;

use XF\Mvc\ParameterBag;

class Forum extends XFCP_Forum
{
	public function actionList(ParameterBag $params)
	{
		//########################################
		// show banner in forum_list
		//########################################

		// get parent
		$parent = parent::actionList($params);
	
		// get visitor
		$visitor = \XF::visitor();				

		// check for user group permission
		if (!$visitor->hasPermission('banner', 'view_forum_list_top') AND !$visitor->hasPermission('banner', 'view_forum_list_bottom'))
		{
			return $parent;
		}

		// get options
		$options = \XF::options();
		
		// get options from Admin CP -> Options -> Banner -> Limit
		$limit = $options->bannerLimit;

		// get db
		$db = \XF::db();		
		
		// run query
		$banners = $db->fetchAll("
		SELECT image_url,
		link,
		target
		FROM xf_andy_banner
		WHERE active = 1
		ORDER BY RAND()
		LIMIT ?
		", $limit);

		// return if no banners
		if (empty($banners))
		{
			return $parent;
		}

		$parent->setParams([
		   'banners' => $banners
		]);	

		return $parent;
	}

Thank you.
 
Last edited:

AndyB

Well-known member
It appears the PAGE_CONTAINER doesn't have a $params variable we can set in the PHP code.

The forum_list template has a $params variable and is set like this:

PHP:
		$parent->setParams([
		   'banners' => $banners
		]);

But how can we pass a variable to the PAGE_CONTAINER template?
 

AndyB

Well-known member
Thank you, Jeremy. That worked perfectly.

1514675478479.png

PHP:
<?php

namespace Andy\Banner;

class Listener
{
    public static function appPubRenderPage(
        \XF\Pub\App $app,
        array &$params,
        \XF\Mvc\Reply\AbstractReply $reply,
        \XF\Mvc\Renderer\AbstractRenderer $renderer
    ) 
	{
		// get options
		$options = \XF::options();
		
		// get options from Admin CP -> Options -> Banner -> Limit
		$limit = $options->bannerLimit;
		
		// get db
		$db = \XF::db();		
		
		// run query
		$banners = $db->fetchAll("
		SELECT *
		FROM xf_andy_banner
		ORDER BY RAND()
		LIMIT ?
		", $limit);

		// update params
		$params['banners'] = $banners;
    }
}
 

Scandal

Well-known member
Hello all! :)
This thread is very useful and thanks for sharing the solution! I used it! :)

I have a similar question too.
Is there any way to pass a $param on every widget template instead of the PAGE_CONTAINER?

I want to pass a param from \XF\Mvc\Reply\AbstractReply $reply->getParam('test') (if exists), to any widget of the loaded page so the widget template could use it.
 
Top