Custom Fields
Re-Envisioned
Support General Check witch field has been updated

  • Creator
    Topic
  • #3706
    nicolas
    Participant

    Hi, is there a way to know if a field was updated by the user and get the name of that field?

    I would like to used this information for logging purposes. Let’s say field X was updated, I want to write down in a log format “Field X was updated by USER Y”

    Thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • Author
    Replies
  • #3711
    Anh Tran
    Keymaster

    Hi Nicolas,

    I think you can hook to rwmb_value like this:

    add_filter( 'rwmb_value', 'prefix_check_field_change', 20, 3 );
    function prefix_check_field_change( $new, $field, $old ) {
        if ( $new !== $old ) {
            // Log
        }
        return $new; // Do not change the value
    }
    #3717
    nicolas
    Participant

    Thank Anh for the reply, it’s working great.

    There is one more thing that I’m trying to accomplish and I can’t with this filter. At least I don’t know how to do if it’s possible.

    If I write to the log in the conditional statement, I will get one entry per field. Was I want is one entry per transaction (one per post save). So in order to write the all the changes in one log entry block, I would need a way to return the results of this filter and THEN write to the log. But I don’t know how to do that. You have any ideas?

    Thanks again

    #3718
    Anh Tran
    Keymaster

    Hi Nicolas,

    You can store the changed fields and then process the log when the post is saved. Here is what I suggest:

    class MB_Log {
        protected $fields = array();
    
        public function __construct() {
            add_filter( 'rwmb_value', array( $this, 'check_field_change' ), 20, 3 );
            add_action( 'rwmb_after_save_post', array( $this, 'log' ) );
        }
    
        public function check_field_change( $new, $field, $old ) {
            if ( $new !== $old ) {
                $this->fields[] = $field;
            }
    
            return $new; // Do not change the value
        }
    
        public function log() {
            foreach ( $this->fields as $field ) {
                // Log
            }
        }
    }
    #3730
    nicolas
    Participant

    Thanks again Anh, working great with a little modification.

    Hooking into rwmb_after_save_post created a double log input. I changed the hook to WP save_post and it is working as expected.

    Thanks again for your help.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Check witch field has been updated’ is closed to new replies.