XF 2.1 Is it possible to know the caller inside entity's _preSave() function?

asprin

Active member
There are two ways that I'm allowing an update of a custom entity.

1. A logged in user with appropriate permission manually updating it via a form submit
2. Via a enqueueLater() job

Now I've a _preSave() defined on the entity's class. But I'm wondering if inside this function I know how how the entity was updated.

PHP:
protected function _preSave()
{
    if($this->isUpdate())
    {
        // figure out if a user submitted a form
        // or the job has triggered the update
        // so tha I can do the following
        if(<the update happened because of the form submitted by the user>)
        {
            $this->updated_by = \XF::visitor()->user_id;
            $this->updated_on = \XF::$time;
        }
    }
}

In other words, I don't want to populate updated_by and updated_on if the update happened via the job.

Is this possible? Maybe checking the stack trace??
 
Can’t you just update those fields in the controller when the form is submitted?
Then I'll have to do it on every controller action that handles form submit. The addon I'm building is significant and there are a number of places where update on the entity happens. Thus, I was hoping to do it at a single place instead of multiple places.
 
Then I'll have to do it on every controller action that handles form submit. The addon I'm building is significant and there are a number of places where update on the entity happens. Thus, I was hoping to do it at a single place instead of multiple places.
You can move the code into a service and call it from the controller. This way you will not duplicate code and follow the MVC architecture
 
In nearly every controller is a check for isPost().
No, no. I meant dentifying if there was post inside the entity's preSave function and not the public controller action.
To inject in multiple controllers you can use a trait.
That's the first I'm hearing of. Let me see if I can find some info it.

You can move the code into a service and call it from the controller
I don't have much experience on services. Is there an example out there?
 
Last edited:
Back
Top Bottom