Not planned Option to disable __preSave()/__postSave() from running when record is created or updated

asprin

Active member
Let's say as part of an addon, I've a custom entity created. In the structure class, I've declared either a __preSave() or a __postSave() or both.

In certain scenarios, there would be a need to not run these functions (use case shown below).

PHP:
protected function __preSave()
{
    $this->updated_by = \XF::visitor()->user_id;
}

Now, I've a part of code that is updating value of a row and in this particular case, I do not want the __preSave() to run.
PHP:
$foo = $this->finder('Vendor\MyAddon:Foo')->where('id', 1)->fetchOne();
if($foo)
{
    $foo->bar = 'something gets updated here';
    $foo->save(); // <--- now I would like to update this record but not run the __preSave()
}

I'm thinking something along the lines of the following:
PHP:
$foo = $this->finder('Vendor\MyAddon:Foo')->where('id', 1)->fetchOne();
if($foo)
{
    $foo->bar = 'something gets updated here';
    $foo->save(false); // <--- false to indicate whether the pre or post functions should run, will be true by default
}

Thoughts?
 
Upvote 0
This suggestion has been closed. Votes are no longer accepted.
You can accomplish this with custom options:
PHP:
$structure->options = [
    'update_updated_by' => true,
];

Then:
PHP:
protected function __preSave()
{
    if ($this->getOption('update_updated_by'))
    {
        $this->updated_by = \XF::visitor()->user_id;
    }
}

Then:
PHP:
$foo = $this->finder('Vendor\MyAddon:Foo')->where('id', 1)->fetchOne();
if($foo)
{
    $foo->bar = 'something gets updated here';
    $foo->setOption('update_updated_by', false);
    $foo->save();
}
 
Agreed.

There are ways to achieve this in the code already.

Another approach is doing:

PHP:
$foo->fastUpdate('bar', 'something gets updated here');

This essentially performs a direct DB update rather than going through the full Entity save routine.
 
Back
Top Bottom