Custom Alert OptOut

Lukas W.

Well-known member
Hey,

I'm currently trying to figure out how to optout custom alert based on user preferences, but it isn't working for some reason...

My profile field in the alert preferences looks like to following:

HTML:
<li><input type="hidden" name="alertSet[ResourceToRPG_invite]" value="1" />
        <label><input type="checkbox" value="1" name="alert[ResourceToRPG_invite]" {xen:checked "!{$alertOptOuts.ResourceToRPG_invite}"} /> {xen:phrase RTR_rpg_invitation}</label>
        <p class="hint">{xen:phrase RTR_adds_you_to_rpg}</p>
    </li>

The content type in the database is ResourceToRPG.

I'm sending the alert with the following code:
PHP:
XenForo_Model_Alert::alert(
       $user,
        $visitor->getUserID(),
        $visitor->toArray()['username'],
       'ResourceToRPG',
       $resource['resource_id'],
       'invite'
);

The setting is stored in the database correctly, but the user receives the alert no matter if he decided to opt it out or not... Any ideas?
 
I can't see anything obviously wrong at first glance with the opt out. If the user has an opt out set in the table for that content type and action then it should work.

However it would be wise to review your alert code there and use of the visitor object.

Array dereferencing (e.g. $visitor->toArray()['username']) wasn't made available in PHP 5.4. Although most people are on higher PHP versions now, the minimum requirements for XF1 are PHP 5.2.x so that code may not work for all users (if you are releasing as an add on).

To access the user ID and username you can use the magic get method:

PHP:
$userId = $visitor->user_id;
$username = $visitor->username;

Or, just as valid, is to use the visitor object just like any other array as it implements ArrayAccess.
 
I'm running on php 5.6 and didn't plan to release it as an AddOn, but I've changed it just to be on the safe side, thank you!

The problem is still persistent however, so if anyone can see the problem, I'd be glad to have it solved.
 
I don't know if it's my bad because I forgot it or if something is not working. However I 'fixed' the problem the following way:

PHP:
if(XenForo_Model_Alert::userReceivesAlert(array('user_id' => $user), 'rtr', 'remove')) {
    XenForo_Model_Alert::alert(
        $user,
        $visitor->user_id,
        $visitor->username,
        'rtr',
        $resource['resource_id'],
        'remove'
    );
}

Is it intentional that I have to wrap the alert function in the if-statement? If so, is there a more beautiful solution to do this? Seems kinda ugly.
 
Heh yeah that is intentional. I did wonder if you had that but I assumed you had.

That's the correct way. You'll see examples of it thoughout XF.
 
Back
Top Bottom