Magento 2.2 – How to Call a Controller Action Inside Another Controller

actioncontrollersmagento2magento2.2

I have a form with text fields and one image file . I want to upload the image and next save the form information in the database.
I have two actions : Create and UploadImage.
I want to call the execute method of UploadImage action in the execute method of Create.
The idea is upload the file first and next create the fields.

It is possible to inject the UploadAction in my Create and call the execute method of UploadAction in the execute method of Create?

Best Answer

I's not a good idea to call controller actions inside other controller actions. Not sure if it's even possible. May be.
But here is what you can do.
Create a separate class that handles the image upload that should not me a controller.
This class should receive some parameters and work with those.
In the UploadImage controller, read the files that are being uploaded and pass them to your class as the parameters I mentioned above.
This way you can use your upload class in the UploadImage controller and in any other controller you like.