XF 2.3 How to override Option value on save?

nopoles613

New member
Hello, we have a custom plugin we've built that uses a Code Event Listener to listen for the event entity_post_save on XF\Entity\Option objects. The Event Listener uses a callback to trigger some checks and updates when certain settings in our plugin are changed. This all works as expected.

However, there are cases where we'd like to change the value of the Option entity from the event listener.

Our listener receives the XF\Entity\Option $entity, and I've tried a half dozen ways to override $entity's "option_value". The closest I got was this, which seems to cause an internal event loop and never returns or saves the desired value:

$entity->set('option_value', 'New Value Here', ['forceSet' => true]);
$entity->save();

What's the best way to override the Option value from a code listener?

Thank you
 
You can likely use option validation callbacks instead, which pass the value by reference and can also perform other changes as desired:

PHP:
<?php

namespace Your\AddOn\Option;

use XF\Entity\Option;

class SomeOption
{
    public static function verifyOption(&$value, Option $option, string $optionId): bool
    {
        $value = 'newValue';

        return true;
    }
}
 
You can likely use option validation callbacks instead, which pass the value by reference and can also perform other changes as desired:
From the sounds of the OP, their addon might be checking multiple different settings, and/or core XF settings which can't be edited to contain a validator.

---

Hello, we have a custom plugin we've built that uses a Code Event Listener to listen for the event entity_post_save on XF\Entity\Option objects. The Event Listener uses a callback to trigger some checks and updates when certain settings in our plugin are changed. This all works as expected.

However, there are cases where we'd like to change the value of the Option entity from the event listener.
I would recommend switching the event listener for a full class Option extends XFCP_Option and hooking _preSave(), something like this:

PHP:
protected function _preSave()
{
    parent::_preSave();
    
    // Insert your option checks here
    
    $this->option_value = $override;
    $yourCustomEntity->yourField = $override;
    $this->addCascadedSave($yourCustomEntity);
}

This is all entirely untested and pseudocode but hopefully it makes sense to you :)
 
Back
Top Bottom