Skip to content

Instantly share code, notes, and snippets.

@SebSept
Created December 8, 2020 10:39
Show Gist options
  • Save SebSept/982e016f60ba9383be5eb30be3e17826 to your computer and use it in GitHub Desktop.
Save SebSept/982e016f60ba9383be5eb30be3e17826 to your computer and use it in GitHub Desktop.
first implementation (wip) of an ajax admin controller. (for review).
<?php
namespace SebSept\Adminproductquantities\Controller;
use PrestaShopBundle\Api\Stock\Movement;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use PrestaShopBundle\Entity\ProductIdentity;
use PrestaShopBundle\Entity\Repository\StockRepository;
use PrestaShopBundle\Service\ProductService;
use Symfony\Component\HttpFoundation\JsonResponse;
class Update extends FrameworkBundleAdminController
{
/**
* Update Product stock
*
* (pas de gestion des déclinaisons, c'est normal)
*
* @param int $quantity new quantity (absolute value)
* @param int $id_product
*
* @return JsonResponse
*/
public function update(int $quantity, int $id_product)
{
try {
$product_provider = $this->get('prestashop.adapter.data_provider.product');
$stock_repository = $this->get('prestashop.core.api.stock.repository');
$delta = $quantity - (int)$product_provider->getQuantity($id_product);
$stock_data = $stock_repository->updateStock(new Movement(new ProductIdentity($id_product), $delta));
$fetched_quantity = $stock_data['product_available_quantity'] ?? 'no-data';
if ($quantity !== $fetched_quantity)
{
throw new \Exception("Echec mise à jour stock : quantité voulue et recupérée differentes. [$quantity] vs [$fetched_quantity]");
}
}
catch (\Exception $exception)
{
return new JsonResponse(['error' => $exception->getMessage()]);
}
// @todo implement reponse positive
return new JsonResponse(['q' => $quantity, 'id' => $id_product]);
}
}
@SebSept
Copy link
Author

SebSept commented Jan 11, 2022

Hello,
Today, to my knowledge, there is no way to access services of the backoffice in the front office.
Sorry.
This will come later, I suppose.

@CristianRojasss
Copy link

Hello friend, I found this article https://blog.floriancourgey.com/2018/05/how-to-work-with-the-symfony-kernel-anywhere-in-prestashop-1-7/, which indicates how to instantiate a symfony service container inside a module front controller (legacy). With the symfony service container I just need to run MyModule::getContainer()->get('prestashop.core.api.stock.repository') to get an instance of StockRepository. Greetings :)

@SebSept
Copy link
Author

SebSept commented Jan 12, 2022

Thanks for the feedback 😄
👍 For sure, booting the kernel and grab it, but I suppose performances is going to suffer from that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment