Hi
I made a custom hook on Quote to make two calculations. I want to know how much of the products are recurring and how much is one-off. For this I also added a recurring property to Product. Now it does work sort of, but for some reason on initial save my hook makes the products saved twice. Lets say I have in the quote 2x Mobile Phones, 2x Subsctiptions so 4 items in total. When Saved I have a list of: 2x Mobile Phones, 2x Subscriptions, 2x Mobile Phones, 2x Subscriptions, so 8 items in total.
I thoought I should probably make my afterSave hook a beforeSave hook instead. But since it is not saved I do not know how I can retrieve a list of QuoteItems related to the Quote.
Here is my code for afterSave located at: /custom/Espo/Custom/Hooks/Quote/UpdateQuoteTotals.php
Question is how do I get the $items in beforeSave?
I made a custom hook on Quote to make two calculations. I want to know how much of the products are recurring and how much is one-off. For this I also added a recurring property to Product. Now it does work sort of, but for some reason on initial save my hook makes the products saved twice. Lets say I have in the quote 2x Mobile Phones, 2x Subsctiptions so 4 items in total. When Saved I have a list of: 2x Mobile Phones, 2x Subscriptions, 2x Mobile Phones, 2x Subscriptions, so 8 items in total.
I thoought I should probably make my afterSave hook a beforeSave hook instead. But since it is not saved I do not know how I can retrieve a list of QuoteItems related to the Quote.
Here is my code for afterSave located at: /custom/Espo/Custom/Hooks/Quote/UpdateQuoteTotals.php
Question is how do I get the $items in beforeSave?
Code:
<?php
namespace Espo\Custom\Hooks\Quote;
use Espo\ORM\Entity;
class UpdateQuoteTotals extends \Espo\Core\Hooks\Base {
public function beforeSave(Entity $entity, array $options): void {
error_log("beforeSave");
}
public function afterSave(Entity $entity, array $options = array()) {
error_log("afterSave");
$entityManager = $this->getEntityManager();
$recurringTotal = 0;
$initialTotal = 0;
$items = $entityManager
->getRDBRepository("QuoteItem")
->where([ // where clause
'quoteId' => $entity->get('id')
])
->find();
foreach ($items as $item) {
$product = $entityManager->getEntity("Product", $item->get('productId'));
if ($product->get('recurring')) {
$recurringTotal += $item->get("amount");
}
else {
$initialTotal += $item->get("amount");
}
}
$entity->set("amountRecurring", $recurringTotal);
$entity->set("amountInitial", $initialTotal);
$entityManager->saveEntity($entity, ['skipHooks' => true]);
}
}
?>
​

Comment