Back to Audit log Support

dave22269
dave22269

Hi Jacob. Loving your plugin. One small issue for me. I have fields in my database set to decimal, and the fields are rendered as decimal in the forms. When I save a form without making ANY changes, the following log is created... total_fee changed from 180.00 to 180, discount changed from 0.00 to 0, addon changed from 0.00 to 0.

Any chance you could fix this? Below is my fix, but maybe you have a better solution?

public function logChangesAfterUpdate() { $attributes = [];

    /** @var array $dirtyAttributes */
    $dirtyAttributes = $this->getDirty();

    /** @var array $originalAttributes */
    $originalAttributes = $this->getOriginal();

    /** @var array $ignoreFieldsLogbook */
    $ignoreFieldsLogbook = $this->ignoreFieldsLogbook ?? ['updated_at'];

    foreach ($dirtyAttributes as $column => $newValue) {
        if (in_array($column, $ignoreFieldsLogbook)) {
            continue; //ignore field
        }

        if ($newValue == $originalAttributes[$column]) {
           continue; // ignore field. Possible false dirty. E.g. "1.00 == 1" // CHANGE
        }

        /** @var Attribute $attributeChanged */
        $attributeChanged = new Attribute([
            'column' => $column,
            'old' => $originalAttributes[$column] ?? null,
            'new' => $newValue,
        ]);

        $attributes[] = $attributeChanged->getData();
    }

    // do not log if no changes // CHANGE
    if (count($attributes))
    { 
        $changes = new Changes([
            'type' => Changes::TYPE_UPDATED,
            'changedAttributes' => $attributes
        ]);

        $this->createLogBookLogItem($changes);
    }

    $this->createLogBookLogItem($changes);

}

Thank-you

dave22269
dave22269

Oops. The last "$this->createLogBookLogItem($changes);" should not be there :)

Jacob
Jacob

Hi Dave,

Eloquent converts .0 to an integer. To prevent this from happening add the following to your model:

protected $casts = [
    'total_fee' => 'float'
];

Add casts for all your decimal fields and your problem should go away :)

Last updated

dave22269
dave22269

Jacob. You are One Smart Cookie. You've knocked my somewhat embarrassing attempt to fix the problem into a cocked hat. The problem has indeed fled the scene. Just out of interest, did you consider piggy-backing the core Revisionable Trait (https://octobercms.com/docs/database/traits#revisionable)? If you did consider it, I would be interested in the reasons why you did not. No sweat if you have a million other things to do. Cheers.

Jacob
Jacob

I didn't know it existed (Lol), but my plugin gives more customisation than the default trait. You can specify which fields are not stored in the database and it adds a formwidget where you can see the changes of the model with the changes from relations of that model. I made this plugin for my own project and I thought maybe other people will like it :)

1-5 of 5