XF 2.1 Custom widget

Lee

Well-known member
Looking for some advice,

I want to build a widget that allows me to (in the sidebar) display a list of users browsing the node.

If visiting node.id x > add to the online list.

Would this be easy to implement?

Any guides to show how to create a new widget?
 

Lawrence

Well-known member
You will need to create an add-on as you will need a new widget definition that includes the widgets definition class. An example widget definition class: Lee\Widget\NodeViewers

Widget example:

PHP:
<?php

namespace Lee\Widget;

use XF\Widget\AbstractWidget;

class NodeViewers extends AbstractWidget
{
    protected $defaultOptions = [
        'limit' => 50
    ];

    public function render()
    {
        // grab those viewing node X and send to your widgets template via viewparams
       // your code here
           
        $viewParams = [
            'viewers' => array_slice($viewers, 0, $options['limit']),
            'title' => $this->getTitle(),
            'hasMore' => $hasMore
        ];
        return $this->renderer('lee_widget_node_viewers', $viewParams);
    }

    public function verifyOptions(\XF\Http\Request $request, array &$options, &$error = null)
    {
        $options = $request->filter([
            'limit' => 'uint'
        ]);

        if ($options['limit'] < 1)
        {
            $options['limit'] = 1;
        }
        return true;
    }
}
 

Lawrence

Well-known member
@Lee I forgot to add that you can get the nodeId via the routePath.

Edit: or far easier: $this->options['context']; :whistle:
 
Last edited:
  • Like
Reactions: Lee
Top