Duplicating an Invoice in a Logic Hook

Hey,

I found an old reference to a way to duplicate records using logic hooks as follows:

$new_account = BeanFactory::getBean('Accounts', $original_account_id);
    $new_account->id = create_guid();
    $new_account->new_with_id = true;

    //set values
    $new_account->name = 'Hello World';
    $new_account->save();

Applying this to AOS_Invoices using the following gives me an issue where the new invoice is created without associated line items, I am assuming that this method only maintains links to Contact and Account because they have a link field in the bean.

$current_id = $bean->fetched_row['id'];
		            $new_invoice = BeanFactory::getBean('AOS_Invoices', $current_id);
		            $new_invoice->id = create_guid();
    			    $new_invoice->new_with_id = true;
                            ....
                            $new_invoice->save();

Does anyone have any suggestions as to how I might bring across the line items as well? I have thought about iterating through them and duplicating/linking them to the new invoice however as Line Items is not a standard module I am unsure of how to do this.

Cheers for any advice,

Sam

1 Like

I had a thought, is there a way to use the built in actions from the action menu (i.e. Duplicate) programmatically? I could call the Duplicate action in the logic hook and then assign any values that need to change. I had a search around and haven’t found anyone doing this that I can see.

Thanks again,

Sam

Hi,
Invoice module is bit different then sugar’s predefined modules. If you look at duplicate functionality, you will find that it is a basically edit view
without record id.

Have a look at action_editview function of controller.php - modules\AOS_Invoices\controller.php
Also check Save function of AOS_Invoices class. - modules\AOS_Invoices\AOS_Invoices.php

You have to learn from both functions to create duplicate invoice.

Thanks and Regards,
Alpesh Savaliya

Hi,

I had looked at these functions previously but I am still a bit green when it comes to PHP and I had assumed that there must be something I was missing (some further function) that actually created the duplicate. From what you have said I should be able to call a function which mimics the controller function to create a duplicate, I will have a go at it, thanks again for the advice!

Sam

Just putting this here incase anyone attempts something similar in future.

I had to give up on using the same functionality as the Duplicate button as I needed to be able to run the logic hook over a number of invoices in a loop. The most effective way I could find was to reuse a bunch of the code in the converToInvoice.php file (modules/AOS_Quotes/converToInvoice.php). Retrieve the invoices using SQL and fill the new invoice with populateFromRow().

If anyone would like a copy of the logic hook for future reference just reply here or shoot me an email at partners@hnsoftwareconsulting.com

Regards,

Sam