How to get previous attribute value in beforeSave or afterSave Hook

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • czcpf
    Senior Member
    • Aug 2022
    • 162

    #1

    How to get previous attribute value in beforeSave or afterSave Hook

    Hello,

    In a custom Hook, how would one get the previous attribute value in afterSave and/or beforeSave hook?

    Example:

    Let's say in UI someone changes the entity field 'myattribute' from 4 to 5 and hits save.

    What I would like to achieve,

    Using beforeSave and/or afterSave I would like to know if 'myattribute' has changed, what was the previous value of it and what is the new value of it.



    MyCustomHook

    PHP Code:
    public function afterSave(Entity $entity, array $options): void
    {

    if( 
    $entity->isAttributeChanged('myattribute') ) {
    //get previous attribute ?
    //$entity->getPreviousAttribute('myattribute);

    }

    }
    ​ 

  • item
    Active Community Member
    • Mar 2017
    • 1555

    #2
    Hi,
    check on github. "fetched"




    ​​



    ​​
    Last edited by item; 08-07-2023, 07:35 PM.
    If you could give the project a star on GitHub. EspoCrm believe our work truly deserves more recognition. Thanks.​

    Comment


    • czcpf
      czcpf commented
      Editing a comment
      Thanks. So getFetched is doing what exactly? Is that the parameter value after saving to db or before saving to db or what?
  • czcpf
    Senior Member
    • Aug 2022
    • 162

    #3
    Thanks item for pointing me in the right direction. I just tested the custom hook and it worked as expected. Below is a code snippet to get the old and new fileId attribute in a afterSave hook.


    PHP Code:
    public function afterSave(Entity $entity, array $options): void {

        if( 
    $entity->isAttributeChanged('fileId') ) {

            
    $currentFileId $entity->get('fileId');
            
    $previousFileId $entity->getFetched('fileId');

            
    $GLOBALS['log']->warning('MyCustomHook.php Espo\Custom\Hooks\Document ',
               [
    'currentFileId'=>$currentFileId,'previousFileId'=>$previousFileId]);

        }

    }
    ​ 

    Comment

    Working...