3

I am following the Magento documentation to add some validation before creating the order (http://devdocs.magento.com/guides/v2.1/howdoi/checkout/checkout_order.html) but I want to do the validation in server side:

1. Create the validator: /view/frontend/web/js/model/custom-validation.js

define(
    ['jquery'],
    function ($) {
        'use strict';
        return {
            /**
             * Validate something
             *
             * @returns {boolean}
             */
            validate: function() {
                //Put your validation logic here
                var customurl = '<?php echo $block->getUrl('module/Controller/Index/Validator');?>';
                $.ajax({
                    url: customurl,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        customdata1: 'test1',
                        customdata2: 'test2',
                    },
                complete: function(response) {             
                    var validation = response.responseJSON.success;
                    console.log(response);
                    if (validation == true){
                        return true;
                    }  
                },
                error: function (xhr, status, errorThrown) {
                    console.log('Error happens. Try again.');
                }
                });
                return false;
            }
        }
    }
);

2. Add validator to the validators pool: /view/frontend/web/js/view/add-validator.js

define(
    [
        'uiComponent',
        'Magento_Checkout/js/model/payment/additional-validators',
        '<your_module>/js/model/custom-validation.js'
    ],
    function (Component, additionalValidators, yourValidator) {
        'use strict';
        additionalValidators.registerValidator(yourValidator);
        return Component.extend({});
    }
);

3. Own controller: vendor/module/Controller/Index/Validator.php

<?php

namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\Result\JsonFactory;
use \Magento\Framework\HTTP\ZendClientFactory;

class Validator extends \Magento\Framework\App\Action\Action
{

    protected $resultPageFactory;

    protected $resultJsonFactory; 

    protected $httpClientFactory;

    /**
     * @param Context     $context
     * @param PageFactory $resultPageFactory
     * @param JsonFactory $resultJsonFactory,
     * @param HttpClientFactory $httpClientFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        JsonFactory $resultJsonFactory,
        HttpClientFactory $httpClientFactory
        )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->resultJsonFactory = $resultJsonFactory; 
        $this->httpClientFactory = $httpClientFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
        $backUrl = $this->_url->getUrl('customer/account');//You can give any url, or current page url


        //if controller request is not ajax type
        if (!$this->getRequest()->isAjax()) {
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setUrl($backUrl);
            return $resultRedirect;
        }

        //Get Params
        $customData = $this->getRequest()->getParam('customdata1', false);

        if ($this->getRequest()->isAjax())) 
        {
            $resultJson = $this->resultJsonFactory->create();

            /*Get information from other API*/
            try {
                $url = 'URL_TO_CUSTOM_API';
                $token = 'TOKEN_API';
                $data['parameter'] = $customData;

                $client = $this->_httpClientFactory->create();
                $client->setUri($url);
                $client->setConfig(['timeout' => 300]);
                $client->setHeaders(['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer '.$token]);
                $client->setMethod(\Zend_Http_Client::GET);
                $client->setRawData(json_encode($data));

                try {
                    $responseBody = $client->request()->getBody();
                    $responseJson = json_decode($responseBody, true);
                    /*
                    echo '<pre>';
                    print_r($responseBody);
                    die;*/
                    $resultJson->setData([
                       'success' => true,
                       'error' => false}]);

                } catch (\Exception $e) {
                    return $resultJson->setData([
                    'success' => false,
                    'error' => $e->getMessage()
                    ]);
                }

                /*$resultJson->setData([
                    'success' => true],
                    'error' => false);*/

            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                return $resultJson->setData([
                    'success' => false,
                    'error' => $e->getMessage()
                    ]);
            } catch (\Exception $e) {
                return $resultJson->setData([
                    'success' => false,
                    'error' => $e->getMessage()
                    ]);
            }


        }
        //return $resultJson;
    }
}

I'm on the right path? Thanks

0

I know is late but just for the record, an ajax call is asynchronous so in your example you will always return false.

You can try using promises but I am not sure how they can fit in the provided validators.

PS: Also this point is left: https://devdocs.magento.com/guides/v2.2/howdoi/checkout/checkout_order.html#layout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.