Where am I going wrong with this simple addon?

nrep

Well-known member
I'm trying to extend \XF\Service\User\Welcome.php so that I can add additional placeholders for the boardURL and boardTitle. This is my first proper XF2 addon and I'm a novice at coding.

For the moment, the addon just uses a simple string for the {boardURL} placeholder so I can see if this would work.

So far, I've created a file at \src\addons\test\welcome\XF\Service\User\Welcome.php with the following contents:

PHP:
<?php

namespace test\welcome\XF\Service\User;

use XF\Entity\User;
use XF\Language;

class Welcome extends XFCP_Welcome
{
   
    protected function prepareTokens($escape = true)
    {
        $tokens = [
            '{name}' => $this->user->username,
            '{email}' => $this->user->email,
            '{id}' => $this->user->user_id,
            '{boardURL}' => 'http://www.testurl.com'
        ];

        if ($escape)
        {
            array_walk($tokens, function(&$value)
            {
                if (is_string($value))
                {
                    $value = htmlspecialchars($value);
                }
            });
        }

        return $tokens;
    }
   
}

I then created a class extension with base class: XF\Service\User\Welcome and extension class: test\welcome\XF\Service\User\Welcome

I thought that this would work, but it seems that if I add the {boardURL} placeholder in a welcome e-mail message, it doesn't get set to the 'http://www.testurl.com' value as I expected.

Can anyone point me in the right direction please, as I'm sure I've made a mistake (or more!) in my coding.
 
If you change the value of any of the other things, do those replacements take effect?

If not, then it suggests your class extension isn't working correctly.

Also bear in mind that although the code as you've written it should work, it isn't the correct way to extend an existing function. As it stands when it works you'll be overwriting that function rather than extending to it, which can be problematic.
PHP:
    protected function prepareTokens($escape = true)
    {
        $tokens = parent::prepareTokens($escape);

        $tokens['{boardURL}'] = 'http://www.testurl.com';

        return $tokens;
    }
 
Many thanks for the reply Chris - that's a much better way of doing it. I've just used the code you wrote above and it works... hurrah :). I'll work on modifying it to use options in the control panel.

Really appreciate the help on this :D.
 
Top Bottom