1010use Setono \SyliusRestockNotificationPlugin \Form \Type \RestockNotificationShopRequestType ;
1111use Setono \SyliusRestockNotificationPlugin \Model \RestockNotificationRequestInterface ;
1212use Symfony \Component \Form \FormFactoryInterface ;
13+ use Symfony \Component \HttpFoundation \JsonResponse ;
1314use Symfony \Component \HttpFoundation \RedirectResponse ;
1415use Symfony \Component \HttpFoundation \Request ;
1516use Symfony \Component \HttpFoundation \Session \Session ;
@@ -29,9 +30,12 @@ public function __construct(
2930 $ this ->managerRegistry = $ managerRegistry ;
3031 }
3132
32- public function __invoke (Request $ request ): RedirectResponse
33+ public function __invoke (Request $ request ): RedirectResponse | JsonResponse
3334 {
34- $ form = $ this ->formFactory ->create (RestockNotificationShopRequestType::class, $ this ->restockNotificationRequestFactory ->createWithChannelAndLocaleContext ());
35+ $ form = $ this ->formFactory ->create (
36+ RestockNotificationShopRequestType::class,
37+ $ this ->restockNotificationRequestFactory ->createWithChannelAndLocaleContext (),
38+ );
3539 $ form ->handleRequest ($ request );
3640
3741 if ($ form ->isSubmitted () && $ form ->isValid ()) {
@@ -43,13 +47,31 @@ public function __invoke(Request $request): RedirectResponse
4347 $ manager ->persist ($ data );
4448 $ manager ->flush ();
4549
50+ if ($ request ->isXmlHttpRequest ()) {
51+ return new JsonResponse ([
52+ 'success ' => true ,
53+ ]);
54+ }
55+
4656 self ::addFlash ($ request , 'success ' , 'setono_sylius_restock_notification.restock_notification_request_created ' );
4757
4858 return self ::createRedirect ($ request , $ this ->urlGenerator ->generate ('sylius_shop_product_show ' , [
4959 'slug ' => $ data ->getProductVariant ()?->getProduct()?->getSlug(),
5060 ]));
5161 }
5262
63+ if ($ request ->isXmlHttpRequest ()) {
64+ $ errors = [];
65+ foreach ($ form ->getErrors (true ) as $ error ) {
66+ $ errors [] = $ error ->getMessage ();
67+ }
68+
69+ return new JsonResponse ([
70+ 'success ' => false ,
71+ 'errors ' => $ errors ,
72+ ]);
73+ }
74+
5375 self ::addFlash ($ request , 'error ' , 'setono_sylius_restock_notification.restock_notification_request_failed ' );
5476
5577 return self ::createRedirect ($ request , $ this ->urlGenerator ->generate ('sylius_shop_homepage ' ));
0 commit comments